xref: /netbsd-src/external/gpl3/gcc.old/dist/libcpp/macro.c (revision 404ee5b9334f618040b6cdef96a0ff35a6fc4636)
1 /* Part of CPP library.  (Macro and #define handling.)
2    Copyright (C) 1986-2017 Free Software Foundation, Inc.
3    Written by Per Bothner, 1994.
4    Based on CCCP program by Paul Rubin, June 1986
5    Adapted to ANSI C, Richard Stallman, Jan 1987
6 
7 This program is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the
9 Free Software Foundation; either version 3, or (at your option) any
10 later version.
11 
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16 
17 You should have received a copy of the GNU General Public License
18 along with this program; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.
20 
21  In other words, you are welcome to use, share and improve this program.
22  You are forbidden to forbid anyone else to use, share and improve
23  what you give them.   Help stamp out software-hoarding!  */
24 
25 #include "config.h"
26 #include "system.h"
27 #include "cpplib.h"
28 #include "internal.h"
29 
30 typedef struct macro_arg macro_arg;
31 /* This structure represents the tokens of a macro argument.  These
32    tokens can be macro themselves, in which case they can be either
33    expanded or unexpanded.  When they are expanded, this data
34    structure keeps both the expanded and unexpanded forms.  */
35 struct macro_arg
36 {
37   const cpp_token **first;	/* First token in unexpanded argument.  */
38   const cpp_token **expanded;	/* Macro-expanded argument.  */
39   const cpp_token *stringified;	/* Stringified argument.  */
40   unsigned int count;		/* # of tokens in argument.  */
41   unsigned int expanded_count;	/* # of tokens in expanded argument.  */
42   source_location *virt_locs;	/* Where virtual locations for
43 				   unexpanded tokens are stored.  */
44   source_location *expanded_virt_locs; /* Where virtual locations for
45 					  expanded tokens are
46 					  stored.  */
47 };
48 
49 /* The kind of macro tokens which the instance of
50    macro_arg_token_iter is supposed to iterate over.  */
51 enum macro_arg_token_kind {
52   MACRO_ARG_TOKEN_NORMAL,
53   /* This is a macro argument token that got transformed into a string
54      litteral, e.g. #foo.  */
55   MACRO_ARG_TOKEN_STRINGIFIED,
56   /* This is a token resulting from the expansion of a macro
57      argument that was itself a macro.  */
58   MACRO_ARG_TOKEN_EXPANDED
59 };
60 
61 /* An iterator over tokens coming from a function-like macro
62    argument.  */
63 typedef struct macro_arg_token_iter macro_arg_token_iter;
64 struct macro_arg_token_iter
65 {
66   /* Whether or not -ftrack-macro-expansion is used.  */
67   bool track_macro_exp_p;
68   /* The kind of token over which we are supposed to iterate.  */
69   enum macro_arg_token_kind kind;
70   /* A pointer to the current token pointed to by the iterator.  */
71   const cpp_token **token_ptr;
72   /* A pointer to the "full" location of the current token.  If
73      -ftrack-macro-expansion is used this location tracks loci across
74      macro expansion.  */
75   const source_location *location_ptr;
76 #if CHECKING_P
77   /* The number of times the iterator went forward. This useful only
78      when checking is enabled.  */
79   size_t num_forwards;
80 #endif
81 };
82 
83 /* Saved data about an identifier being used as a macro argument
84    name.  */
85 struct macro_arg_saved_data {
86   /* The canonical (UTF-8) spelling of this identifier.  */
87   cpp_hashnode *canonical_node;
88   /* The previous value of this identifier.  */
89   union _cpp_hashnode_value value;
90 };
91 
92 /* Macro expansion.  */
93 
94 static int enter_macro_context (cpp_reader *, cpp_hashnode *,
95 				const cpp_token *, source_location);
96 static int builtin_macro (cpp_reader *, cpp_hashnode *,
97 			  source_location, source_location);
98 static void push_ptoken_context (cpp_reader *, cpp_hashnode *, _cpp_buff *,
99 				 const cpp_token **, unsigned int);
100 static void push_extended_tokens_context (cpp_reader *, cpp_hashnode *,
101 					  _cpp_buff *, source_location *,
102 					  const cpp_token **, unsigned int);
103 static _cpp_buff *collect_args (cpp_reader *, const cpp_hashnode *,
104 				_cpp_buff **, unsigned *);
105 static cpp_context *next_context (cpp_reader *);
106 static const cpp_token *padding_token (cpp_reader *, const cpp_token *);
107 static void expand_arg (cpp_reader *, macro_arg *);
108 static const cpp_token *new_string_token (cpp_reader *, uchar *, unsigned int);
109 static const cpp_token *stringify_arg (cpp_reader *, macro_arg *);
110 static void paste_all_tokens (cpp_reader *, const cpp_token *);
111 static bool paste_tokens (cpp_reader *, source_location,
112 			  const cpp_token **, const cpp_token *);
113 static void alloc_expanded_arg_mem (cpp_reader *, macro_arg *, size_t);
114 static void ensure_expanded_arg_room (cpp_reader *, macro_arg *, size_t, size_t *);
115 static void delete_macro_args (_cpp_buff*, unsigned num_args);
116 static void set_arg_token (macro_arg *, const cpp_token *,
117 			   source_location, size_t,
118 			   enum macro_arg_token_kind,
119 			   bool);
120 static const source_location *get_arg_token_location (const macro_arg *,
121 						      enum macro_arg_token_kind);
122 static const cpp_token **arg_token_ptr_at (const macro_arg *,
123 					   size_t,
124 					   enum macro_arg_token_kind,
125 					   source_location **virt_location);
126 
127 static void macro_arg_token_iter_init (macro_arg_token_iter *, bool,
128 				       enum macro_arg_token_kind,
129 				       const macro_arg *,
130 				       const cpp_token **);
131 static const cpp_token *macro_arg_token_iter_get_token
132 (const macro_arg_token_iter *it);
133 static source_location macro_arg_token_iter_get_location
134 (const macro_arg_token_iter *);
135 static void macro_arg_token_iter_forward (macro_arg_token_iter *);
136 static _cpp_buff *tokens_buff_new (cpp_reader *, size_t,
137 				   source_location **);
138 static size_t tokens_buff_count (_cpp_buff *);
139 static const cpp_token **tokens_buff_last_token_ptr (_cpp_buff *);
140 static inline const cpp_token **tokens_buff_put_token_to (const cpp_token **,
141                                                           source_location *,
142                                                           const cpp_token *,
143                                                           source_location,
144                                                           source_location,
145                                                           const line_map_macro *,
146                                                           unsigned int);
147 
148 static const cpp_token **tokens_buff_add_token (_cpp_buff *,
149 						source_location *,
150 						const cpp_token *,
151 						source_location,
152 						source_location,
153 						const line_map_macro *,
154 						unsigned int);
155 static inline void tokens_buff_remove_last_token (_cpp_buff *);
156 static void replace_args (cpp_reader *, cpp_hashnode *, cpp_macro *,
157 			  macro_arg *, source_location);
158 static _cpp_buff *funlike_invocation_p (cpp_reader *, cpp_hashnode *,
159 					_cpp_buff **, unsigned *);
160 static bool create_iso_definition (cpp_reader *, cpp_macro *);
161 
162 /* #define directive parsing and handling.  */
163 
164 static cpp_token *alloc_expansion_token (cpp_reader *, cpp_macro *);
165 static cpp_token *lex_expansion_token (cpp_reader *, cpp_macro *);
166 static bool warn_of_redefinition (cpp_reader *, cpp_hashnode *,
167 				  const cpp_macro *);
168 static bool parse_params (cpp_reader *, cpp_macro *);
169 static void check_trad_stringification (cpp_reader *, const cpp_macro *,
170 					const cpp_string *);
171 static bool reached_end_of_context (cpp_context *);
172 static void consume_next_token_from_context (cpp_reader *pfile,
173 					     const cpp_token **,
174 					     source_location *);
175 static const cpp_token* cpp_get_token_1 (cpp_reader *, source_location *);
176 
177 static cpp_hashnode* macro_of_context (cpp_context *context);
178 
179 static bool in_macro_expansion_p (cpp_reader *pfile);
180 
181 /* Statistical counter tracking the number of macros that got
182    expanded.  */
183 unsigned num_expanded_macros_counter = 0;
184 /* Statistical counter tracking the total number tokens resulting
185    from macro expansion.  */
186 unsigned num_macro_tokens_counter = 0;
187 
188 /* Emits a warning if NODE is a macro defined in the main file that
189    has not been used.  */
190 int
191 _cpp_warn_if_unused_macro (cpp_reader *pfile, cpp_hashnode *node,
192 			   void *v ATTRIBUTE_UNUSED)
193 {
194   if (node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
195     {
196       cpp_macro *macro = node->value.macro;
197 
198       if (!macro->used
199 	  && MAIN_FILE_P (linemap_check_ordinary
200 			    (linemap_lookup (pfile->line_table,
201 					     macro->line))))
202 	cpp_warning_with_line (pfile, CPP_W_UNUSED_MACROS, macro->line, 0,
203 			       "macro \"%s\" is not used", NODE_NAME (node));
204     }
205 
206   return 1;
207 }
208 
209 /* Allocates and returns a CPP_STRING token, containing TEXT of length
210    LEN, after null-terminating it.  TEXT must be in permanent storage.  */
211 static const cpp_token *
212 new_string_token (cpp_reader *pfile, unsigned char *text, unsigned int len)
213 {
214   cpp_token *token = _cpp_temp_token (pfile);
215 
216   text[len] = '\0';
217   token->type = CPP_STRING;
218   token->val.str.len = len;
219   token->val.str.text = text;
220   token->flags = 0;
221   return token;
222 }
223 
224 static const char * const monthnames[] =
225 {
226   "Jan", "Feb", "Mar", "Apr", "May", "Jun",
227   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
228 };
229 
230 static size_t remap_pairs;
231 static char **remap_src;
232 static char **remap_dst;
233 
234 void
235 add_cpp_remap_path (const char *arg)
236 {
237 	const char *arg_dst;
238 	size_t len;
239 
240 	arg_dst = strchr(arg, ':');
241 	if (arg_dst == NULL) {
242 		fprintf(stderr, "Invalid argument for -iremap");
243 		exit(1);
244 	}
245 	len = arg_dst - arg;
246 	++arg_dst;
247 
248 	remap_src = (char **) xrealloc(remap_src, sizeof(char *) * (remap_pairs + 1));
249 	remap_dst = (char **) xrealloc(remap_dst, sizeof(char *) * (remap_pairs + 1));
250 
251 	remap_src[remap_pairs] = (char *) xmalloc(len + 1);
252 	memcpy(remap_src[remap_pairs], arg, len);
253 	remap_src[remap_pairs][len] = '\0';
254 	remap_dst[remap_pairs] = xstrdup(arg_dst);
255 	++remap_pairs;
256 }
257 
258 static const char *
259 cpp_remap_file (const char *arg, char **tmp_name)
260 {
261 	char *result;
262 	size_t i, len;
263 
264 	for (i = 0; i < remap_pairs; ++i) {
265 		len = strlen (remap_src[i]);
266 		if (strncmp (remap_src[i], arg, len))
267 			continue;
268 		if (arg[len] == '\0')
269 			return remap_dst[i];
270 		if (arg[len] != '/')
271 			continue;
272 		arg += len;
273 		len = strlen (remap_dst[i]);
274 		result = (char *) xmalloc (len + strlen (arg) + 1);
275 		memcpy(result, remap_dst[i], len);
276 		strcpy(result + len, arg);
277 		*tmp_name = result;
278 
279 		return result;
280 	}
281 
282 	return arg;
283 }
284 
285 /* Helper function for builtin_macro.  Returns the text generated by
286    a builtin macro. */
287 const uchar *
288 _cpp_builtin_macro_text (cpp_reader *pfile, cpp_hashnode *node,
289 			 source_location loc)
290 {
291   const uchar *result = NULL;
292   linenum_type number = 1;
293 
294   switch (node->value.builtin)
295     {
296     default:
297       cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
298 		 NODE_NAME (node));
299       break;
300 
301     case BT_TIMESTAMP:
302       {
303 	if (CPP_OPTION (pfile, warn_date_time))
304 	  cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
305 		       "reproducible builds", NODE_NAME (node));
306 
307 	cpp_buffer *pbuffer = cpp_get_buffer (pfile);
308 	if (pbuffer->timestamp == NULL)
309 	  {
310 	    /* Initialize timestamp value of the assotiated file. */
311             struct _cpp_file *file = cpp_get_file (pbuffer);
312 	    if (file)
313 	      {
314     		/* Generate __TIMESTAMP__ string, that represents
315 		   the date and time of the last modification
316 		   of the current source file. The string constant
317 		   looks like "Sun Sep 16 01:03:52 1973".  */
318 		struct tm *tb = NULL;
319 		struct stat *st = _cpp_get_file_stat (file);
320 		if (st)
321 		  tb = localtime (&st->st_mtime);
322 		if (tb)
323 		  {
324 		    char *str = asctime (tb);
325 		    size_t len = strlen (str);
326 		    unsigned char *buf = _cpp_unaligned_alloc (pfile, len + 2);
327 		    buf[0] = '"';
328 		    strcpy ((char *) buf + 1, str);
329 		    buf[len] = '"';
330 		    pbuffer->timestamp = buf;
331 		  }
332 		else
333 		  {
334 		    cpp_errno (pfile, CPP_DL_WARNING,
335 			"could not determine file timestamp");
336 		    pbuffer->timestamp = UC"\"??? ??? ?? ??:??:?? ????\"";
337 		  }
338 	      }
339 	  }
340 	result = pbuffer->timestamp;
341       }
342       break;
343     case BT_FILE:
344     case BT_BASE_FILE:
345       {
346 	unsigned int len;
347 	const char *name;
348 	char *tmp_name;
349 	uchar *buf;
350 
351 	if (node->value.builtin == BT_FILE)
352 	  name = linemap_get_expansion_filename (pfile->line_table,
353 						 pfile->line_table->highest_line);
354 	else
355 	  {
356 	    name = _cpp_get_file_name (pfile->main_file);
357 	    if (!name)
358 	      abort ();
359 	  }
360 	tmp_name = NULL;
361 	name = cpp_remap_file (name, &tmp_name);
362 	len = strlen (name);
363 	buf = _cpp_unaligned_alloc (pfile, len * 2 + 3);
364 	result = buf;
365 	*buf = '"';
366 	buf = cpp_quote_string (buf + 1, (const unsigned char *) name, len);
367 	free (tmp_name);
368 	*buf++ = '"';
369 	*buf = '\0';
370       }
371       break;
372 
373     case BT_INCLUDE_LEVEL:
374       /* The line map depth counts the primary source as level 1, but
375 	 historically __INCLUDE_DEPTH__ has called the primary source
376 	 level 0.  */
377       number = pfile->line_table->depth - 1;
378       break;
379 
380     case BT_SPECLINE:
381       /* If __LINE__ is embedded in a macro, it must expand to the
382 	 line of the macro's invocation, not its definition.
383 	 Otherwise things like assert() will not work properly.
384 	 See WG14 N1911, WG21 N4220 sec 6.5, and PR 61861.  */
385       if (CPP_OPTION (pfile, traditional))
386 	loc = pfile->line_table->highest_line;
387       else
388 	loc = linemap_resolve_location (pfile->line_table, loc,
389 					LRK_MACRO_EXPANSION_POINT, NULL);
390       number = linemap_get_expansion_line (pfile->line_table, loc);
391       break;
392 
393       /* __STDC__ has the value 1 under normal circumstances.
394 	 However, if (a) we are in a system header, (b) the option
395 	 stdc_0_in_system_headers is true (set by target config), and
396 	 (c) we are not in strictly conforming mode, then it has the
397 	 value 0.  (b) and (c) are already checked in cpp_init_builtins.  */
398     case BT_STDC:
399       if (cpp_in_system_header (pfile))
400 	number = 0;
401       else
402 	number = 1;
403       break;
404 
405     case BT_DATE:
406     case BT_TIME:
407       if (CPP_OPTION (pfile, warn_date_time))
408 	cpp_warning (pfile, CPP_W_DATE_TIME, "macro \"%s\" might prevent "
409 		     "reproducible builds", NODE_NAME (node));
410       if (pfile->date == NULL)
411 	{
412 	  /* Allocate __DATE__ and __TIME__ strings from permanent
413 	     storage.  We only do this once, and don't generate them
414 	     at init time, because time() and localtime() are very
415 	     slow on some systems.  */
416 	  time_t tt;
417 	  struct tm *tb = NULL;
418 
419 	  /* Set a reproducible timestamp for __DATE__ and __TIME__ macro
420 	     if SOURCE_DATE_EPOCH is defined.  */
421 	  if (pfile->source_date_epoch == (time_t) -2
422 	      && pfile->cb.get_source_date_epoch != NULL)
423 	    pfile->source_date_epoch = pfile->cb.get_source_date_epoch (pfile);
424 
425 	  if (pfile->source_date_epoch >= (time_t) 0)
426 	    tb = gmtime (&pfile->source_date_epoch);
427 	  else
428 	    {
429 	      /* (time_t) -1 is a legitimate value for "number of seconds
430 		 since the Epoch", so we have to do a little dance to
431 		 distinguish that from a genuine error.  */
432 	      errno = 0;
433 	      tt = time (NULL);
434 	      if (tt != (time_t)-1 || errno == 0)
435 		tb = localtime (&tt);
436 	    }
437 
438 	  if (tb)
439 	    {
440 	      pfile->date = _cpp_unaligned_alloc (pfile,
441 						  sizeof ("\"Oct 11 1347\""));
442 	      sprintf ((char *) pfile->date, "\"%s %2d %4d\"",
443 		       monthnames[tb->tm_mon], tb->tm_mday,
444 		       tb->tm_year + 1900);
445 
446 	      pfile->time = _cpp_unaligned_alloc (pfile,
447 						  sizeof ("\"12:34:56\""));
448 	      sprintf ((char *) pfile->time, "\"%02d:%02d:%02d\"",
449 		       tb->tm_hour, tb->tm_min, tb->tm_sec);
450 	    }
451 	  else
452 	    {
453 	      cpp_errno (pfile, CPP_DL_WARNING,
454 			 "could not determine date and time");
455 
456 	      pfile->date = UC"\"??? ?? ????\"";
457 	      pfile->time = UC"\"??:??:??\"";
458 	    }
459 	}
460 
461       if (node->value.builtin == BT_DATE)
462 	result = pfile->date;
463       else
464 	result = pfile->time;
465       break;
466 
467     case BT_COUNTER:
468       if (CPP_OPTION (pfile, directives_only) && pfile->state.in_directive)
469 	cpp_error (pfile, CPP_DL_ERROR,
470 	    "__COUNTER__ expanded inside directive with -fdirectives-only");
471       number = pfile->counter++;
472       break;
473 
474     case BT_HAS_ATTRIBUTE:
475       number = pfile->cb.has_attribute (pfile);
476       break;
477     }
478 
479   if (result == NULL)
480     {
481       /* 21 bytes holds all NUL-terminated unsigned 64-bit numbers.  */
482       result = _cpp_unaligned_alloc (pfile, 21);
483       sprintf ((char *) result, "%u", number);
484     }
485 
486   return result;
487 }
488 
489 /* Convert builtin macros like __FILE__ to a token and push it on the
490    context stack.  Also handles _Pragma, for which a new token may not
491    be created.  Returns 1 if it generates a new token context, 0 to
492    return the token to the caller.  LOC is the location of the expansion
493    point of the macro.  */
494 static int
495 builtin_macro (cpp_reader *pfile, cpp_hashnode *node,
496 	       source_location loc, source_location expand_loc)
497 {
498   const uchar *buf;
499   size_t len;
500   char *nbuf;
501 
502   if (node->value.builtin == BT_PRAGMA)
503     {
504       /* Don't interpret _Pragma within directives.  The standard is
505          not clear on this, but to me this makes most sense.  */
506       if (pfile->state.in_directive)
507 	return 0;
508 
509       return _cpp_do__Pragma (pfile, loc);
510     }
511 
512   buf = _cpp_builtin_macro_text (pfile, node, expand_loc);
513   len = ustrlen (buf);
514   nbuf = (char *) alloca (len + 1);
515   memcpy (nbuf, buf, len);
516   nbuf[len]='\n';
517 
518   cpp_push_buffer (pfile, (uchar *) nbuf, len, /* from_stage3 */ true);
519   _cpp_clean_line (pfile);
520 
521   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
522   pfile->cur_token = _cpp_temp_token (pfile);
523   cpp_token *token = _cpp_lex_direct (pfile);
524   /* We should point to the expansion point of the builtin macro.  */
525   token->src_loc = loc;
526   if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
527     {
528       /* We are tracking tokens resulting from macro expansion.
529 	 Create a macro line map and generate a virtual location for
530 	 the token resulting from the expansion of the built-in
531 	 macro.  */
532       source_location *virt_locs = NULL;
533       _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
534       const line_map_macro * map =
535 	linemap_enter_macro (pfile->line_table, node, loc, 1);
536       tokens_buff_add_token (token_buf, virt_locs, token,
537 			     pfile->line_table->builtin_location,
538 			     pfile->line_table->builtin_location,
539 			    map, /*macro_token_index=*/0);
540       push_extended_tokens_context (pfile, node, token_buf, virt_locs,
541 				    (const cpp_token **)token_buf->base,
542 				    1);
543     }
544   else
545     _cpp_push_token_context (pfile, NULL, token, 1);
546   if (pfile->buffer->cur != pfile->buffer->rlimit)
547     cpp_error (pfile, CPP_DL_ICE, "invalid built-in macro \"%s\"",
548 	       NODE_NAME (node));
549   _cpp_pop_buffer (pfile);
550 
551   return 1;
552 }
553 
554 /* Copies SRC, of length LEN, to DEST, adding backslashes before all
555    backslashes and double quotes. DEST must be of sufficient size.
556    Returns a pointer to the end of the string.  */
557 uchar *
558 cpp_quote_string (uchar *dest, const uchar *src, unsigned int len)
559 {
560   while (len--)
561     {
562       uchar c = *src++;
563 
564       if (c == '\\' || c == '"')
565 	{
566 	  *dest++ = '\\';
567 	  *dest++ = c;
568 	}
569       else
570 	  *dest++ = c;
571     }
572 
573   return dest;
574 }
575 
576 /* Convert a token sequence ARG to a single string token according to
577    the rules of the ISO C #-operator.  */
578 static const cpp_token *
579 stringify_arg (cpp_reader *pfile, macro_arg *arg)
580 {
581   unsigned char *dest;
582   unsigned int i, escape_it, backslash_count = 0;
583   const cpp_token *source = NULL;
584   size_t len;
585 
586   if (BUFF_ROOM (pfile->u_buff) < 3)
587     _cpp_extend_buff (pfile, &pfile->u_buff, 3);
588   dest = BUFF_FRONT (pfile->u_buff);
589   *dest++ = '"';
590 
591   /* Loop, reading in the argument's tokens.  */
592   for (i = 0; i < arg->count; i++)
593     {
594       const cpp_token *token = arg->first[i];
595 
596       if (token->type == CPP_PADDING)
597 	{
598 	  if (source == NULL
599 	      || (!(source->flags & PREV_WHITE)
600 		  && token->val.source == NULL))
601 	    source = token->val.source;
602 	  continue;
603 	}
604 
605       escape_it = (token->type == CPP_STRING || token->type == CPP_CHAR
606 		   || token->type == CPP_WSTRING || token->type == CPP_WCHAR
607 		   || token->type == CPP_STRING32 || token->type == CPP_CHAR32
608 		   || token->type == CPP_STRING16 || token->type == CPP_CHAR16
609 		   || token->type == CPP_UTF8STRING || token->type == CPP_UTF8CHAR
610 		   || cpp_userdef_string_p (token->type)
611 		   || cpp_userdef_char_p (token->type));
612 
613       /* Room for each char being written in octal, initial space and
614 	 final quote and NUL.  */
615       len = cpp_token_len (token);
616       if (escape_it)
617 	len *= 4;
618       len += 3;
619 
620       if ((size_t) (BUFF_LIMIT (pfile->u_buff) - dest) < len)
621 	{
622 	  size_t len_so_far = dest - BUFF_FRONT (pfile->u_buff);
623 	  _cpp_extend_buff (pfile, &pfile->u_buff, len);
624 	  dest = BUFF_FRONT (pfile->u_buff) + len_so_far;
625 	}
626 
627       /* Leading white space?  */
628       if (dest - 1 != BUFF_FRONT (pfile->u_buff))
629 	{
630 	  if (source == NULL)
631 	    source = token;
632 	  if (source->flags & PREV_WHITE)
633 	    *dest++ = ' ';
634 	}
635       source = NULL;
636 
637       if (escape_it)
638 	{
639 	  _cpp_buff *buff = _cpp_get_buff (pfile, len);
640 	  unsigned char *buf = BUFF_FRONT (buff);
641 	  len = cpp_spell_token (pfile, token, buf, true) - buf;
642 	  dest = cpp_quote_string (dest, buf, len);
643 	  _cpp_release_buff (pfile, buff);
644 	}
645       else
646 	dest = cpp_spell_token (pfile, token, dest, true);
647 
648       if (token->type == CPP_OTHER && token->val.str.text[0] == '\\')
649 	backslash_count++;
650       else
651 	backslash_count = 0;
652     }
653 
654   /* Ignore the final \ of invalid string literals.  */
655   if (backslash_count & 1)
656     {
657       cpp_error (pfile, CPP_DL_WARNING,
658 		 "invalid string literal, ignoring final '\\'");
659       dest--;
660     }
661 
662   /* Commit the memory, including NUL, and return the token.  */
663   *dest++ = '"';
664   len = dest - BUFF_FRONT (pfile->u_buff);
665   BUFF_FRONT (pfile->u_buff) = dest + 1;
666   return new_string_token (pfile, dest - len, len);
667 }
668 
669 /* Try to paste two tokens.  On success, return nonzero.  In any
670    case, PLHS is updated to point to the pasted token, which is
671    guaranteed to not have the PASTE_LEFT flag set.  LOCATION is
672    the virtual location used for error reporting.  */
673 static bool
674 paste_tokens (cpp_reader *pfile, source_location location,
675 	      const cpp_token **plhs, const cpp_token *rhs)
676 {
677   unsigned char *buf, *end, *lhsend;
678   cpp_token *lhs;
679   unsigned int len;
680 
681   len = cpp_token_len (*plhs) + cpp_token_len (rhs) + 1;
682   buf = (unsigned char *) alloca (len);
683   end = lhsend = cpp_spell_token (pfile, *plhs, buf, true);
684 
685   /* Avoid comment headers, since they are still processed in stage 3.
686      It is simpler to insert a space here, rather than modifying the
687      lexer to ignore comments in some circumstances.  Simply returning
688      false doesn't work, since we want to clear the PASTE_LEFT flag.  */
689   if ((*plhs)->type == CPP_DIV && rhs->type != CPP_EQ)
690     *end++ = ' ';
691   /* In one obscure case we might see padding here.  */
692   if (rhs->type != CPP_PADDING)
693     end = cpp_spell_token (pfile, rhs, end, true);
694   *end = '\n';
695 
696   cpp_push_buffer (pfile, buf, end - buf, /* from_stage3 */ true);
697   _cpp_clean_line (pfile);
698 
699   /* Set pfile->cur_token as required by _cpp_lex_direct.  */
700   pfile->cur_token = _cpp_temp_token (pfile);
701   lhs = _cpp_lex_direct (pfile);
702   if (pfile->buffer->cur != pfile->buffer->rlimit)
703     {
704       source_location saved_loc = lhs->src_loc;
705 
706       _cpp_pop_buffer (pfile);
707       _cpp_backup_tokens (pfile, 1);
708       *lhsend = '\0';
709 
710       /* We have to remove the PASTE_LEFT flag from the old lhs, but
711 	 we want to keep the new location.  */
712       *lhs = **plhs;
713       *plhs = lhs;
714       lhs->src_loc = saved_loc;
715       lhs->flags &= ~PASTE_LEFT;
716 
717       /* Mandatory error for all apart from assembler.  */
718       if (CPP_OPTION (pfile, lang) != CLK_ASM)
719 	cpp_error_with_line (pfile, CPP_DL_ERROR, location, 0,
720 	 "pasting \"%s\" and \"%s\" does not give a valid preprocessing token",
721 		   buf, cpp_token_as_text (pfile, rhs));
722       return false;
723     }
724 
725   *plhs = lhs;
726   _cpp_pop_buffer (pfile);
727   return true;
728 }
729 
730 /* Handles an arbitrarily long sequence of ## operators, with initial
731    operand LHS.  This implementation is left-associative,
732    non-recursive, and finishes a paste before handling succeeding
733    ones.  If a paste fails, we back up to the RHS of the failing ##
734    operator before pushing the context containing the result of prior
735    successful pastes, with the effect that the RHS appears in the
736    output stream after the pasted LHS normally.  */
737 static void
738 paste_all_tokens (cpp_reader *pfile, const cpp_token *lhs)
739 {
740   const cpp_token *rhs = NULL;
741   cpp_context *context = pfile->context;
742   source_location virt_loc = 0;
743 
744   /* We are expanding a macro and we must have been called on a token
745      that appears at the left hand side of a ## operator.  */
746   if (macro_of_context (pfile->context) == NULL
747       || (!(lhs->flags & PASTE_LEFT)))
748     abort ();
749 
750   if (context->tokens_kind == TOKENS_KIND_EXTENDED)
751     /* The caller must have called consume_next_token_from_context
752        right before calling us.  That has incremented the pointer to
753        the current virtual location.  So it now points to the location
754        of the token that comes right after *LHS.  We want the
755        resulting pasted token to have the location of the current
756        *LHS, though.  */
757     virt_loc = context->c.mc->cur_virt_loc[-1];
758   else
759     /* We are not tracking macro expansion.  So the best virtual
760        location we can get here is the expansion point of the macro we
761        are currently expanding.  */
762     virt_loc = pfile->invocation_location;
763 
764   do
765     {
766       /* Take the token directly from the current context.  We can do
767 	 this, because we are in the replacement list of either an
768 	 object-like macro, or a function-like macro with arguments
769 	 inserted.  In either case, the constraints to #define
770 	 guarantee we have at least one more token.  */
771       if (context->tokens_kind == TOKENS_KIND_DIRECT)
772 	rhs = FIRST (context).token++;
773       else if (context->tokens_kind == TOKENS_KIND_INDIRECT)
774 	rhs = *FIRST (context).ptoken++;
775       else if (context->tokens_kind == TOKENS_KIND_EXTENDED)
776 	{
777 	  /* So we are in presence of an extended token context, which
778 	     means that each token in this context has a virtual
779 	     location attached to it.  So let's not forget to update
780 	     the pointer to the current virtual location of the
781 	     current token when we update the pointer to the current
782 	     token */
783 
784 	  rhs = *FIRST (context).ptoken++;
785 	  /* context->c.mc must be non-null, as if we were not in a
786 	     macro context, context->tokens_kind could not be equal to
787 	     TOKENS_KIND_EXTENDED.  */
788 	  context->c.mc->cur_virt_loc++;
789 	}
790 
791       if (rhs->type == CPP_PADDING)
792 	{
793 	  if (rhs->flags & PASTE_LEFT)
794 	    abort ();
795 	}
796       if (!paste_tokens (pfile, virt_loc, &lhs, rhs))
797 	break;
798     }
799   while (rhs->flags & PASTE_LEFT);
800 
801   /* Put the resulting token in its own context.  */
802   if (context->tokens_kind == TOKENS_KIND_EXTENDED)
803     {
804       source_location *virt_locs = NULL;
805       _cpp_buff *token_buf = tokens_buff_new (pfile, 1, &virt_locs);
806       tokens_buff_add_token (token_buf, virt_locs, lhs,
807 			     virt_loc, 0, NULL, 0);
808       push_extended_tokens_context (pfile, context->c.mc->macro_node,
809 				    token_buf, virt_locs,
810 				    (const cpp_token **)token_buf->base, 1);
811     }
812   else
813     _cpp_push_token_context (pfile, NULL, lhs, 1);
814 }
815 
816 /* Returns TRUE if the number of arguments ARGC supplied in an
817    invocation of the MACRO referenced by NODE is valid.  An empty
818    invocation to a macro with no parameters should pass ARGC as zero.
819 
820    Note that MACRO cannot necessarily be deduced from NODE, in case
821    NODE was redefined whilst collecting arguments.  */
822 bool
823 _cpp_arguments_ok (cpp_reader *pfile, cpp_macro *macro, const cpp_hashnode *node, unsigned int argc)
824 {
825   if (argc == macro->paramc)
826     return true;
827 
828   if (argc < macro->paramc)
829     {
830       /* As an extension, variadic arguments are allowed to not appear in
831 	 the invocation at all.
832 	 e.g. #define debug(format, args...) something
833 	 debug("string");
834 
835 	 This is exactly the same as if an empty variadic list had been
836 	 supplied - debug("string", ).  */
837 
838       if (argc + 1 == macro->paramc && macro->variadic)
839 	{
840 	  if (CPP_PEDANTIC (pfile) && ! macro->syshdr)
841 	    {
842 	      if (CPP_OPTION (pfile, cplusplus))
843 		cpp_error (pfile, CPP_DL_PEDWARN,
844 			   "ISO C++11 requires at least one argument "
845 			   "for the \"...\" in a variadic macro");
846 	      else
847 		cpp_error (pfile, CPP_DL_PEDWARN,
848 			   "ISO C99 requires at least one argument "
849 			   "for the \"...\" in a variadic macro");
850 	    }
851 	  return true;
852 	}
853 
854       cpp_error (pfile, CPP_DL_ERROR,
855 		 "macro \"%s\" requires %u arguments, but only %u given",
856 		 NODE_NAME (node), macro->paramc, argc);
857     }
858   else
859     cpp_error (pfile, CPP_DL_ERROR,
860 	       "macro \"%s\" passed %u arguments, but takes just %u",
861 	       NODE_NAME (node), argc, macro->paramc);
862 
863   return false;
864 }
865 
866 /* Reads and returns the arguments to a function-like macro
867    invocation.  Assumes the opening parenthesis has been processed.
868    If there is an error, emits an appropriate diagnostic and returns
869    NULL.  Each argument is terminated by a CPP_EOF token, for the
870    future benefit of expand_arg().  If there are any deferred
871    #pragma directives among macro arguments, store pointers to the
872    CPP_PRAGMA ... CPP_PRAGMA_EOL tokens into *PRAGMA_BUFF buffer.
873 
874    What is returned is the buffer that contains the memory allocated
875    to hold the macro arguments.  NODE is the name of the macro this
876    function is dealing with.  If NUM_ARGS is non-NULL, *NUM_ARGS is
877    set to the actual number of macro arguments allocated in the
878    returned buffer.  */
879 static _cpp_buff *
880 collect_args (cpp_reader *pfile, const cpp_hashnode *node,
881 	      _cpp_buff **pragma_buff, unsigned *num_args)
882 {
883   _cpp_buff *buff, *base_buff;
884   cpp_macro *macro;
885   macro_arg *args, *arg;
886   const cpp_token *token;
887   unsigned int argc;
888   source_location virt_loc;
889   bool track_macro_expansion_p = CPP_OPTION (pfile, track_macro_expansion);
890   unsigned num_args_alloced = 0;
891 
892   macro = node->value.macro;
893   if (macro->paramc)
894     argc = macro->paramc;
895   else
896     argc = 1;
897 
898 #define DEFAULT_NUM_TOKENS_PER_MACRO_ARG 50
899 #define ARG_TOKENS_EXTENT 1000
900 
901   buff = _cpp_get_buff (pfile, argc * (DEFAULT_NUM_TOKENS_PER_MACRO_ARG
902 				       * sizeof (cpp_token *)
903 				       + sizeof (macro_arg)));
904   base_buff = buff;
905   args = (macro_arg *) buff->base;
906   memset (args, 0, argc * sizeof (macro_arg));
907   buff->cur = (unsigned char *) &args[argc];
908   arg = args, argc = 0;
909   pfile->state.collecting_args = 1;
910 
911   /* Collect the tokens making up each argument.  We don't yet know
912      how many arguments have been supplied, whether too many or too
913      few.  Hence the slightly bizarre usage of "argc" and "arg".  */
914   do
915     {
916       unsigned int paren_depth = 0;
917       unsigned int ntokens = 0;
918       unsigned virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
919       num_args_alloced++;
920 
921       argc++;
922       arg->first = (const cpp_token **) buff->cur;
923       if (track_macro_expansion_p)
924 	{
925 	  virt_locs_capacity = DEFAULT_NUM_TOKENS_PER_MACRO_ARG;
926 	  arg->virt_locs = XNEWVEC (source_location,
927 				    virt_locs_capacity);
928 	}
929 
930       for (;;)
931 	{
932 	  /* Require space for 2 new tokens (including a CPP_EOF).  */
933 	  if ((unsigned char *) &arg->first[ntokens + 2] > buff->limit)
934 	    {
935 	      buff = _cpp_append_extend_buff (pfile, buff,
936 					      ARG_TOKENS_EXTENT
937 					      * sizeof (cpp_token *));
938 	      arg->first = (const cpp_token **) buff->cur;
939 	    }
940 	  if (track_macro_expansion_p
941 	      && (ntokens + 2 > virt_locs_capacity))
942 	    {
943 	      virt_locs_capacity += ARG_TOKENS_EXTENT;
944 	      arg->virt_locs = XRESIZEVEC (source_location,
945 					   arg->virt_locs,
946 					   virt_locs_capacity);
947 	    }
948 
949 	  token = cpp_get_token_1 (pfile, &virt_loc);
950 
951 	  if (token->type == CPP_PADDING)
952 	    {
953 	      /* Drop leading padding.  */
954 	      if (ntokens == 0)
955 		continue;
956 	    }
957 	  else if (token->type == CPP_OPEN_PAREN)
958 	    paren_depth++;
959 	  else if (token->type == CPP_CLOSE_PAREN)
960 	    {
961 	      if (paren_depth-- == 0)
962 		break;
963 	    }
964 	  else if (token->type == CPP_COMMA)
965 	    {
966 	      /* A comma does not terminate an argument within
967 		 parentheses or as part of a variable argument.  */
968 	      if (paren_depth == 0
969 		  && ! (macro->variadic && argc == macro->paramc))
970 		break;
971 	    }
972 	  else if (token->type == CPP_EOF
973 		   || (token->type == CPP_HASH && token->flags & BOL))
974 	    break;
975 	  else if (token->type == CPP_PRAGMA)
976 	    {
977 	      cpp_token *newtok = _cpp_temp_token (pfile);
978 
979 	      /* CPP_PRAGMA token lives in directive_result, which will
980 		 be overwritten on the next directive.  */
981 	      *newtok = *token;
982 	      token = newtok;
983 	      do
984 		{
985 		  if (*pragma_buff == NULL
986 		      || BUFF_ROOM (*pragma_buff) < sizeof (cpp_token *))
987 		    {
988 		      _cpp_buff *next;
989 		      if (*pragma_buff == NULL)
990 			*pragma_buff
991 			  = _cpp_get_buff (pfile, 32 * sizeof (cpp_token *));
992 		      else
993 			{
994 			  next = *pragma_buff;
995 			  *pragma_buff
996 			    = _cpp_get_buff (pfile,
997 					     (BUFF_FRONT (*pragma_buff)
998 					      - (*pragma_buff)->base) * 2);
999 			  (*pragma_buff)->next = next;
1000 			}
1001 		    }
1002 		  *(const cpp_token **) BUFF_FRONT (*pragma_buff) = token;
1003 		  BUFF_FRONT (*pragma_buff) += sizeof (cpp_token *);
1004 		  if (token->type == CPP_PRAGMA_EOL)
1005 		    break;
1006 		  token = cpp_get_token_1 (pfile, &virt_loc);
1007 		}
1008 	      while (token->type != CPP_EOF);
1009 
1010 	      /* In deferred pragmas parsing_args and prevent_expansion
1011 		 had been changed, reset it.  */
1012 	      pfile->state.parsing_args = 2;
1013 	      pfile->state.prevent_expansion = 1;
1014 
1015 	      if (token->type == CPP_EOF)
1016 		break;
1017 	      else
1018 		continue;
1019 	    }
1020 	  set_arg_token (arg, token, virt_loc,
1021 			 ntokens, MACRO_ARG_TOKEN_NORMAL,
1022 			 CPP_OPTION (pfile, track_macro_expansion));
1023 	  ntokens++;
1024 	}
1025 
1026       /* Drop trailing padding.  */
1027       while (ntokens > 0 && arg->first[ntokens - 1]->type == CPP_PADDING)
1028 	ntokens--;
1029 
1030       arg->count = ntokens;
1031       set_arg_token (arg, &pfile->eof, pfile->eof.src_loc,
1032 		     ntokens, MACRO_ARG_TOKEN_NORMAL,
1033 		     CPP_OPTION (pfile, track_macro_expansion));
1034 
1035       /* Terminate the argument.  Excess arguments loop back and
1036 	 overwrite the final legitimate argument, before failing.  */
1037       if (argc <= macro->paramc)
1038 	{
1039 	  buff->cur = (unsigned char *) &arg->first[ntokens + 1];
1040 	  if (argc != macro->paramc)
1041 	    arg++;
1042 	}
1043     }
1044   while (token->type != CPP_CLOSE_PAREN && token->type != CPP_EOF);
1045   pfile->state.collecting_args = 0;
1046 
1047   if (token->type == CPP_EOF)
1048     {
1049       /* We still need the CPP_EOF to end directives, and to end
1050 	 pre-expansion of a macro argument.  Step back is not
1051 	 unconditional, since we don't want to return a CPP_EOF to our
1052 	 callers at the end of an -include-d file.  */
1053       if (pfile->context->prev || pfile->state.in_directive)
1054 	_cpp_backup_tokens (pfile, 1);
1055       cpp_error (pfile, CPP_DL_ERROR,
1056 		 "unterminated argument list invoking macro \"%s\"",
1057 		 NODE_NAME (node));
1058     }
1059   else
1060     {
1061       /* A single empty argument is counted as no argument.  */
1062       if (argc == 1 && macro->paramc == 0 && args[0].count == 0)
1063 	argc = 0;
1064       if (_cpp_arguments_ok (pfile, macro, node, argc))
1065 	{
1066 	  /* GCC has special semantics for , ## b where b is a varargs
1067 	     parameter: we remove the comma if b was omitted entirely.
1068 	     If b was merely an empty argument, the comma is retained.
1069 	     If the macro takes just one (varargs) parameter, then we
1070 	     retain the comma only if we are standards conforming.
1071 
1072 	     If FIRST is NULL replace_args () swallows the comma.  */
1073 	  if (macro->variadic && (argc < macro->paramc
1074 				  || (argc == 1 && args[0].count == 0
1075 				      && !CPP_OPTION (pfile, std))))
1076 	    args[macro->paramc - 1].first = NULL;
1077 	  if (num_args)
1078 	    *num_args = num_args_alloced;
1079 	  return base_buff;
1080 	}
1081     }
1082 
1083   /* An error occurred.  */
1084   _cpp_release_buff (pfile, base_buff);
1085   return NULL;
1086 }
1087 
1088 /* Search for an opening parenthesis to the macro of NODE, in such a
1089    way that, if none is found, we don't lose the information in any
1090    intervening padding tokens.  If we find the parenthesis, collect
1091    the arguments and return the buffer containing them.  PRAGMA_BUFF
1092    argument is the same as in collect_args.  If NUM_ARGS is non-NULL,
1093    *NUM_ARGS is set to the number of arguments contained in the
1094    returned buffer.  */
1095 static _cpp_buff *
1096 funlike_invocation_p (cpp_reader *pfile, cpp_hashnode *node,
1097 		      _cpp_buff **pragma_buff, unsigned *num_args)
1098 {
1099   const cpp_token *token, *padding = NULL;
1100 
1101   for (;;)
1102     {
1103       token = cpp_get_token (pfile);
1104       if (token->type != CPP_PADDING)
1105 	break;
1106       if (padding == NULL
1107 	  || (!(padding->flags & PREV_WHITE) && token->val.source == NULL))
1108 	padding = token;
1109     }
1110 
1111   if (token->type == CPP_OPEN_PAREN)
1112     {
1113       pfile->state.parsing_args = 2;
1114       return collect_args (pfile, node, pragma_buff, num_args);
1115     }
1116 
1117   /* CPP_EOF can be the end of macro arguments, or the end of the
1118      file.  We mustn't back up over the latter.  Ugh.  */
1119   if (token->type != CPP_EOF || token == &pfile->eof)
1120     {
1121       /* Back up.  We may have skipped padding, in which case backing
1122 	 up more than one token when expanding macros is in general
1123 	 too difficult.  We re-insert it in its own context.  */
1124       _cpp_backup_tokens (pfile, 1);
1125       if (padding)
1126 	_cpp_push_token_context (pfile, NULL, padding, 1);
1127     }
1128 
1129   return NULL;
1130 }
1131 
1132 /* Return the real number of tokens in the expansion of MACRO.  */
1133 static inline unsigned int
1134 macro_real_token_count (const cpp_macro *macro)
1135 {
1136   unsigned int i;
1137   if (__builtin_expect (!macro->extra_tokens, true))
1138     return macro->count;
1139   for (i = 0; i < macro->count; i++)
1140     if (macro->exp.tokens[i].type == CPP_PASTE)
1141       return i;
1142   abort ();
1143 }
1144 
1145 /* Push the context of a macro with hash entry NODE onto the context
1146    stack.  If we can successfully expand the macro, we push a context
1147    containing its yet-to-be-rescanned replacement list and return one.
1148    If there were additionally any unexpanded deferred #pragma
1149    directives among macro arguments, push another context containing
1150    the pragma tokens before the yet-to-be-rescanned replacement list
1151    and return two.  Otherwise, we don't push a context and return
1152    zero. LOCATION is the location of the expansion point of the
1153    macro.  */
1154 static int
1155 enter_macro_context (cpp_reader *pfile, cpp_hashnode *node,
1156 		     const cpp_token *result, source_location location)
1157 {
1158   /* The presence of a macro invalidates a file's controlling macro.  */
1159   pfile->mi_valid = false;
1160 
1161   pfile->state.angled_headers = false;
1162 
1163   /* From here to when we push the context for the macro later down
1164      this function, we need to flag the fact that we are about to
1165      expand a macro.  This is useful when -ftrack-macro-expansion is
1166      turned off.  In that case, we need to record the location of the
1167      expansion point of the top-most macro we are about to to expand,
1168      into pfile->invocation_location.  But we must not record any such
1169      location once the process of expanding the macro starts; that is,
1170      we must not do that recording between now and later down this
1171      function where set this flag to FALSE.  */
1172   pfile->about_to_expand_macro_p = true;
1173 
1174   if ((node->flags & NODE_BUILTIN) && !(node->flags & NODE_USED))
1175     {
1176       node->flags |= NODE_USED;
1177       if ((!pfile->cb.user_builtin_macro
1178 	   || !pfile->cb.user_builtin_macro (pfile, node))
1179 	  && pfile->cb.used_define)
1180 	pfile->cb.used_define (pfile, pfile->directive_line, node);
1181     }
1182 
1183   /* Handle standard macros.  */
1184   if (! (node->flags & NODE_BUILTIN))
1185     {
1186       cpp_macro *macro = node->value.macro;
1187       _cpp_buff *pragma_buff = NULL;
1188 
1189       if (macro->fun_like)
1190 	{
1191 	  _cpp_buff *buff;
1192 	  unsigned num_args = 0;
1193 
1194 	  pfile->state.prevent_expansion++;
1195 	  pfile->keep_tokens++;
1196 	  pfile->state.parsing_args = 1;
1197 	  buff = funlike_invocation_p (pfile, node, &pragma_buff,
1198 				       &num_args);
1199 	  pfile->state.parsing_args = 0;
1200 	  pfile->keep_tokens--;
1201 	  pfile->state.prevent_expansion--;
1202 
1203 	  if (buff == NULL)
1204 	    {
1205 	      if (CPP_WTRADITIONAL (pfile) && ! node->value.macro->syshdr)
1206 		cpp_warning (pfile, CPP_W_TRADITIONAL,
1207  "function-like macro \"%s\" must be used with arguments in traditional C",
1208 			     NODE_NAME (node));
1209 
1210 	      if (pragma_buff)
1211 		_cpp_release_buff (pfile, pragma_buff);
1212 
1213 	      pfile->about_to_expand_macro_p = false;
1214 	      return 0;
1215 	    }
1216 
1217 	  if (macro->paramc > 0)
1218 	    replace_args (pfile, node, macro,
1219 			  (macro_arg *) buff->base,
1220 			  location);
1221 	  /* Free the memory used by the arguments of this
1222 	     function-like macro.  This memory has been allocated by
1223 	     funlike_invocation_p and by replace_args.  */
1224 	  delete_macro_args (buff, num_args);
1225 	}
1226 
1227       /* Disable the macro within its expansion.  */
1228       node->flags |= NODE_DISABLED;
1229 
1230       if (!(node->flags & NODE_USED))
1231 	{
1232 	  node->flags |= NODE_USED;
1233 	  if (pfile->cb.used_define)
1234 	    pfile->cb.used_define (pfile, pfile->directive_line, node);
1235 	}
1236 
1237       if (pfile->cb.used)
1238 	pfile->cb.used (pfile, location, node);
1239 
1240       macro->used = 1;
1241 
1242       if (macro->paramc == 0)
1243 	{
1244 	  unsigned tokens_count = macro_real_token_count (macro);
1245 	  if (CPP_OPTION (pfile, track_macro_expansion))
1246 	    {
1247 	      unsigned int i;
1248 	      const cpp_token *src = macro->exp.tokens;
1249 	      const line_map_macro *map;
1250 	      source_location *virt_locs = NULL;
1251 	      _cpp_buff *macro_tokens
1252 		= tokens_buff_new (pfile, tokens_count, &virt_locs);
1253 
1254 	      /* Create a macro map to record the locations of the
1255 		 tokens that are involved in the expansion. LOCATION
1256 		 is the location of the macro expansion point.  */
1257 	      map = linemap_enter_macro (pfile->line_table,
1258 					 node, location, tokens_count);
1259 	      for (i = 0; i < tokens_count; ++i)
1260 		{
1261 		  tokens_buff_add_token (macro_tokens, virt_locs,
1262 					 src, src->src_loc,
1263 					 src->src_loc, map, i);
1264 		  ++src;
1265 		}
1266 	      push_extended_tokens_context (pfile, node,
1267 					    macro_tokens,
1268 					    virt_locs,
1269 					    (const cpp_token **)
1270 					    macro_tokens->base,
1271 					    tokens_count);
1272 	    }
1273 	  else
1274 	    _cpp_push_token_context (pfile, node, macro->exp.tokens,
1275 				     tokens_count);
1276 	  num_macro_tokens_counter += tokens_count;
1277 	}
1278 
1279       if (pragma_buff)
1280 	{
1281 	  if (!pfile->state.in_directive)
1282 	    _cpp_push_token_context (pfile, NULL,
1283 				     padding_token (pfile, result), 1);
1284 	  do
1285 	    {
1286 	      unsigned tokens_count;
1287 	      _cpp_buff *tail = pragma_buff->next;
1288 	      pragma_buff->next = NULL;
1289 	      tokens_count = ((const cpp_token **) BUFF_FRONT (pragma_buff)
1290 			      - (const cpp_token **) pragma_buff->base);
1291 	      push_ptoken_context (pfile, NULL, pragma_buff,
1292 				   (const cpp_token **) pragma_buff->base,
1293 				   tokens_count);
1294 	      pragma_buff = tail;
1295 	      if (!CPP_OPTION (pfile, track_macro_expansion))
1296 		num_macro_tokens_counter += tokens_count;
1297 
1298 	    }
1299 	  while (pragma_buff != NULL);
1300 	  pfile->about_to_expand_macro_p = false;
1301 	  return 2;
1302 	}
1303 
1304       pfile->about_to_expand_macro_p = false;
1305       return 1;
1306     }
1307 
1308   pfile->about_to_expand_macro_p = false;
1309   /* Handle built-in macros and the _Pragma operator.  */
1310   {
1311     source_location loc, expand_loc;
1312 
1313     if (/* The top-level macro invocation that triggered the expansion
1314 	   we are looking at is with a standard macro ...*/
1315 	!(pfile->top_most_macro_node->flags & NODE_BUILTIN)
1316 	/* ... and it's a function-like macro invocation.  */
1317 	&& pfile->top_most_macro_node->value.macro->fun_like)
1318       {
1319 	/* Then the location of the end of the macro invocation is the
1320 	   location of the closing parenthesis.  */
1321 	loc = pfile->cur_token[-1].src_loc;
1322 	expand_loc = loc;
1323       }
1324     else
1325       {
1326 	/* Otherwise, the location of the end of the macro invocation is
1327 	   the location of the expansion point of that top-level macro
1328 	   invocation.  */
1329 	loc = location;
1330 	expand_loc = pfile->invocation_location;
1331       }
1332 
1333     return builtin_macro (pfile, node, loc, expand_loc);
1334   }
1335 }
1336 
1337 /* De-allocate the memory used by BUFF which is an array of instances
1338    of macro_arg.  NUM_ARGS is the number of instances of macro_arg
1339    present in BUFF.  */
1340 static void
1341 delete_macro_args (_cpp_buff *buff, unsigned num_args)
1342 {
1343   macro_arg *macro_args;
1344   unsigned i;
1345 
1346   if (buff == NULL)
1347     return;
1348 
1349   macro_args = (macro_arg *) buff->base;
1350 
1351   /* Walk instances of macro_arg to free their expanded tokens as well
1352      as their macro_arg::virt_locs members.  */
1353   for (i = 0; i < num_args; ++i)
1354     {
1355       if (macro_args[i].expanded)
1356 	{
1357 	  free (macro_args[i].expanded);
1358 	  macro_args[i].expanded = NULL;
1359 	}
1360       if (macro_args[i].virt_locs)
1361 	{
1362 	  free (macro_args[i].virt_locs);
1363 	  macro_args[i].virt_locs = NULL;
1364 	}
1365       if (macro_args[i].expanded_virt_locs)
1366 	{
1367 	  free (macro_args[i].expanded_virt_locs);
1368 	  macro_args[i].expanded_virt_locs = NULL;
1369 	}
1370     }
1371   _cpp_free_buff (buff);
1372 }
1373 
1374 /* Set the INDEXth token of the macro argument ARG. TOKEN is the token
1375    to set, LOCATION is its virtual location.  "Virtual" location means
1376    the location that encodes loci across macro expansion. Otherwise
1377    it has to be TOKEN->SRC_LOC.  KIND is the kind of tokens the
1378    argument ARG is supposed to contain.  Note that ARG must be
1379    tailored so that it has enough room to contain INDEX + 1 numbers of
1380    tokens, at least.  */
1381 static void
1382 set_arg_token (macro_arg *arg, const cpp_token *token,
1383 	       source_location location, size_t index,
1384 	       enum macro_arg_token_kind kind,
1385 	       bool track_macro_exp_p)
1386 {
1387   const cpp_token **token_ptr;
1388   source_location *loc = NULL;
1389 
1390   token_ptr =
1391     arg_token_ptr_at (arg, index, kind,
1392 		      track_macro_exp_p ? &loc : NULL);
1393   *token_ptr = token;
1394 
1395   if (loc != NULL)
1396     {
1397       /* We can't set the location of a stringified argument
1398 	 token and we can't set any location if we aren't tracking
1399 	 macro expansion locations.   */
1400       gcc_checking_assert (kind != MACRO_ARG_TOKEN_STRINGIFIED
1401 			   && track_macro_exp_p);
1402       *loc = location;
1403     }
1404 }
1405 
1406 /* Get the pointer to the location of the argument token of the
1407    function-like macro argument ARG.  This function must be called
1408    only when we -ftrack-macro-expansion is on.  */
1409 static const source_location *
1410 get_arg_token_location (const macro_arg *arg,
1411 			enum macro_arg_token_kind kind)
1412 {
1413   const source_location *loc = NULL;
1414   const cpp_token **token_ptr =
1415     arg_token_ptr_at (arg, 0, kind, (source_location **) &loc);
1416 
1417   if (token_ptr == NULL)
1418     return NULL;
1419 
1420   return loc;
1421 }
1422 
1423 /* Return the pointer to the INDEXth token of the macro argument ARG.
1424    KIND specifies the kind of token the macro argument ARG contains.
1425    If VIRT_LOCATION is non NULL, *VIRT_LOCATION is set to the address
1426    of the virtual location of the returned token if the
1427    -ftrack-macro-expansion flag is on; otherwise, it's set to the
1428    spelling location of the returned token.  */
1429 static const cpp_token **
1430 arg_token_ptr_at (const macro_arg *arg, size_t index,
1431 		  enum macro_arg_token_kind kind,
1432 		  source_location **virt_location)
1433 {
1434   const cpp_token **tokens_ptr = NULL;
1435 
1436   switch (kind)
1437     {
1438     case MACRO_ARG_TOKEN_NORMAL:
1439       tokens_ptr = arg->first;
1440       break;
1441     case MACRO_ARG_TOKEN_STRINGIFIED:
1442       tokens_ptr = (const cpp_token **) &arg->stringified;
1443       break;
1444     case MACRO_ARG_TOKEN_EXPANDED:
1445 	tokens_ptr = arg->expanded;
1446       break;
1447     }
1448 
1449   if (tokens_ptr == NULL)
1450     /* This can happen for e.g, an empty token argument to a
1451        funtion-like macro.  */
1452     return tokens_ptr;
1453 
1454   if (virt_location)
1455     {
1456       if (kind == MACRO_ARG_TOKEN_NORMAL)
1457 	*virt_location = &arg->virt_locs[index];
1458       else if (kind == MACRO_ARG_TOKEN_EXPANDED)
1459 	*virt_location = &arg->expanded_virt_locs[index];
1460       else if (kind == MACRO_ARG_TOKEN_STRINGIFIED)
1461 	*virt_location =
1462 	  (source_location *) &tokens_ptr[index]->src_loc;
1463     }
1464   return &tokens_ptr[index];
1465 }
1466 
1467 /* Initialize an iterator so that it iterates over the tokens of a
1468    function-like macro argument.  KIND is the kind of tokens we want
1469    ITER to iterate over. TOKEN_PTR points the first token ITER will
1470    iterate over.  */
1471 static void
1472 macro_arg_token_iter_init (macro_arg_token_iter *iter,
1473 			   bool track_macro_exp_p,
1474 			   enum macro_arg_token_kind kind,
1475 			   const macro_arg *arg,
1476 			   const cpp_token **token_ptr)
1477 {
1478   iter->track_macro_exp_p = track_macro_exp_p;
1479   iter->kind = kind;
1480   iter->token_ptr = token_ptr;
1481   /* Unconditionally initialize this so that the compiler doesn't warn
1482      about iter->location_ptr being possibly uninitialized later after
1483      this code has been inlined somewhere.  */
1484   iter->location_ptr = NULL;
1485   if (track_macro_exp_p)
1486     iter->location_ptr = get_arg_token_location (arg, kind);
1487 #if CHECKING_P
1488   iter->num_forwards = 0;
1489   if (track_macro_exp_p
1490       && token_ptr != NULL
1491       && iter->location_ptr == NULL)
1492     abort ();
1493 #endif
1494 }
1495 
1496 /* Move the iterator one token forward. Note that if IT was
1497    initialized on an argument that has a stringified token, moving it
1498    forward doesn't make sense as a stringified token is essentially one
1499    string.  */
1500 static void
1501 macro_arg_token_iter_forward (macro_arg_token_iter *it)
1502 {
1503   switch (it->kind)
1504     {
1505     case MACRO_ARG_TOKEN_NORMAL:
1506     case MACRO_ARG_TOKEN_EXPANDED:
1507       it->token_ptr++;
1508       if (it->track_macro_exp_p)
1509 	it->location_ptr++;
1510       break;
1511     case MACRO_ARG_TOKEN_STRINGIFIED:
1512 #if CHECKING_P
1513       if (it->num_forwards > 0)
1514 	abort ();
1515 #endif
1516       break;
1517     }
1518 
1519 #if CHECKING_P
1520   it->num_forwards++;
1521 #endif
1522 }
1523 
1524 /* Return the token pointed to by the iterator.  */
1525 static const cpp_token *
1526 macro_arg_token_iter_get_token (const macro_arg_token_iter *it)
1527 {
1528 #if CHECKING_P
1529   if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1530       && it->num_forwards > 0)
1531     abort ();
1532 #endif
1533   if (it->token_ptr == NULL)
1534     return NULL;
1535   return *it->token_ptr;
1536 }
1537 
1538 /* Return the location of the token pointed to by the iterator.*/
1539 static source_location
1540 macro_arg_token_iter_get_location (const macro_arg_token_iter *it)
1541 {
1542 #if CHECKING_P
1543   if (it->kind == MACRO_ARG_TOKEN_STRINGIFIED
1544       && it->num_forwards > 0)
1545     abort ();
1546 #endif
1547   if (it->track_macro_exp_p)
1548     return *it->location_ptr;
1549   else
1550     return (*it->token_ptr)->src_loc;
1551 }
1552 
1553 /* Return the index of a token [resulting from macro expansion] inside
1554    the total list of tokens resulting from a given macro
1555    expansion. The index can be different depending on whether if we
1556    want each tokens resulting from function-like macro arguments
1557    expansion to have a different location or not.
1558 
1559    E.g, consider this function-like macro:
1560 
1561         #define M(x) x - 3
1562 
1563    Then consider us "calling" it (and thus expanding it) like:
1564 
1565        M(1+4)
1566 
1567    It will be expanded into:
1568 
1569        1+4-3
1570 
1571    Let's consider the case of the token '4'.
1572 
1573    Its index can be 2 (it's the third token of the set of tokens
1574    resulting from the expansion) or it can be 0 if we consider that
1575    all tokens resulting from the expansion of the argument "1+2" have
1576    the same index, which is 0. In this later case, the index of token
1577    '-' would then be 1 and the index of token '3' would be 2.
1578 
1579    The later case is useful to use less memory e.g, for the case of
1580    the user using the option -ftrack-macro-expansion=1.
1581 
1582    ABSOLUTE_TOKEN_INDEX is the index of the macro argument token we
1583    are interested in.  CUR_REPLACEMENT_TOKEN is the token of the macro
1584    parameter (inside the macro replacement list) that corresponds to
1585    the macro argument for which ABSOLUTE_TOKEN_INDEX is a token index
1586    of.
1587 
1588    If we refer to the example above, for the '4' argument token,
1589    ABSOLUTE_TOKEN_INDEX would be set to 2, and CUR_REPLACEMENT_TOKEN
1590    would be set to the token 'x', in the replacement list "x - 3" of
1591    macro M.
1592 
1593    This is a subroutine of replace_args.  */
1594 inline static unsigned
1595 expanded_token_index (cpp_reader *pfile, cpp_macro *macro,
1596 		      const cpp_token *cur_replacement_token,
1597 		      unsigned absolute_token_index)
1598 {
1599   if (CPP_OPTION (pfile, track_macro_expansion) > 1)
1600     return absolute_token_index;
1601   return cur_replacement_token - macro->exp.tokens;
1602 }
1603 
1604 /* Replace the parameters in a function-like macro of NODE with the
1605    actual ARGS, and place the result in a newly pushed token context.
1606    Expand each argument before replacing, unless it is operated upon
1607    by the # or ## operators. EXPANSION_POINT_LOC is the location of
1608    the expansion point of the macro. E.g, the location of the
1609    function-like macro invocation.  */
1610 static void
1611 replace_args (cpp_reader *pfile, cpp_hashnode *node, cpp_macro *macro,
1612 	      macro_arg *args, source_location expansion_point_loc)
1613 {
1614   unsigned int i, total;
1615   const cpp_token *src, *limit;
1616   const cpp_token **first = NULL;
1617   macro_arg *arg;
1618   _cpp_buff *buff = NULL;
1619   source_location *virt_locs = NULL;
1620   unsigned int exp_count;
1621   const line_map_macro *map = NULL;
1622   int track_macro_exp;
1623 
1624   /* First, fully macro-expand arguments, calculating the number of
1625      tokens in the final expansion as we go.  The ordering of the if
1626      statements below is subtle; we must handle stringification before
1627      pasting.  */
1628 
1629   /* EXP_COUNT is the number of tokens in the macro replacement
1630      list.  TOTAL is the number of tokens /after/ macro parameters
1631      have been replaced by their arguments.   */
1632   exp_count = macro_real_token_count (macro);
1633   total = exp_count;
1634   limit = macro->exp.tokens + exp_count;
1635 
1636   for (src = macro->exp.tokens; src < limit; src++)
1637     if (src->type == CPP_MACRO_ARG)
1638       {
1639 	/* Leading and trailing padding tokens.  */
1640 	total += 2;
1641 	/* Account for leading and padding tokens in exp_count too.
1642 	   This is going to be important later down this function,
1643 	   when we want to handle the case of (track_macro_exp <
1644 	   2).  */
1645 	exp_count += 2;
1646 
1647 	/* We have an argument.  If it is not being stringified or
1648 	   pasted it is macro-replaced before insertion.  */
1649 	arg = &args[src->val.macro_arg.arg_no - 1];
1650 
1651 	if (src->flags & STRINGIFY_ARG)
1652 	  {
1653 	    if (!arg->stringified)
1654 	      arg->stringified = stringify_arg (pfile, arg);
1655 	  }
1656 	else if ((src->flags & PASTE_LEFT)
1657 		 || (src > macro->exp.tokens && (src[-1].flags & PASTE_LEFT)))
1658 	  total += arg->count - 1;
1659 	else
1660 	  {
1661 	    if (!arg->expanded)
1662 	      expand_arg (pfile, arg);
1663 	    total += arg->expanded_count - 1;
1664 	  }
1665       }
1666 
1667   /* When the compiler is called with the -ftrack-macro-expansion
1668      flag, we need to keep track of the location of each token that
1669      results from macro expansion.
1670 
1671      A token resulting from macro expansion is not a new token. It is
1672      simply the same token as the token coming from the macro
1673      definition.  The new things that are allocated are the buffer
1674      that holds the tokens resulting from macro expansion and a new
1675      location that records many things like the locus of the expansion
1676      point as well as the original locus inside the definition of the
1677      macro.  This location is called a virtual location.
1678 
1679      So the buffer BUFF holds a set of cpp_token*, and the buffer
1680      VIRT_LOCS holds the virtual locations of the tokens held by BUFF.
1681 
1682      Both of these two buffers are going to be hung off of the macro
1683      context, when the latter is pushed.  The memory allocated to
1684      store the tokens and their locations is going to be freed once
1685      the context of macro expansion is popped.
1686 
1687      As far as tokens are concerned, the memory overhead of
1688      -ftrack-macro-expansion is proportional to the number of
1689      macros that get expanded multiplied by sizeof (source_location).
1690      The good news is that extra memory gets freed when the macro
1691      context is freed, i.e shortly after the macro got expanded.  */
1692 
1693   /* Is the -ftrack-macro-expansion flag in effect?  */
1694   track_macro_exp = CPP_OPTION (pfile, track_macro_expansion);
1695 
1696   /* Now allocate memory space for tokens and locations resulting from
1697      the macro expansion, copy the tokens and replace the arguments.
1698      This memory must be freed when the context of the macro MACRO is
1699      popped.  */
1700   buff = tokens_buff_new (pfile, total, track_macro_exp ? &virt_locs : NULL);
1701 
1702   first = (const cpp_token **) buff->base;
1703 
1704   /* Create a macro map to record the locations of the tokens that are
1705      involved in the expansion.  Note that the expansion point is set
1706      to the location of the closing parenthesis.  Otherwise, the
1707      subsequent map created for the first token that comes after the
1708      macro map might have a wrong line number.  That would lead to
1709      tokens with wrong line numbers after the macro expansion.  This
1710      adds up to the memory overhead of the -ftrack-macro-expansion
1711      flag; for every macro that is expanded, a "macro map" is
1712      created.  */
1713   if (track_macro_exp)
1714     {
1715       int num_macro_tokens = total;
1716       if (track_macro_exp < 2)
1717 	/* Then the number of macro tokens won't take in account the
1718 	   fact that function-like macro arguments can expand to
1719 	   multiple tokens. This is to save memory at the expense of
1720 	   accuracy.
1721 
1722 	   Suppose we have #define SQARE(A) A * A
1723 
1724 	   And then we do SQARE(2+3)
1725 
1726 	   Then the tokens 2, +, 3, will have the same location,
1727 	   saying they come from the expansion of the argument A.  */
1728 	num_macro_tokens = exp_count;
1729       map = linemap_enter_macro (pfile->line_table, node,
1730 				 expansion_point_loc,
1731 				 num_macro_tokens);
1732     }
1733   i = 0;
1734   for (src = macro->exp.tokens; src < limit; src++)
1735     {
1736       unsigned int arg_tokens_count;
1737       macro_arg_token_iter from;
1738       const cpp_token **paste_flag = NULL;
1739       const cpp_token **tmp_token_ptr;
1740 
1741       if (src->type != CPP_MACRO_ARG)
1742 	{
1743 	  /* Allocate a virtual location for token SRC, and add that
1744 	     token and its virtual location into the buffers BUFF and
1745 	     VIRT_LOCS.  */
1746 	  unsigned index = expanded_token_index (pfile, macro, src, i);
1747 	  tokens_buff_add_token (buff, virt_locs, src,
1748 				 src->src_loc, src->src_loc,
1749 				 map, index);
1750 	  i += 1;
1751 	  continue;
1752 	}
1753 
1754       paste_flag = 0;
1755       arg = &args[src->val.macro_arg.arg_no - 1];
1756       /* SRC is a macro parameter that we need to replace with its
1757 	 corresponding argument.  So at some point we'll need to
1758 	 iterate over the tokens of the macro argument and copy them
1759 	 into the "place" now holding the correspondig macro
1760 	 parameter.  We are going to use the iterator type
1761 	 macro_argo_token_iter to handle that iterating.  The 'if'
1762 	 below is to initialize the iterator depending on the type of
1763 	 tokens the macro argument has.  It also does some adjustment
1764 	 related to padding tokens and some pasting corner cases.  */
1765       if (src->flags & STRINGIFY_ARG)
1766 	{
1767 	  arg_tokens_count = 1;
1768 	  macro_arg_token_iter_init (&from,
1769 				     CPP_OPTION (pfile,
1770 						 track_macro_expansion),
1771 				     MACRO_ARG_TOKEN_STRINGIFIED,
1772 				     arg, &arg->stringified);
1773 	}
1774       else if (src->flags & PASTE_LEFT)
1775 	{
1776 	  arg_tokens_count = arg->count;
1777 	  macro_arg_token_iter_init (&from,
1778 				     CPP_OPTION (pfile,
1779 						 track_macro_expansion),
1780 				     MACRO_ARG_TOKEN_NORMAL,
1781 				     arg, arg->first);
1782 	}
1783       else if (src != macro->exp.tokens && (src[-1].flags & PASTE_LEFT))
1784 	{
1785 	  int num_toks;
1786 	  arg_tokens_count = arg->count;
1787 	  macro_arg_token_iter_init (&from,
1788 				     CPP_OPTION (pfile,
1789 						 track_macro_expansion),
1790 				     MACRO_ARG_TOKEN_NORMAL,
1791 				     arg, arg->first);
1792 
1793 	  num_toks = tokens_buff_count (buff);
1794 
1795 	  if (num_toks != 0)
1796 	    {
1797 	      /* So the current parameter token is pasted to the previous
1798 		 token in the replacement list.  Let's look at what
1799 		 we have as previous and current arguments.  */
1800 
1801 	      /* This is the previous argument's token ...  */
1802 	      tmp_token_ptr = tokens_buff_last_token_ptr (buff);
1803 
1804 	      if ((*tmp_token_ptr)->type == CPP_COMMA
1805 		  && macro->variadic
1806 		  && src->val.macro_arg.arg_no == macro->paramc)
1807 		{
1808 		  /* ... which is a comma; and the current parameter
1809 		     is the last parameter of a variadic function-like
1810 		     macro.  If the argument to the current last
1811 		     parameter is NULL, then swallow the comma,
1812 		     otherwise drop the paste flag.  */
1813 		  if (macro_arg_token_iter_get_token (&from) == NULL)
1814 		    tokens_buff_remove_last_token (buff);
1815 		  else
1816 		    paste_flag = tmp_token_ptr;
1817 		}
1818 	      /* Remove the paste flag if the RHS is a placemarker.  */
1819 	      else if (arg_tokens_count == 0)
1820 		paste_flag = tmp_token_ptr;
1821 	    }
1822 	}
1823       else
1824 	{
1825 	  arg_tokens_count = arg->expanded_count;
1826 	  macro_arg_token_iter_init (&from,
1827 				     CPP_OPTION (pfile,
1828 						 track_macro_expansion),
1829 				     MACRO_ARG_TOKEN_EXPANDED,
1830 				     arg, arg->expanded);
1831 	}
1832 
1833       /* Padding on the left of an argument (unless RHS of ##).  */
1834       if ((!pfile->state.in_directive || pfile->state.directive_wants_padding)
1835 	  && src != macro->exp.tokens && !(src[-1].flags & PASTE_LEFT))
1836 	{
1837 	  const cpp_token *t = padding_token (pfile, src);
1838 	  unsigned index = expanded_token_index (pfile, macro, src, i);
1839 	  /* Allocate a virtual location for the padding token and
1840 	     append the token and its location to BUFF and
1841 	     VIRT_LOCS.   */
1842 	  tokens_buff_add_token (buff, virt_locs, t,
1843 				 t->src_loc, t->src_loc,
1844 				 map, index);
1845 	}
1846 
1847       if (arg_tokens_count)
1848 	{
1849 	  /* So now we've got the number of tokens that make up the
1850 	     argument that is going to replace the current parameter
1851 	     in the macro's replacement list.  */
1852 	  unsigned int j;
1853 	  for (j = 0; j < arg_tokens_count; ++j)
1854 	    {
1855 	      /* So if track_macro_exp is < 2, the user wants to
1856 		 save extra memory while tracking macro expansion
1857 		 locations.  So in that case here is what we do:
1858 
1859 		 Suppose we have #define SQARE(A) A * A
1860 
1861 		 And then we do SQARE(2+3)
1862 
1863 		 Then the tokens 2, +, 3, will have the same location,
1864 		 saying they come from the expansion of the argument
1865 		 A.
1866 
1867 	      So that means we are going to ignore the COUNT tokens
1868 	      resulting from the expansion of the current macro
1869 	      arugment. In other words all the ARG_TOKENS_COUNT tokens
1870 	      resulting from the expansion of the macro argument will
1871 	      have the index I. Normally, each of those token should
1872 	      have index I+J.  */
1873 	      unsigned token_index = i;
1874 	      unsigned index;
1875 	      if (track_macro_exp > 1)
1876 		token_index += j;
1877 
1878 	      index = expanded_token_index (pfile, macro, src, token_index);
1879 	      tokens_buff_add_token (buff, virt_locs,
1880 				     macro_arg_token_iter_get_token (&from),
1881 				     macro_arg_token_iter_get_location (&from),
1882 				     src->src_loc, map, index);
1883 	      macro_arg_token_iter_forward (&from);
1884 	    }
1885 
1886 	  /* With a non-empty argument on the LHS of ##, the last
1887 	     token should be flagged PASTE_LEFT.  */
1888 	  if (src->flags & PASTE_LEFT)
1889 	    paste_flag =
1890 	      (const cpp_token **) tokens_buff_last_token_ptr (buff);
1891 	}
1892       else if (CPP_PEDANTIC (pfile) && ! CPP_OPTION (pfile, c99)
1893 	       && ! macro->syshdr && ! cpp_in_system_header (pfile))
1894 	{
1895 	  if (CPP_OPTION (pfile, cplusplus))
1896 	    cpp_pedwarning (pfile, CPP_W_PEDANTIC,
1897 			    "invoking macro %s argument %d: "
1898 			    "empty macro arguments are undefined"
1899 			    " in ISO C++98",
1900 			    NODE_NAME (node), src->val.macro_arg.arg_no);
1901 	  else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat))
1902 	    cpp_pedwarning (pfile,
1903 			    CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
1904 			    ? CPP_W_C90_C99_COMPAT : CPP_W_PEDANTIC,
1905 			    "invoking macro %s argument %d: "
1906 			    "empty macro arguments are undefined"
1907 			    " in ISO C90",
1908 			    NODE_NAME (node), src->val.macro_arg.arg_no);
1909 	}
1910       else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
1911 	       && ! CPP_OPTION (pfile, cplusplus)
1912 	       && ! macro->syshdr && ! cpp_in_system_header (pfile))
1913 	cpp_warning (pfile, CPP_W_C90_C99_COMPAT,
1914 		     "invoking macro %s argument %d: "
1915 		     "empty macro arguments are undefined"
1916 		     " in ISO C90",
1917 		     NODE_NAME (node), src->val.macro_arg.arg_no);
1918 
1919       /* Avoid paste on RHS (even case count == 0).  */
1920       if (!pfile->state.in_directive && !(src->flags & PASTE_LEFT))
1921 	{
1922 	  const cpp_token *t = &pfile->avoid_paste;
1923 	  tokens_buff_add_token (buff, virt_locs,
1924 				 t, t->src_loc, t->src_loc,
1925 				 NULL, 0);
1926 	}
1927 
1928       /* Add a new paste flag, or remove an unwanted one.  */
1929       if (paste_flag)
1930 	{
1931 	  cpp_token *token = _cpp_temp_token (pfile);
1932 	  token->type = (*paste_flag)->type;
1933 	  token->val = (*paste_flag)->val;
1934 	  if (src->flags & PASTE_LEFT)
1935 	    token->flags = (*paste_flag)->flags | PASTE_LEFT;
1936 	  else
1937 	    token->flags = (*paste_flag)->flags & ~PASTE_LEFT;
1938 	  *paste_flag = token;
1939 	}
1940 
1941       i += arg_tokens_count;
1942     }
1943 
1944   if (track_macro_exp)
1945     push_extended_tokens_context (pfile, node, buff, virt_locs, first,
1946 				  tokens_buff_count (buff));
1947   else
1948     push_ptoken_context (pfile, node, buff, first,
1949 			 tokens_buff_count (buff));
1950 
1951   num_macro_tokens_counter += tokens_buff_count (buff);
1952 }
1953 
1954 /* Return a special padding token, with padding inherited from SOURCE.  */
1955 static const cpp_token *
1956 padding_token (cpp_reader *pfile, const cpp_token *source)
1957 {
1958   cpp_token *result = _cpp_temp_token (pfile);
1959 
1960   result->type = CPP_PADDING;
1961 
1962   /* Data in GCed data structures cannot be made const so far, so we
1963      need a cast here.  */
1964   result->val.source = (cpp_token *) source;
1965   result->flags = 0;
1966   return result;
1967 }
1968 
1969 /* Get a new uninitialized context.  Create a new one if we cannot
1970    re-use an old one.  */
1971 static cpp_context *
1972 next_context (cpp_reader *pfile)
1973 {
1974   cpp_context *result = pfile->context->next;
1975 
1976   if (result == 0)
1977     {
1978       result = XNEW (cpp_context);
1979       memset (result, 0, sizeof (cpp_context));
1980       result->prev = pfile->context;
1981       result->next = 0;
1982       pfile->context->next = result;
1983     }
1984 
1985   pfile->context = result;
1986   return result;
1987 }
1988 
1989 /* Push a list of pointers to tokens.  */
1990 static void
1991 push_ptoken_context (cpp_reader *pfile, cpp_hashnode *macro, _cpp_buff *buff,
1992 		     const cpp_token **first, unsigned int count)
1993 {
1994   cpp_context *context = next_context (pfile);
1995 
1996   context->tokens_kind = TOKENS_KIND_INDIRECT;
1997   context->c.macro = macro;
1998   context->buff = buff;
1999   FIRST (context).ptoken = first;
2000   LAST (context).ptoken = first + count;
2001 }
2002 
2003 /* Push a list of tokens.
2004 
2005    A NULL macro means that we should continue the current macro
2006    expansion, in essence.  That means that if we are currently in a
2007    macro expansion context, we'll make the new pfile->context refer to
2008    the current macro.  */
2009 void
2010 _cpp_push_token_context (cpp_reader *pfile, cpp_hashnode *macro,
2011 			 const cpp_token *first, unsigned int count)
2012 {
2013   cpp_context *context;
2014 
2015    if (macro == NULL)
2016      macro = macro_of_context (pfile->context);
2017 
2018    context = next_context (pfile);
2019    context->tokens_kind = TOKENS_KIND_DIRECT;
2020    context->c.macro = macro;
2021    context->buff = NULL;
2022    FIRST (context).token = first;
2023    LAST (context).token = first + count;
2024 }
2025 
2026 /* Build a context containing a list of tokens as well as their
2027    virtual locations and push it.  TOKENS_BUFF is the buffer that
2028    contains the tokens pointed to by FIRST.  If TOKENS_BUFF is
2029    non-NULL, it means that the context owns it, meaning that
2030    _cpp_pop_context will free it as well as VIRT_LOCS_BUFF that
2031    contains the virtual locations.
2032 
2033    A NULL macro means that we should continue the current macro
2034    expansion, in essence.  That means that if we are currently in a
2035    macro expansion context, we'll make the new pfile->context refer to
2036    the current macro.  */
2037 static void
2038 push_extended_tokens_context (cpp_reader *pfile,
2039 			      cpp_hashnode *macro,
2040 			      _cpp_buff *token_buff,
2041 			      source_location *virt_locs,
2042 			      const cpp_token **first,
2043 			      unsigned int count)
2044 {
2045   cpp_context *context;
2046   macro_context *m;
2047 
2048   if (macro == NULL)
2049     macro = macro_of_context (pfile->context);
2050 
2051   context = next_context (pfile);
2052   context->tokens_kind = TOKENS_KIND_EXTENDED;
2053   context->buff = token_buff;
2054 
2055   m = XNEW (macro_context);
2056   m->macro_node = macro;
2057   m->virt_locs = virt_locs;
2058   m->cur_virt_loc = virt_locs;
2059   context->c.mc = m;
2060   FIRST (context).ptoken = first;
2061   LAST (context).ptoken = first + count;
2062 }
2063 
2064 /* Push a traditional macro's replacement text.  */
2065 void
2066 _cpp_push_text_context (cpp_reader *pfile, cpp_hashnode *macro,
2067 			const uchar *start, size_t len)
2068 {
2069   cpp_context *context = next_context (pfile);
2070 
2071   context->tokens_kind = TOKENS_KIND_DIRECT;
2072   context->c.macro = macro;
2073   context->buff = NULL;
2074   CUR (context) = start;
2075   RLIMIT (context) = start + len;
2076   macro->flags |= NODE_DISABLED;
2077 }
2078 
2079 /* Creates a buffer that holds tokens a.k.a "token buffer", usually
2080    for the purpose of storing them on a cpp_context. If VIRT_LOCS is
2081    non-null (which means that -ftrack-macro-expansion is on),
2082    *VIRT_LOCS is set to a newly allocated buffer that is supposed to
2083    hold the virtual locations of the tokens resulting from macro
2084    expansion.  */
2085 static _cpp_buff*
2086 tokens_buff_new (cpp_reader *pfile, size_t len,
2087 		 source_location **virt_locs)
2088 {
2089   size_t tokens_size = len * sizeof (cpp_token *);
2090   size_t locs_size = len * sizeof (source_location);
2091 
2092   if (virt_locs != NULL)
2093     *virt_locs = XNEWVEC (source_location, locs_size);
2094   return _cpp_get_buff (pfile, tokens_size);
2095 }
2096 
2097 /* Returns the number of tokens contained in a token buffer.  The
2098    buffer holds a set of cpp_token*.  */
2099 static size_t
2100 tokens_buff_count (_cpp_buff *buff)
2101 {
2102   return (BUFF_FRONT (buff) - buff->base) / sizeof (cpp_token *);
2103 }
2104 
2105 /* Return a pointer to the last token contained in the token buffer
2106    BUFF.  */
2107 static const cpp_token **
2108 tokens_buff_last_token_ptr (_cpp_buff *buff)
2109 {
2110   return &((const cpp_token **) BUFF_FRONT (buff))[-1];
2111 }
2112 
2113 /* Remove the last token contained in the token buffer TOKENS_BUFF.
2114    If VIRT_LOCS_BUFF is non-NULL,  it should point at the buffer
2115    containing the virtual locations of the tokens in TOKENS_BUFF; in
2116    which case the function updates that buffer as well.   */
2117 static inline void
2118 tokens_buff_remove_last_token (_cpp_buff *tokens_buff)
2119 
2120 {
2121   if (BUFF_FRONT (tokens_buff) > tokens_buff->base)
2122     BUFF_FRONT (tokens_buff) =
2123       (unsigned char *) &((cpp_token **) BUFF_FRONT (tokens_buff))[-1];
2124 }
2125 
2126 /* Insert a token into the token buffer at the position pointed to by
2127    DEST.  Note that the buffer is not enlarged so the previous token
2128    that was at *DEST is overwritten.  VIRT_LOC_DEST, if non-null,
2129    means -ftrack-macro-expansion is effect; it then points to where to
2130    insert the virtual location of TOKEN.  TOKEN is the token to
2131    insert.  VIRT_LOC is the virtual location of the token, i.e, the
2132    location possibly encoding its locus across macro expansion.  If
2133    TOKEN is an argument of a function-like macro (inside a macro
2134    replacement list), PARM_DEF_LOC is the spelling location of the
2135    macro parameter that TOKEN is replacing, in the replacement list of
2136    the macro.  If TOKEN is not an argument of a function-like macro or
2137    if it doesn't come from a macro expansion, then VIRT_LOC can just
2138    be set to the same value as PARM_DEF_LOC.  If MAP is non null, it
2139    means TOKEN comes from a macro expansion and MAP is the macro map
2140    associated to the macro.  MACRO_TOKEN_INDEX points to the index of
2141    the token in the macro map; it is not considered if MAP is NULL.
2142 
2143    Upon successful completion this function returns the a pointer to
2144    the position of the token coming right after the insertion
2145    point.  */
2146 static inline const cpp_token **
2147 tokens_buff_put_token_to (const cpp_token **dest,
2148 			  source_location *virt_loc_dest,
2149 			  const cpp_token *token,
2150 			  source_location virt_loc,
2151 			  source_location parm_def_loc,
2152 			  const line_map_macro *map,
2153 			  unsigned int macro_token_index)
2154 {
2155   source_location macro_loc = virt_loc;
2156   const cpp_token **result;
2157 
2158   if (virt_loc_dest)
2159     {
2160       /* -ftrack-macro-expansion is on.  */
2161       if (map)
2162 	macro_loc = linemap_add_macro_token (map, macro_token_index,
2163 					     virt_loc, parm_def_loc);
2164       *virt_loc_dest = macro_loc;
2165     }
2166   *dest = token;
2167   result = &dest[1];
2168 
2169   return result;
2170 }
2171 
2172 /* Adds a token at the end of the tokens contained in BUFFER.  Note
2173    that this function doesn't enlarge BUFFER when the number of tokens
2174    reaches BUFFER's size; it aborts in that situation.
2175 
2176    TOKEN is the token to append. VIRT_LOC is the virtual location of
2177    the token, i.e, the location possibly encoding its locus across
2178    macro expansion. If TOKEN is an argument of a function-like macro
2179    (inside a macro replacement list), PARM_DEF_LOC is the location of
2180    the macro parameter that TOKEN is replacing.  If TOKEN doesn't come
2181    from a macro expansion, then VIRT_LOC can just be set to the same
2182    value as PARM_DEF_LOC.  If MAP is non null, it means TOKEN comes
2183    from a macro expansion and MAP is the macro map associated to the
2184    macro.  MACRO_TOKEN_INDEX points to the index of the token in the
2185    macro map; It is not considered if MAP is NULL.  If VIRT_LOCS is
2186    non-null, it means -ftrack-macro-expansion is on; in which case
2187    this function adds the virtual location DEF_LOC to the VIRT_LOCS
2188    array, at the same index as the one of TOKEN in BUFFER.  Upon
2189    successful completion this function returns the a pointer to the
2190    position of the token coming right after the insertion point.  */
2191 static const cpp_token **
2192 tokens_buff_add_token (_cpp_buff *buffer,
2193 		       source_location *virt_locs,
2194 		       const cpp_token *token,
2195 		       source_location virt_loc,
2196 		       source_location parm_def_loc,
2197 		       const line_map_macro *map,
2198 		       unsigned int macro_token_index)
2199 {
2200   const cpp_token **result;
2201   source_location *virt_loc_dest = NULL;
2202   unsigned token_index =
2203     (BUFF_FRONT (buffer) - buffer->base) / sizeof (cpp_token *);
2204 
2205   /* Abort if we pass the end the buffer.  */
2206   if (BUFF_FRONT (buffer) > BUFF_LIMIT (buffer))
2207     abort ();
2208 
2209   if (virt_locs != NULL)
2210     virt_loc_dest = &virt_locs[token_index];
2211 
2212   result =
2213     tokens_buff_put_token_to ((const cpp_token **) BUFF_FRONT (buffer),
2214 			      virt_loc_dest, token, virt_loc, parm_def_loc,
2215 			      map, macro_token_index);
2216 
2217   BUFF_FRONT (buffer) = (unsigned char *) result;
2218   return result;
2219 }
2220 
2221 /* Allocate space for the function-like macro argument ARG to store
2222    the tokens resulting from the macro-expansion of the tokens that
2223    make up ARG itself. That space is allocated in ARG->expanded and
2224    needs to be freed using free.  */
2225 static void
2226 alloc_expanded_arg_mem (cpp_reader *pfile, macro_arg *arg, size_t capacity)
2227 {
2228   gcc_checking_assert (arg->expanded == NULL
2229 		       && arg->expanded_virt_locs == NULL);
2230 
2231   arg->expanded = XNEWVEC (const cpp_token *, capacity);
2232   if (CPP_OPTION (pfile, track_macro_expansion))
2233     arg->expanded_virt_locs = XNEWVEC (source_location, capacity);
2234 
2235 }
2236 
2237 /* If necessary, enlarge ARG->expanded to so that it can contain SIZE
2238    tokens.  */
2239 static void
2240 ensure_expanded_arg_room (cpp_reader *pfile, macro_arg *arg,
2241 			  size_t size, size_t *expanded_capacity)
2242 {
2243   if (size <= *expanded_capacity)
2244     return;
2245 
2246   size *= 2;
2247 
2248   arg->expanded =
2249     XRESIZEVEC (const cpp_token *, arg->expanded, size);
2250   *expanded_capacity = size;
2251 
2252   if (CPP_OPTION (pfile, track_macro_expansion))
2253     {
2254       if (arg->expanded_virt_locs == NULL)
2255 	arg->expanded_virt_locs = XNEWVEC (source_location, size);
2256       else
2257 	arg->expanded_virt_locs = XRESIZEVEC (source_location,
2258 					      arg->expanded_virt_locs,
2259 					      size);
2260     }
2261 }
2262 
2263 /* Expand an argument ARG before replacing parameters in a
2264    function-like macro.  This works by pushing a context with the
2265    argument's tokens, and then expanding that into a temporary buffer
2266    as if it were a normal part of the token stream.  collect_args()
2267    has terminated the argument's tokens with a CPP_EOF so that we know
2268    when we have fully expanded the argument.  */
2269 static void
2270 expand_arg (cpp_reader *pfile, macro_arg *arg)
2271 {
2272   size_t capacity;
2273   bool saved_warn_trad;
2274   bool track_macro_exp_p = CPP_OPTION (pfile, track_macro_expansion);
2275 
2276   if (arg->count == 0
2277       || arg->expanded != NULL)
2278     return;
2279 
2280   /* Don't warn about funlike macros when pre-expanding.  */
2281   saved_warn_trad = CPP_WTRADITIONAL (pfile);
2282   CPP_WTRADITIONAL (pfile) = 0;
2283 
2284   /* Loop, reading in the tokens of the argument.  */
2285   capacity = 256;
2286   alloc_expanded_arg_mem (pfile, arg, capacity);
2287 
2288   if (track_macro_exp_p)
2289     push_extended_tokens_context (pfile, NULL, NULL,
2290 				  arg->virt_locs,
2291 				  arg->first,
2292 				  arg->count + 1);
2293   else
2294     push_ptoken_context (pfile, NULL, NULL,
2295 			 arg->first, arg->count + 1);
2296 
2297   for (;;)
2298     {
2299       const cpp_token *token;
2300       source_location location;
2301 
2302       ensure_expanded_arg_room (pfile, arg, arg->expanded_count + 1,
2303 				&capacity);
2304 
2305       token = cpp_get_token_1 (pfile, &location);
2306 
2307       if (token->type == CPP_EOF)
2308 	break;
2309 
2310       set_arg_token (arg, token, location,
2311 		     arg->expanded_count, MACRO_ARG_TOKEN_EXPANDED,
2312 		     CPP_OPTION (pfile, track_macro_expansion));
2313       arg->expanded_count++;
2314     }
2315 
2316   _cpp_pop_context (pfile);
2317 
2318   CPP_WTRADITIONAL (pfile) = saved_warn_trad;
2319 }
2320 
2321 /* Returns the macro associated to the current context if we are in
2322    the context a macro expansion, NULL otherwise.  */
2323 static cpp_hashnode*
2324 macro_of_context (cpp_context *context)
2325 {
2326   if (context == NULL)
2327     return NULL;
2328 
2329   return (context->tokens_kind == TOKENS_KIND_EXTENDED)
2330     ? context->c.mc->macro_node
2331     : context->c.macro;
2332 }
2333 
2334 /* Return TRUE iff we are expanding a macro or are about to start
2335    expanding one.  If we are effectively expanding a macro, the
2336    function macro_of_context returns a pointer to the macro being
2337    expanded.  */
2338 static bool
2339 in_macro_expansion_p (cpp_reader *pfile)
2340 {
2341   if (pfile == NULL)
2342     return false;
2343 
2344   return (pfile->about_to_expand_macro_p
2345 	  || macro_of_context (pfile->context));
2346 }
2347 
2348 /* Pop the current context off the stack, re-enabling the macro if the
2349    context represented a macro's replacement list.  Initially the
2350    context structure was not freed so that we can re-use it later, but
2351    now we do free it to reduce peak memory consumption.  */
2352 void
2353 _cpp_pop_context (cpp_reader *pfile)
2354 {
2355   cpp_context *context = pfile->context;
2356 
2357   /* We should not be popping the base context.  */
2358   if (context == &pfile->base_context)
2359     abort ();
2360 
2361   if (context->c.macro)
2362     {
2363       cpp_hashnode *macro;
2364       if (context->tokens_kind == TOKENS_KIND_EXTENDED)
2365 	{
2366 	  macro_context *mc = context->c.mc;
2367 	  macro = mc->macro_node;
2368 	  /* If context->buff is set, it means the life time of tokens
2369 	     is bound to the life time of this context; so we must
2370 	     free the tokens; that means we must free the virtual
2371 	     locations of these tokens too.  */
2372 	  if (context->buff && mc->virt_locs)
2373 	    {
2374 	      free (mc->virt_locs);
2375 	      mc->virt_locs = NULL;
2376 	    }
2377 	  free (mc);
2378 	  context->c.mc = NULL;
2379 	}
2380       else
2381 	macro = context->c.macro;
2382 
2383       /* Beware that MACRO can be NULL in cases like when we are
2384 	 called from expand_arg.  In those cases, a dummy context with
2385 	 tokens is pushed just for the purpose of walking them using
2386 	 cpp_get_token_1.  In that case, no 'macro' field is set into
2387 	 the dummy context.  */
2388       if (macro != NULL
2389 	  /* Several contiguous macro expansion contexts can be
2390 	     associated to the same macro; that means it's the same
2391 	     macro expansion that spans across all these (sub)
2392 	     contexts.  So we should re-enable an expansion-disabled
2393 	     macro only when we are sure we are really out of that
2394 	     macro expansion.  */
2395 	  && macro_of_context (context->prev) != macro)
2396 	macro->flags &= ~NODE_DISABLED;
2397 
2398       if (macro == pfile->top_most_macro_node && context->prev == NULL)
2399 	/* We are popping the context of the top-most macro node.  */
2400 	pfile->top_most_macro_node = NULL;
2401     }
2402 
2403   if (context->buff)
2404     {
2405       /* Decrease memory peak consumption by freeing the memory used
2406 	 by the context.  */
2407       _cpp_free_buff (context->buff);
2408     }
2409 
2410   pfile->context = context->prev;
2411   /* decrease peak memory consumption by feeing the context.  */
2412   pfile->context->next = NULL;
2413   free (context);
2414 }
2415 
2416 /* Return TRUE if we reached the end of the set of tokens stored in
2417    CONTEXT, FALSE otherwise.  */
2418 static inline bool
2419 reached_end_of_context (cpp_context *context)
2420 {
2421   if (context->tokens_kind == TOKENS_KIND_DIRECT)
2422       return FIRST (context).token == LAST (context).token;
2423   else if (context->tokens_kind == TOKENS_KIND_INDIRECT
2424 	   || context->tokens_kind == TOKENS_KIND_EXTENDED)
2425     return FIRST (context).ptoken == LAST (context).ptoken;
2426   else
2427     abort ();
2428 }
2429 
2430 /* Consume the next token contained in the current context of PFILE,
2431    and return it in *TOKEN. It's "full location" is returned in
2432    *LOCATION. If -ftrack-macro-location is in effeect, fFull location"
2433    means the location encoding the locus of the token across macro
2434    expansion; otherwise it's just is the "normal" location of the
2435    token which (*TOKEN)->src_loc.  */
2436 static inline void
2437 consume_next_token_from_context (cpp_reader *pfile,
2438 				 const cpp_token ** token,
2439 				 source_location *location)
2440 {
2441   cpp_context *c = pfile->context;
2442 
2443   if ((c)->tokens_kind == TOKENS_KIND_DIRECT)
2444     {
2445       *token = FIRST (c).token;
2446       *location = (*token)->src_loc;
2447       FIRST (c).token++;
2448     }
2449   else if ((c)->tokens_kind == TOKENS_KIND_INDIRECT)
2450     {
2451       *token = *FIRST (c).ptoken;
2452       *location = (*token)->src_loc;
2453       FIRST (c).ptoken++;
2454     }
2455   else if ((c)->tokens_kind == TOKENS_KIND_EXTENDED)
2456     {
2457       macro_context *m = c->c.mc;
2458       *token = *FIRST (c).ptoken;
2459       if (m->virt_locs)
2460 	{
2461 	  *location = *m->cur_virt_loc;
2462 	  m->cur_virt_loc++;
2463 	}
2464       else
2465 	*location = (*token)->src_loc;
2466       FIRST (c).ptoken++;
2467     }
2468   else
2469     abort ();
2470 }
2471 
2472 /* In the traditional mode of the preprocessor, if we are currently in
2473    a directive, the location of a token must be the location of the
2474    start of the directive line.  This function returns the proper
2475    location if we are in the traditional mode, and just returns
2476    LOCATION otherwise.  */
2477 
2478 static inline source_location
2479 maybe_adjust_loc_for_trad_cpp (cpp_reader *pfile, source_location location)
2480 {
2481   if (CPP_OPTION (pfile, traditional))
2482     {
2483       if (pfile->state.in_directive)
2484 	return pfile->directive_line;
2485     }
2486   return location;
2487 }
2488 
2489 /* Routine to get a token as well as its location.
2490 
2491    Macro expansions and directives are transparently handled,
2492    including entering included files.  Thus tokens are post-macro
2493    expansion, and after any intervening directives.  External callers
2494    see CPP_EOF only at EOF.  Internal callers also see it when meeting
2495    a directive inside a macro call, when at the end of a directive and
2496    state.in_directive is still 1, and at the end of argument
2497    pre-expansion.
2498 
2499    LOC is an out parameter; *LOC is set to the location "as expected
2500    by the user".  Please read the comment of
2501    cpp_get_token_with_location to learn more about the meaning of this
2502    location.  */
2503 static const cpp_token*
2504 cpp_get_token_1 (cpp_reader *pfile, source_location *location)
2505 {
2506   const cpp_token *result;
2507   /* This token is a virtual token that either encodes a location
2508      related to macro expansion or a spelling location.  */
2509   source_location virt_loc = 0;
2510   /* pfile->about_to_expand_macro_p can be overriden by indirect calls
2511      to functions that push macro contexts.  So let's save it so that
2512      we can restore it when we are about to leave this routine.  */
2513   bool saved_about_to_expand_macro = pfile->about_to_expand_macro_p;
2514 
2515   for (;;)
2516     {
2517       cpp_hashnode *node;
2518       cpp_context *context = pfile->context;
2519 
2520       /* Context->prev == 0 <=> base context.  */
2521       if (!context->prev)
2522 	{
2523 	  result = _cpp_lex_token (pfile);
2524 	  virt_loc = result->src_loc;
2525 	}
2526       else if (!reached_end_of_context (context))
2527 	{
2528 	  consume_next_token_from_context (pfile, &result,
2529 					   &virt_loc);
2530 	  if (result->flags & PASTE_LEFT)
2531 	    {
2532 	      paste_all_tokens (pfile, result);
2533 	      if (pfile->state.in_directive)
2534 		continue;
2535 	      result = padding_token (pfile, result);
2536 	      goto out;
2537 	    }
2538 	}
2539       else
2540 	{
2541 	  if (pfile->context->c.macro)
2542 	    ++num_expanded_macros_counter;
2543 	  _cpp_pop_context (pfile);
2544 	  if (pfile->state.in_directive)
2545 	    continue;
2546 	  result = &pfile->avoid_paste;
2547 	  goto out;
2548 	}
2549 
2550       if (pfile->state.in_directive && result->type == CPP_COMMENT)
2551 	continue;
2552 
2553       if (result->type != CPP_NAME)
2554 	break;
2555 
2556       node = result->val.node.node;
2557 
2558       if (node->type != NT_MACRO || (result->flags & NO_EXPAND))
2559 	break;
2560 
2561       if (!(node->flags & NODE_DISABLED))
2562 	{
2563 	  int ret = 0;
2564 	  /* If not in a macro context, and we're going to start an
2565 	     expansion, record the location and the top level macro
2566 	     about to be expanded.  */
2567 	  if (!in_macro_expansion_p (pfile))
2568 	    {
2569 	      pfile->invocation_location = result->src_loc;
2570 	      pfile->top_most_macro_node = node;
2571 	    }
2572 	  if (pfile->state.prevent_expansion)
2573 	    break;
2574 
2575 	  /* Conditional macros require that a predicate be evaluated
2576 	     first.  */
2577 	  if ((node->flags & NODE_CONDITIONAL) != 0)
2578 	    {
2579 	      if (pfile->cb.macro_to_expand)
2580 		{
2581 		  bool whitespace_after;
2582 		  const cpp_token *peek_tok = cpp_peek_token (pfile, 0);
2583 
2584 		  whitespace_after = (peek_tok->type == CPP_PADDING
2585 				      || (peek_tok->flags & PREV_WHITE));
2586 		  node = pfile->cb.macro_to_expand (pfile, result);
2587 		  if (node)
2588 		    ret = enter_macro_context (pfile, node, result,
2589 					       virt_loc);
2590 		  else if (whitespace_after)
2591 		    {
2592 		      /* If macro_to_expand hook returned NULL and it
2593 			 ate some tokens, see if we don't need to add
2594 			 a padding token in between this and the
2595 			 next token.  */
2596 		      peek_tok = cpp_peek_token (pfile, 0);
2597 		      if (peek_tok->type != CPP_PADDING
2598 			  && (peek_tok->flags & PREV_WHITE) == 0)
2599 			_cpp_push_token_context (pfile, NULL,
2600 						 padding_token (pfile,
2601 								peek_tok), 1);
2602 		    }
2603 		}
2604 	    }
2605 	  else
2606 	    ret = enter_macro_context (pfile, node, result,
2607 				       virt_loc);
2608 	  if (ret)
2609  	    {
2610 	      if (pfile->state.in_directive || ret == 2)
2611 		continue;
2612 	      result = padding_token (pfile, result);
2613 	      goto out;
2614 	    }
2615 	}
2616       else
2617 	{
2618 	  /* Flag this token as always unexpandable.  FIXME: move this
2619 	     to collect_args()?.  */
2620 	  cpp_token *t = _cpp_temp_token (pfile);
2621 	  t->type = result->type;
2622 	  t->flags = result->flags | NO_EXPAND;
2623 	  t->val = result->val;
2624 	  result = t;
2625 	}
2626 
2627       break;
2628     }
2629 
2630  out:
2631   if (location != NULL)
2632     {
2633       if (virt_loc == 0)
2634 	virt_loc = result->src_loc;
2635       *location = virt_loc;
2636 
2637       if (!CPP_OPTION (pfile, track_macro_expansion)
2638 	  && macro_of_context (pfile->context) != NULL)
2639 	/* We are in a macro expansion context, are not tracking
2640 	   virtual location, but were asked to report the location
2641 	   of the expansion point of the macro being expanded.  */
2642 	*location = pfile->invocation_location;
2643 
2644       *location = maybe_adjust_loc_for_trad_cpp (pfile, *location);
2645     }
2646 
2647   pfile->about_to_expand_macro_p = saved_about_to_expand_macro;
2648   return result;
2649 }
2650 
2651 /* External routine to get a token.  Also used nearly everywhere
2652    internally, except for places where we know we can safely call
2653    _cpp_lex_token directly, such as lexing a directive name.
2654 
2655    Macro expansions and directives are transparently handled,
2656    including entering included files.  Thus tokens are post-macro
2657    expansion, and after any intervening directives.  External callers
2658    see CPP_EOF only at EOF.  Internal callers also see it when meeting
2659    a directive inside a macro call, when at the end of a directive and
2660    state.in_directive is still 1, and at the end of argument
2661    pre-expansion.  */
2662 const cpp_token *
2663 cpp_get_token (cpp_reader *pfile)
2664 {
2665   return cpp_get_token_1 (pfile, NULL);
2666 }
2667 
2668 /* Like cpp_get_token, but also returns a virtual token location
2669    separate from the spelling location carried by the returned token.
2670 
2671    LOC is an out parameter; *LOC is set to the location "as expected
2672    by the user".  This matters when a token results from macro
2673    expansion; in that case the token's spelling location indicates the
2674    locus of the token in the definition of the macro but *LOC
2675    virtually encodes all the other meaningful locuses associated to
2676    the token.
2677 
2678    What? virtual location? Yes, virtual location.
2679 
2680    If the token results from macro expansion and if macro expansion
2681    location tracking is enabled its virtual location encodes (at the
2682    same time):
2683 
2684    - the spelling location of the token
2685 
2686    - the locus of the macro expansion point
2687 
2688    - the locus of the point where the token got instantiated as part
2689      of the macro expansion process.
2690 
2691    You have to use the linemap API to get the locus you are interested
2692    in from a given virtual location.
2693 
2694    Note however that virtual locations are not necessarily ordered for
2695    relations '<' and '>'.  One must use the function
2696    linemap_location_before_p instead of using the relational operator
2697    '<'.
2698 
2699    If macro expansion tracking is off and if the token results from
2700    macro expansion the virtual location is the expansion point of the
2701    macro that got expanded.
2702 
2703    When the token doesn't result from macro expansion, the virtual
2704    location is just the same thing as its spelling location.  */
2705 
2706 const cpp_token *
2707 cpp_get_token_with_location (cpp_reader *pfile, source_location *loc)
2708 {
2709   return cpp_get_token_1 (pfile, loc);
2710 }
2711 
2712 /* Returns true if we're expanding an object-like macro that was
2713    defined in a system header.  Just checks the macro at the top of
2714    the stack.  Used for diagnostic suppression.  */
2715 int
2716 cpp_sys_macro_p (cpp_reader *pfile)
2717 {
2718   cpp_hashnode *node = NULL;
2719 
2720   if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2721     node = pfile->context->c.mc->macro_node;
2722   else
2723     node = pfile->context->c.macro;
2724 
2725   return node && node->value.macro && node->value.macro->syshdr;
2726 }
2727 
2728 /* Read each token in, until end of the current file.  Directives are
2729    transparently processed.  */
2730 void
2731 cpp_scan_nooutput (cpp_reader *pfile)
2732 {
2733   /* Request a CPP_EOF token at the end of this file, rather than
2734      transparently continuing with the including file.  */
2735   pfile->buffer->return_at_eof = true;
2736 
2737   pfile->state.discarding_output++;
2738   pfile->state.prevent_expansion++;
2739 
2740   if (CPP_OPTION (pfile, traditional))
2741     while (_cpp_read_logical_line_trad (pfile))
2742       ;
2743   else
2744     while (cpp_get_token (pfile)->type != CPP_EOF)
2745       ;
2746 
2747   pfile->state.discarding_output--;
2748   pfile->state.prevent_expansion--;
2749 }
2750 
2751 /* Step back one or more tokens obtained from the lexer.  */
2752 void
2753 _cpp_backup_tokens_direct (cpp_reader *pfile, unsigned int count)
2754 {
2755   pfile->lookaheads += count;
2756   while (count--)
2757     {
2758       pfile->cur_token--;
2759       if (pfile->cur_token == pfile->cur_run->base
2760           /* Possible with -fpreprocessed and no leading #line.  */
2761           && pfile->cur_run->prev != NULL)
2762         {
2763           pfile->cur_run = pfile->cur_run->prev;
2764           pfile->cur_token = pfile->cur_run->limit;
2765         }
2766     }
2767 }
2768 
2769 /* Step back one (or more) tokens.  Can only step back more than 1 if
2770    they are from the lexer, and not from macro expansion.  */
2771 void
2772 _cpp_backup_tokens (cpp_reader *pfile, unsigned int count)
2773 {
2774   if (pfile->context->prev == NULL)
2775     _cpp_backup_tokens_direct (pfile, count);
2776   else
2777     {
2778       if (count != 1)
2779 	abort ();
2780       if (pfile->context->tokens_kind == TOKENS_KIND_DIRECT)
2781 	FIRST (pfile->context).token--;
2782       else if (pfile->context->tokens_kind == TOKENS_KIND_INDIRECT)
2783 	FIRST (pfile->context).ptoken--;
2784       else if (pfile->context->tokens_kind == TOKENS_KIND_EXTENDED)
2785 	{
2786 	  FIRST (pfile->context).ptoken--;
2787 	  if (pfile->context->c.macro)
2788 	    {
2789 	      macro_context *m = pfile->context->c.mc;
2790 	      m->cur_virt_loc--;
2791 	      gcc_checking_assert (m->cur_virt_loc >= m->virt_locs);
2792 	    }
2793 	  else
2794 	    abort ();
2795 	}
2796       else
2797 	abort ();
2798     }
2799 }
2800 
2801 /* #define directive parsing and handling.  */
2802 
2803 /* Returns nonzero if a macro redefinition warning is required.  */
2804 static bool
2805 warn_of_redefinition (cpp_reader *pfile, cpp_hashnode *node,
2806 		      const cpp_macro *macro2)
2807 {
2808   const cpp_macro *macro1;
2809   unsigned int i;
2810 
2811   /* Some redefinitions need to be warned about regardless.  */
2812   if (node->flags & NODE_WARN)
2813     return true;
2814 
2815   /* Suppress warnings for builtins that lack the NODE_WARN flag,
2816      unless Wbuiltin-macro-redefined.  */
2817   if (node->flags & NODE_BUILTIN
2818       && (!pfile->cb.user_builtin_macro
2819 	  || !pfile->cb.user_builtin_macro (pfile, node)))
2820     return CPP_OPTION (pfile, warn_builtin_macro_redefined);
2821 
2822   /* Redefinitions of conditional (context-sensitive) macros, on
2823      the other hand, must be allowed silently.  */
2824   if (node->flags & NODE_CONDITIONAL)
2825     return false;
2826 
2827   /* Redefinition of a macro is allowed if and only if the old and new
2828      definitions are the same.  (6.10.3 paragraph 2).  */
2829   macro1 = node->value.macro;
2830 
2831   /* Don't check count here as it can be different in valid
2832      traditional redefinitions with just whitespace differences.  */
2833   if (macro1->paramc != macro2->paramc
2834       || macro1->fun_like != macro2->fun_like
2835       || macro1->variadic != macro2->variadic)
2836     return true;
2837 
2838   /* Check parameter spellings.  */
2839   for (i = 0; i < macro1->paramc; i++)
2840     if (macro1->params[i] != macro2->params[i])
2841       return true;
2842 
2843   /* Check the replacement text or tokens.  */
2844   if (CPP_OPTION (pfile, traditional))
2845     return _cpp_expansions_different_trad (macro1, macro2);
2846 
2847   if (macro1->count != macro2->count)
2848     return true;
2849 
2850   for (i = 0; i < macro1->count; i++)
2851     if (!_cpp_equiv_tokens (&macro1->exp.tokens[i], &macro2->exp.tokens[i]))
2852       return true;
2853 
2854   return false;
2855 }
2856 
2857 /* Free the definition of hashnode H.  */
2858 void
2859 _cpp_free_definition (cpp_hashnode *h)
2860 {
2861   /* Macros and assertions no longer have anything to free.  */
2862   h->type = NT_VOID;
2863   /* Clear builtin flag in case of redefinition.  */
2864   h->flags &= ~(NODE_BUILTIN | NODE_DISABLED | NODE_USED);
2865 }
2866 
2867 /* Save parameter NODE (spelling SPELLING) to the parameter list of
2868    macro MACRO.  Returns zero on success, nonzero if the parameter is
2869    a duplicate.  */
2870 bool
2871 _cpp_save_parameter (cpp_reader *pfile, cpp_macro *macro, cpp_hashnode *node,
2872 		     cpp_hashnode *spelling)
2873 {
2874   unsigned int len;
2875   /* Constraint 6.10.3.6 - duplicate parameter names.  */
2876   if (node->flags & NODE_MACRO_ARG)
2877     {
2878       cpp_error (pfile, CPP_DL_ERROR, "duplicate macro parameter \"%s\"",
2879 		 NODE_NAME (node));
2880       return true;
2881     }
2882 
2883   if (BUFF_ROOM (pfile->a_buff)
2884       < (macro->paramc + 1) * sizeof (cpp_hashnode *))
2885     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_hashnode *));
2886 
2887   ((cpp_hashnode **) BUFF_FRONT (pfile->a_buff))[macro->paramc++] = spelling;
2888   node->flags |= NODE_MACRO_ARG;
2889   len = macro->paramc * sizeof (struct macro_arg_saved_data);
2890   if (len > pfile->macro_buffer_len)
2891     {
2892       pfile->macro_buffer = XRESIZEVEC (unsigned char, pfile->macro_buffer,
2893                                         len);
2894       pfile->macro_buffer_len = len;
2895     }
2896   struct macro_arg_saved_data save;
2897   save.value = node->value;
2898   save.canonical_node = node;
2899   ((struct macro_arg_saved_data *) pfile->macro_buffer)[macro->paramc - 1]
2900     = save;
2901 
2902   node->value.arg_index  = macro->paramc;
2903   return false;
2904 }
2905 
2906 /* Check the syntax of the parameters in a MACRO definition.  Returns
2907    false if an error occurs.  */
2908 static bool
2909 parse_params (cpp_reader *pfile, cpp_macro *macro)
2910 {
2911   unsigned int prev_ident = 0;
2912 
2913   for (;;)
2914     {
2915       const cpp_token *token = _cpp_lex_token (pfile);
2916 
2917       switch (token->type)
2918 	{
2919 	default:
2920 	  /* Allow/ignore comments in parameter lists if we are
2921 	     preserving comments in macro expansions.  */
2922 	  if (token->type == CPP_COMMENT
2923 	      && ! CPP_OPTION (pfile, discard_comments_in_macro_exp))
2924 	    continue;
2925 
2926 	  cpp_error (pfile, CPP_DL_ERROR,
2927 		     "\"%s\" may not appear in macro parameter list",
2928 		     cpp_token_as_text (pfile, token));
2929 	  return false;
2930 
2931 	case CPP_NAME:
2932 	  if (prev_ident)
2933 	    {
2934 	      cpp_error (pfile, CPP_DL_ERROR,
2935 			 "macro parameters must be comma-separated");
2936 	      return false;
2937 	    }
2938 	  prev_ident = 1;
2939 
2940 	  if (_cpp_save_parameter (pfile, macro, token->val.node.node,
2941 				   token->val.node.spelling))
2942 	    return false;
2943 	  continue;
2944 
2945 	case CPP_CLOSE_PAREN:
2946 	  if (prev_ident || macro->paramc == 0)
2947 	    return true;
2948 
2949 	  /* Fall through to pick up the error.  */
2950 	  /* FALLTHRU */
2951 	case CPP_COMMA:
2952 	  if (!prev_ident)
2953 	    {
2954 	      cpp_error (pfile, CPP_DL_ERROR, "parameter name missing");
2955 	      return false;
2956 	    }
2957 	  prev_ident = 0;
2958 	  continue;
2959 
2960 	case CPP_ELLIPSIS:
2961 	  macro->variadic = 1;
2962 	  if (!prev_ident)
2963 	    {
2964 	      _cpp_save_parameter (pfile, macro,
2965 				   pfile->spec_nodes.n__VA_ARGS__,
2966 				   pfile->spec_nodes.n__VA_ARGS__);
2967 	      pfile->state.va_args_ok = 1;
2968 	      if (! CPP_OPTION (pfile, c99)
2969 		  && CPP_OPTION (pfile, cpp_pedantic)
2970 		  && CPP_OPTION (pfile, warn_variadic_macros))
2971 		{
2972 		  if (CPP_OPTION (pfile, cplusplus))
2973 		    cpp_pedwarning
2974 			(pfile, CPP_W_VARIADIC_MACROS,
2975 			"anonymous variadic macros were introduced in C++11");
2976 		  else
2977 		    cpp_pedwarning
2978 			(pfile, CPP_W_VARIADIC_MACROS,
2979 			"anonymous variadic macros were introduced in C99");
2980 		}
2981 	      else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
2982 		       && ! CPP_OPTION (pfile, cplusplus))
2983 		cpp_error (pfile, CPP_DL_WARNING,
2984 			   "anonymous variadic macros were introduced in C99");
2985 	    }
2986 	  else if (CPP_OPTION (pfile, cpp_pedantic)
2987 		   && CPP_OPTION (pfile, warn_variadic_macros))
2988 	    {
2989 	      if (CPP_OPTION (pfile, cplusplus))
2990 		cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2991 		            "ISO C++ does not permit named variadic macros");
2992 	      else
2993 		cpp_pedwarning (pfile, CPP_W_VARIADIC_MACROS,
2994 		            "ISO C does not permit named variadic macros");
2995 	    }
2996 
2997 	  /* We're at the end, and just expect a closing parenthesis.  */
2998 	  token = _cpp_lex_token (pfile);
2999 	  if (token->type == CPP_CLOSE_PAREN)
3000 	    return true;
3001 	  /* Fall through.  */
3002 
3003 	case CPP_EOF:
3004 	  cpp_error (pfile, CPP_DL_ERROR, "missing ')' in macro parameter list");
3005 	  return false;
3006 	}
3007     }
3008 }
3009 
3010 /* Allocate room for a token from a macro's replacement list.  */
3011 static cpp_token *
3012 alloc_expansion_token (cpp_reader *pfile, cpp_macro *macro)
3013 {
3014   if (BUFF_ROOM (pfile->a_buff) < (macro->count + 1) * sizeof (cpp_token))
3015     _cpp_extend_buff (pfile, &pfile->a_buff, sizeof (cpp_token));
3016 
3017   return &((cpp_token *) BUFF_FRONT (pfile->a_buff))[macro->count++];
3018 }
3019 
3020 /* Lex a token from the expansion of MACRO, but mark parameters as we
3021    find them and warn of traditional stringification.  */
3022 static cpp_token *
3023 lex_expansion_token (cpp_reader *pfile, cpp_macro *macro)
3024 {
3025   cpp_token *token, *saved_cur_token;
3026 
3027   saved_cur_token = pfile->cur_token;
3028   pfile->cur_token = alloc_expansion_token (pfile, macro);
3029   token = _cpp_lex_direct (pfile);
3030   pfile->cur_token = saved_cur_token;
3031 
3032   /* Is this a parameter?  */
3033   if (token->type == CPP_NAME
3034       && (token->val.node.node->flags & NODE_MACRO_ARG) != 0)
3035     {
3036       cpp_hashnode *spelling = token->val.node.spelling;
3037       token->type = CPP_MACRO_ARG;
3038       token->val.macro_arg.arg_no = token->val.node.node->value.arg_index;
3039       token->val.macro_arg.spelling = spelling;
3040     }
3041   else if (CPP_WTRADITIONAL (pfile) && macro->paramc > 0
3042 	   && (token->type == CPP_STRING || token->type == CPP_CHAR))
3043     check_trad_stringification (pfile, macro, &token->val.str);
3044 
3045   return token;
3046 }
3047 
3048 static bool
3049 create_iso_definition (cpp_reader *pfile, cpp_macro *macro)
3050 {
3051   cpp_token *token;
3052   const cpp_token *ctoken;
3053   bool following_paste_op = false;
3054   const char *paste_op_error_msg =
3055     N_("'##' cannot appear at either end of a macro expansion");
3056   unsigned int num_extra_tokens = 0;
3057 
3058   /* Get the first token of the expansion (or the '(' of a
3059      function-like macro).  */
3060   ctoken = _cpp_lex_token (pfile);
3061 
3062   if (ctoken->type == CPP_OPEN_PAREN && !(ctoken->flags & PREV_WHITE))
3063     {
3064       bool ok = parse_params (pfile, macro);
3065       macro->params = (cpp_hashnode **) BUFF_FRONT (pfile->a_buff);
3066       if (!ok)
3067 	return false;
3068 
3069       /* Success.  Commit or allocate the parameter array.  */
3070       if (pfile->hash_table->alloc_subobject)
3071 	{
3072 	  cpp_hashnode **params =
3073             (cpp_hashnode **) pfile->hash_table->alloc_subobject
3074             (sizeof (cpp_hashnode *) * macro->paramc);
3075 	  memcpy (params, macro->params,
3076 		  sizeof (cpp_hashnode *) * macro->paramc);
3077 	  macro->params = params;
3078 	}
3079       else
3080 	BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->params[macro->paramc];
3081       macro->fun_like = 1;
3082     }
3083   else if (ctoken->type != CPP_EOF && !(ctoken->flags & PREV_WHITE))
3084     {
3085       /* While ISO C99 requires whitespace before replacement text
3086 	 in a macro definition, ISO C90 with TC1 allows characters
3087 	 from the basic source character set there.  */
3088       if (CPP_OPTION (pfile, c99))
3089 	{
3090 	  if (CPP_OPTION (pfile, cplusplus))
3091 	    cpp_error (pfile, CPP_DL_PEDWARN,
3092 		       "ISO C++11 requires whitespace after the macro name");
3093 	  else
3094 	    cpp_error (pfile, CPP_DL_PEDWARN,
3095 		       "ISO C99 requires whitespace after the macro name");
3096 	}
3097       else
3098 	{
3099 	  int warntype = CPP_DL_WARNING;
3100 	  switch (ctoken->type)
3101 	    {
3102 	    case CPP_ATSIGN:
3103 	    case CPP_AT_NAME:
3104 	    case CPP_OBJC_STRING:
3105 	      /* '@' is not in basic character set.  */
3106 	      warntype = CPP_DL_PEDWARN;
3107 	      break;
3108 	    case CPP_OTHER:
3109 	      /* Basic character set sans letters, digits and _.  */
3110 	      if (strchr ("!\"#%&'()*+,-./:;<=>?[\\]^{|}~",
3111 			  ctoken->val.str.text[0]) == NULL)
3112 		warntype = CPP_DL_PEDWARN;
3113 	      break;
3114 	    default:
3115 	      /* All other tokens start with a character from basic
3116 		 character set.  */
3117 	      break;
3118 	    }
3119 	  cpp_error (pfile, warntype,
3120 		     "missing whitespace after the macro name");
3121 	}
3122     }
3123 
3124   if (macro->fun_like)
3125     token = lex_expansion_token (pfile, macro);
3126   else
3127     {
3128       token = alloc_expansion_token (pfile, macro);
3129       *token = *ctoken;
3130     }
3131 
3132   for (;;)
3133     {
3134       /* Check the stringifying # constraint 6.10.3.2.1 of
3135 	 function-like macros when lexing the subsequent token.  */
3136       if (macro->count > 1 && token[-1].type == CPP_HASH && macro->fun_like)
3137 	{
3138 	  if (token->type == CPP_MACRO_ARG)
3139 	    {
3140 	      if (token->flags & PREV_WHITE)
3141 		token->flags |= SP_PREV_WHITE;
3142 	      if (token[-1].flags & DIGRAPH)
3143 		token->flags |= SP_DIGRAPH;
3144 	      token->flags &= ~PREV_WHITE;
3145 	      token->flags |= STRINGIFY_ARG;
3146 	      token->flags |= token[-1].flags & PREV_WHITE;
3147 	      token[-1] = token[0];
3148 	      macro->count--;
3149 	    }
3150 	  /* Let assembler get away with murder.  */
3151 	  else if (CPP_OPTION (pfile, lang) != CLK_ASM)
3152 	    {
3153 	      cpp_error (pfile, CPP_DL_ERROR,
3154 			 "'#' is not followed by a macro parameter");
3155 	      return false;
3156 	    }
3157 	}
3158 
3159       if (token->type == CPP_EOF)
3160 	{
3161 	  /* Paste operator constraint 6.10.3.3.1:
3162 	     Token-paste ##, can appear in both object-like and
3163 	     function-like macros, but not at the end.  */
3164 	  if (following_paste_op)
3165 	    {
3166 	      cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3167 	      return false;
3168 	    }
3169 	  break;
3170 	}
3171 
3172       /* Paste operator constraint 6.10.3.3.1.  */
3173       if (token->type == CPP_PASTE)
3174 	{
3175 	  /* Token-paste ##, can appear in both object-like and
3176 	     function-like macros, but not at the beginning.  */
3177 	  if (macro->count == 1)
3178 	    {
3179 	      cpp_error (pfile, CPP_DL_ERROR, paste_op_error_msg);
3180 	      return false;
3181 	    }
3182 
3183 	  if (token[-1].flags & PASTE_LEFT)
3184 	    {
3185 	      macro->extra_tokens = 1;
3186 	      num_extra_tokens++;
3187 	      token->val.token_no = macro->count - 1;
3188 	    }
3189 	  else
3190 	    {
3191 	      --macro->count;
3192 	      token[-1].flags |= PASTE_LEFT;
3193 	      if (token->flags & DIGRAPH)
3194 		token[-1].flags |= SP_DIGRAPH;
3195 	      if (token->flags & PREV_WHITE)
3196 		token[-1].flags |= SP_PREV_WHITE;
3197 	    }
3198 	}
3199 
3200       following_paste_op = (token->type == CPP_PASTE);
3201       token = lex_expansion_token (pfile, macro);
3202     }
3203 
3204   macro->exp.tokens = (cpp_token *) BUFF_FRONT (pfile->a_buff);
3205   macro->traditional = 0;
3206 
3207   /* Don't count the CPP_EOF.  */
3208   macro->count--;
3209 
3210   /* Clear whitespace on first token for warn_of_redefinition().  */
3211   if (macro->count)
3212     macro->exp.tokens[0].flags &= ~PREV_WHITE;
3213 
3214   /* Commit or allocate the memory.  */
3215   if (pfile->hash_table->alloc_subobject)
3216     {
3217       cpp_token *tokns =
3218         (cpp_token *) pfile->hash_table->alloc_subobject (sizeof (cpp_token)
3219                                                           * macro->count);
3220       if (num_extra_tokens)
3221 	{
3222 	  /* Place second and subsequent ## or %:%: tokens in
3223 	     sequences of consecutive such tokens at the end of the
3224 	     list to preserve information about where they appear, how
3225 	     they are spelt and whether they are preceded by
3226 	     whitespace without otherwise interfering with macro
3227 	     expansion.  */
3228 	  cpp_token *normal_dest = tokns;
3229 	  cpp_token *extra_dest = tokns + macro->count - num_extra_tokens;
3230 	  unsigned int i;
3231 	  for (i = 0; i < macro->count; i++)
3232 	    {
3233 	      if (macro->exp.tokens[i].type == CPP_PASTE)
3234 		*extra_dest++ = macro->exp.tokens[i];
3235 	      else
3236 		*normal_dest++ = macro->exp.tokens[i];
3237 	    }
3238 	}
3239       else
3240 	memcpy (tokns, macro->exp.tokens, sizeof (cpp_token) * macro->count);
3241       macro->exp.tokens = tokns;
3242     }
3243   else
3244     BUFF_FRONT (pfile->a_buff) = (uchar *) &macro->exp.tokens[macro->count];
3245 
3246   return true;
3247 }
3248 
3249 /* Parse a macro and save its expansion.  Returns nonzero on success.  */
3250 bool
3251 _cpp_create_definition (cpp_reader *pfile, cpp_hashnode *node)
3252 {
3253   cpp_macro *macro;
3254   unsigned int i;
3255   bool ok;
3256 
3257   if (pfile->hash_table->alloc_subobject)
3258     macro = (cpp_macro *) pfile->hash_table->alloc_subobject
3259       (sizeof (cpp_macro));
3260   else
3261     macro = (cpp_macro *) _cpp_aligned_alloc (pfile, sizeof (cpp_macro));
3262   macro->line = pfile->directive_line;
3263   macro->params = 0;
3264   macro->paramc = 0;
3265   macro->variadic = 0;
3266   macro->used = !CPP_OPTION (pfile, warn_unused_macros);
3267   macro->count = 0;
3268   macro->fun_like = 0;
3269   macro->extra_tokens = 0;
3270   /* To suppress some diagnostics.  */
3271   macro->syshdr = pfile->buffer && pfile->buffer->sysp != 0;
3272 
3273   if (CPP_OPTION (pfile, traditional))
3274     ok = _cpp_create_trad_definition (pfile, macro);
3275   else
3276     {
3277       ok = create_iso_definition (pfile, macro);
3278 
3279       /* We set the type for SEEN_EOL() in directives.c.
3280 
3281 	 Longer term we should lex the whole line before coming here,
3282 	 and just copy the expansion.  */
3283 
3284       /* Stop the lexer accepting __VA_ARGS__.  */
3285       pfile->state.va_args_ok = 0;
3286     }
3287 
3288   /* Clear the fast argument lookup indices.  */
3289   for (i = macro->paramc; i-- > 0; )
3290     {
3291       struct macro_arg_saved_data *save =
3292 	&((struct macro_arg_saved_data *) pfile->macro_buffer)[i];
3293       struct cpp_hashnode *node = save->canonical_node;
3294       node->flags &= ~ NODE_MACRO_ARG;
3295       node->value = save->value;
3296     }
3297 
3298   if (!ok)
3299     return ok;
3300 
3301   if (node->type == NT_MACRO)
3302     {
3303       if (CPP_OPTION (pfile, warn_unused_macros))
3304 	_cpp_warn_if_unused_macro (pfile, node, NULL);
3305 
3306       if (warn_of_redefinition (pfile, node, macro))
3307 	{
3308           const int reason = ((node->flags & NODE_BUILTIN)
3309 			      && !(node->flags & NODE_WARN))
3310                              ? CPP_W_BUILTIN_MACRO_REDEFINED : CPP_W_NONE;
3311 
3312 	  bool warned =
3313 	    cpp_pedwarning_with_line (pfile, reason,
3314 				      pfile->directive_line, 0,
3315 				      "\"%s\" redefined", NODE_NAME (node));
3316 
3317 	  if (warned && node->type == NT_MACRO && !(node->flags & NODE_BUILTIN))
3318 	    cpp_error_with_line (pfile, CPP_DL_NOTE,
3319 				 node->value.macro->line, 0,
3320 			 "this is the location of the previous definition");
3321 	}
3322     }
3323 
3324   if (node->type != NT_VOID)
3325     _cpp_free_definition (node);
3326 
3327   /* Enter definition in hash table.  */
3328   node->type = NT_MACRO;
3329   node->value.macro = macro;
3330   if (! ustrncmp (NODE_NAME (node), DSC ("__STDC_"))
3331       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_FORMAT_MACROS")
3332       /* __STDC_LIMIT_MACROS and __STDC_CONSTANT_MACROS are mentioned
3333 	 in the C standard, as something that one must use in C++.
3334 	 However DR#593 and C++11 indicate that they play no role in C++.
3335 	 We special-case them anyway.  */
3336       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_LIMIT_MACROS")
3337       && ustrcmp (NODE_NAME (node), (const uchar *) "__STDC_CONSTANT_MACROS"))
3338     node->flags |= NODE_WARN;
3339 
3340   /* If user defines one of the conditional macros, remove the
3341      conditional flag */
3342   node->flags &= ~NODE_CONDITIONAL;
3343 
3344   return ok;
3345 }
3346 
3347 /* Warn if a token in STRING matches one of a function-like MACRO's
3348    parameters.  */
3349 static void
3350 check_trad_stringification (cpp_reader *pfile, const cpp_macro *macro,
3351 			    const cpp_string *string)
3352 {
3353   unsigned int i, len;
3354   const uchar *p, *q, *limit;
3355 
3356   /* Loop over the string.  */
3357   limit = string->text + string->len - 1;
3358   for (p = string->text + 1; p < limit; p = q)
3359     {
3360       /* Find the start of an identifier.  */
3361       while (p < limit && !is_idstart (*p))
3362 	p++;
3363 
3364       /* Find the end of the identifier.  */
3365       q = p;
3366       while (q < limit && is_idchar (*q))
3367 	q++;
3368 
3369       len = q - p;
3370 
3371       /* Loop over the function macro arguments to see if the
3372 	 identifier inside the string matches one of them.  */
3373       for (i = 0; i < macro->paramc; i++)
3374 	{
3375 	  const cpp_hashnode *node = macro->params[i];
3376 
3377 	  if (NODE_LEN (node) == len
3378 	      && !memcmp (p, NODE_NAME (node), len))
3379 	    {
3380 	      cpp_error (pfile, CPP_DL_WARNING,
3381 	   "macro argument \"%s\" would be stringified in traditional C",
3382 			 NODE_NAME (node));
3383 	      break;
3384 	    }
3385 	}
3386     }
3387 }
3388 
3389 /* Returns true of NODE is a function-like macro.  */
3390 bool
3391 cpp_fun_like_macro_p (cpp_hashnode *node)
3392 {
3393   return (node->type == NT_MACRO
3394 	  && (node->flags & (NODE_BUILTIN | NODE_MACRO_ARG)) == 0
3395 	  && node->value.macro->fun_like);
3396 }
3397 
3398 /* Returns the name, arguments and expansion of a macro, in a format
3399    suitable to be read back in again, and therefore also for DWARF 2
3400    debugging info.  e.g. "PASTE(X, Y) X ## Y", or "MACNAME EXPANSION".
3401    Caller is expected to generate the "#define" bit if needed.  The
3402    returned text is temporary, and automatically freed later.  */
3403 const unsigned char *
3404 cpp_macro_definition (cpp_reader *pfile, cpp_hashnode *node)
3405 {
3406   unsigned int i, len;
3407   const cpp_macro *macro;
3408   unsigned char *buffer;
3409 
3410   if (node->type != NT_MACRO || (node->flags & NODE_BUILTIN))
3411     {
3412       if (node->type != NT_MACRO
3413 	  || !pfile->cb.user_builtin_macro
3414           || !pfile->cb.user_builtin_macro (pfile, node))
3415 	{
3416 	  cpp_error (pfile, CPP_DL_ICE,
3417 		     "invalid hash type %d in cpp_macro_definition",
3418 		     node->type);
3419 	  return 0;
3420 	}
3421     }
3422 
3423   macro = node->value.macro;
3424   /* Calculate length.  */
3425   len = NODE_LEN (node) * 10 + 2;		/* ' ' and NUL.  */
3426   if (macro->fun_like)
3427     {
3428       len += 4;		/* "()" plus possible final ".." of named
3429 			   varargs (we have + 1 below).  */
3430       for (i = 0; i < macro->paramc; i++)
3431 	len += NODE_LEN (macro->params[i]) + 1; /* "," */
3432     }
3433 
3434   /* This should match below where we fill in the buffer.  */
3435   if (CPP_OPTION (pfile, traditional))
3436     len += _cpp_replacement_text_len (macro);
3437   else
3438     {
3439       unsigned int count = macro_real_token_count (macro);
3440       for (i = 0; i < count; i++)
3441 	{
3442 	  cpp_token *token = &macro->exp.tokens[i];
3443 
3444 	  if (token->type == CPP_MACRO_ARG)
3445 	    len += NODE_LEN (token->val.macro_arg.spelling);
3446 	  else
3447 	    len += cpp_token_len (token);
3448 
3449 	  if (token->flags & STRINGIFY_ARG)
3450 	    len++;			/* "#" */
3451 	  if (token->flags & PASTE_LEFT)
3452 	    len += 3;		/* " ##" */
3453 	  if (token->flags & PREV_WHITE)
3454 	    len++;              /* " " */
3455 	}
3456     }
3457 
3458   if (len > pfile->macro_buffer_len)
3459     {
3460       pfile->macro_buffer = XRESIZEVEC (unsigned char,
3461                                         pfile->macro_buffer, len);
3462       pfile->macro_buffer_len = len;
3463     }
3464 
3465   /* Fill in the buffer.  Start with the macro name.  */
3466   buffer = pfile->macro_buffer;
3467   buffer = _cpp_spell_ident_ucns (buffer, node);
3468 
3469   /* Parameter names.  */
3470   if (macro->fun_like)
3471     {
3472       *buffer++ = '(';
3473       for (i = 0; i < macro->paramc; i++)
3474 	{
3475 	  cpp_hashnode *param = macro->params[i];
3476 
3477 	  if (param != pfile->spec_nodes.n__VA_ARGS__)
3478 	    {
3479 	      memcpy (buffer, NODE_NAME (param), NODE_LEN (param));
3480 	      buffer += NODE_LEN (param);
3481 	    }
3482 
3483 	  if (i + 1 < macro->paramc)
3484 	    /* Don't emit a space after the comma here; we're trying
3485 	       to emit a Dwarf-friendly definition, and the Dwarf spec
3486 	       forbids spaces in the argument list.  */
3487 	    *buffer++ = ',';
3488 	  else if (macro->variadic)
3489 	    *buffer++ = '.', *buffer++ = '.', *buffer++ = '.';
3490 	}
3491       *buffer++ = ')';
3492     }
3493 
3494   /* The Dwarf spec requires a space after the macro name, even if the
3495      definition is the empty string.  */
3496   *buffer++ = ' ';
3497 
3498   if (CPP_OPTION (pfile, traditional))
3499     buffer = _cpp_copy_replacement_text (macro, buffer);
3500   else if (macro->count)
3501   /* Expansion tokens.  */
3502     {
3503       unsigned int count = macro_real_token_count (macro);
3504       for (i = 0; i < count; i++)
3505 	{
3506 	  cpp_token *token = &macro->exp.tokens[i];
3507 
3508 	  if (token->flags & PREV_WHITE)
3509 	    *buffer++ = ' ';
3510 	  if (token->flags & STRINGIFY_ARG)
3511 	    *buffer++ = '#';
3512 
3513 	  if (token->type == CPP_MACRO_ARG)
3514 	    {
3515 	      memcpy (buffer,
3516 		      NODE_NAME (token->val.macro_arg.spelling),
3517 		      NODE_LEN (token->val.macro_arg.spelling));
3518 	      buffer += NODE_LEN (token->val.macro_arg.spelling);
3519 	    }
3520 	  else
3521 	    buffer = cpp_spell_token (pfile, token, buffer, true);
3522 
3523 	  if (token->flags & PASTE_LEFT)
3524 	    {
3525 	      *buffer++ = ' ';
3526 	      *buffer++ = '#';
3527 	      *buffer++ = '#';
3528 	      /* Next has PREV_WHITE; see _cpp_create_definition.  */
3529 	    }
3530 	}
3531     }
3532 
3533   *buffer = '\0';
3534   return pfile->macro_buffer;
3535 }
3536