Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/TokenLexer.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- TokenLexer.cpp - Lex from a token stream ---------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements the TokenLexer interface.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Lex/TokenLexer.h"
14
#include "clang/Basic/Diagnostic.h"
15
#include "clang/Basic/IdentifierTable.h"
16
#include "clang/Basic/LangOptions.h"
17
#include "clang/Basic/SourceLocation.h"
18
#include "clang/Basic/SourceManager.h"
19
#include "clang/Basic/TokenKinds.h"
20
#include "clang/Lex/LexDiagnostic.h"
21
#include "clang/Lex/Lexer.h"
22
#include "clang/Lex/MacroArgs.h"
23
#include "clang/Lex/MacroInfo.h"
24
#include "clang/Lex/Preprocessor.h"
25
#include "clang/Lex/Token.h"
26
#include "clang/Lex/VariadicMacroSupport.h"
27
#include "llvm/ADT/ArrayRef.h"
28
#include "llvm/ADT/SmallString.h"
29
#include "llvm/ADT/SmallVector.h"
30
#include "llvm/ADT/iterator_range.h"
31
#include <cassert>
32
#include <cstring>
33
34
using namespace clang;
35
36
/// Create a TokenLexer for the specified macro with the specified actual
37
/// arguments.  Note that this ctor takes ownership of the ActualArgs pointer.
38
void TokenLexer::Init(Token &Tok, SourceLocation ELEnd, MacroInfo *MI,
39
52.9M
                      MacroArgs *Actuals) {
40
  // If the client is reusing a TokenLexer, make sure to free any memory
41
  // associated with it.
42
52.9M
  destroy();
43
44
52.9M
  Macro = MI;
45
52.9M
  ActualArgs = Actuals;
46
52.9M
  CurTokenIdx = 0;
47
48
52.9M
  ExpandLocStart = Tok.getLocation();
49
52.9M
  ExpandLocEnd = ELEnd;
50
52.9M
  AtStartOfLine = Tok.isAtStartOfLine();
51
52.9M
  HasLeadingSpace = Tok.hasLeadingSpace();
52
52.9M
  NextTokGetsSpace = false;
53
52.9M
  Tokens = &*Macro->tokens_begin();
54
52.9M
  OwnsTokens = false;
55
52.9M
  DisableMacroExpansion = false;
56
52.9M
  IsReinject = false;
57
52.9M
  NumTokens = Macro->tokens_end()-Macro->tokens_begin();
58
52.9M
  MacroExpansionStart = SourceLocation();
59
60
52.9M
  SourceManager &SM = PP.getSourceManager();
61
52.9M
  MacroStartSLocOffset = SM.getNextLocalOffset();
62
63
52.9M
  if (NumTokens > 0) {
64
52.9M
    assert(Tokens[0].getLocation().isValid());
65
0
    assert((Tokens[0].getLocation().isFileID() || Tokens[0].is(tok::comment)) &&
66
52.9M
           "Macro defined in macro?");
67
0
    assert(ExpandLocStart.isValid());
68
69
    // Reserve a source location entry chunk for the length of the macro
70
    // definition. Tokens that get lexed directly from the definition will
71
    // have their locations pointing inside this chunk. This is to avoid
72
    // creating separate source location entries for each token.
73
0
    MacroDefStart = SM.getExpansionLoc(Tokens[0].getLocation());
74
52.9M
    MacroDefLength = Macro->getDefinitionLength(SM);
75
52.9M
    MacroExpansionStart = SM.createExpansionLoc(MacroDefStart,
76
52.9M
                                                ExpandLocStart,
77
52.9M
                                                ExpandLocEnd,
78
52.9M
                                                MacroDefLength);
79
52.9M
  }
80
81
  // If this is a function-like macro, expand the arguments and change
82
  // Tokens to point to the expanded tokens.
83
52.9M
  if (Macro->isFunctionLike() && 
Macro->getNumParams()19.6M
)
84
19.6M
    ExpandFunctionArguments();
85
86
  // Mark the macro as currently disabled, so that it is not recursively
87
  // expanded.  The macro must be disabled only after argument pre-expansion of
88
  // function-like macro arguments occurs.
89
52.9M
  Macro->DisableMacro();
90
52.9M
}
91
92
/// Create a TokenLexer for the specified token stream.  This does not
93
/// take ownership of the specified token vector.
94
void TokenLexer::Init(const Token *TokArray, unsigned NumToks,
95
                      bool disableMacroExpansion, bool ownsTokens,
96
4.35M
                      bool isReinject) {
97
4.35M
  assert(!isReinject || disableMacroExpansion);
98
  // If the client is reusing a TokenLexer, make sure to free any memory
99
  // associated with it.
100
0
  destroy();
101
102
4.35M
  Macro = nullptr;
103
4.35M
  ActualArgs = nullptr;
104
4.35M
  Tokens = TokArray;
105
4.35M
  OwnsTokens = ownsTokens;
106
4.35M
  DisableMacroExpansion = disableMacroExpansion;
107
4.35M
  IsReinject = isReinject;
108
4.35M
  NumTokens = NumToks;
109
4.35M
  CurTokenIdx = 0;
110
4.35M
  ExpandLocStart = ExpandLocEnd = SourceLocation();
111
4.35M
  AtStartOfLine = false;
112
4.35M
  HasLeadingSpace = false;
113
4.35M
  NextTokGetsSpace = false;
114
4.35M
  MacroExpansionStart = SourceLocation();
115
116
  // Set HasLeadingSpace/AtStartOfLine so that the first token will be
117
  // returned unmodified.
118
4.35M
  if (NumToks != 0) {
119
4.35M
    AtStartOfLine   = TokArray[0].isAtStartOfLine();
120
4.35M
    HasLeadingSpace = TokArray[0].hasLeadingSpace();
121
4.35M
  }
122
4.35M
}
123
124
57.7M
void TokenLexer::destroy() {
125
  // If this was a function-like macro that actually uses its arguments, delete
126
  // the expanded tokens.
127
57.7M
  if (OwnsTokens) {
128
347k
    delete [] Tokens;
129
347k
    Tokens = nullptr;
130
347k
    OwnsTokens = false;
131
347k
  }
132
133
  // TokenLexer owns its formal arguments.
134
57.7M
  if (ActualArgs) 
ActualArgs->destroy(PP)19.6M
;
135
57.7M
}
136
137
bool TokenLexer::MaybeRemoveCommaBeforeVaArgs(
138
    SmallVectorImpl<Token> &ResultToks, bool HasPasteOperator, MacroInfo *Macro,
139
168k
    unsigned MacroArgNo, Preprocessor &PP) {
140
  // Is the macro argument __VA_ARGS__?
141
168k
  if (!Macro->isVariadic() || 
MacroArgNo != Macro->getNumParams()-1168k
)
142
143k
    return false;
143
144
  // In Microsoft-compatibility mode, a comma is removed in the expansion
145
  // of " ... , __VA_ARGS__ " if __VA_ARGS__ is empty.  This extension is
146
  // not supported by gcc.
147
25.0k
  if (!HasPasteOperator && 
!PP.getLangOpts().MSVCCompat12.9k
)
148
12.9k
    return false;
149
150
  // GCC removes the comma in the expansion of " ... , ## __VA_ARGS__ " if
151
  // __VA_ARGS__ is empty, but not in strict C99 mode where there are no
152
  // named arguments, where it remains.  In all other modes, including C99
153
  // with GNU extensions, it is removed regardless of named arguments.
154
  // Microsoft also appears to support this extension, unofficially.
155
12.1k
  if (PP.getLangOpts().C99 && 
!PP.getLangOpts().GNUMode40
156
12.1k
        && 
Macro->getNumParams() < 29
)
157
3
    return false;
158
159
  // Is a comma available to be removed?
160
12.1k
  if (ResultToks.empty() || !ResultToks.back().is(tok::comma))
161
3
    return false;
162
163
  // Issue an extension diagnostic for the paste operator.
164
12.1k
  if (HasPasteOperator)
165
12.1k
    PP.Diag(ResultToks.back().getLocation(), diag::ext_paste_comma);
166
167
  // Remove the comma.
168
12.1k
  ResultToks.pop_back();
169
170
12.1k
  if (!ResultToks.empty()) {
171
    // If the comma was right after another paste (e.g. "X##,##__VA_ARGS__"),
172
    // then removal of the comma should produce a placemarker token (in C99
173
    // terms) which we model by popping off the previous ##, giving us a plain
174
    // "X" when __VA_ARGS__ is empty.
175
12.1k
    if (ResultToks.back().is(tok::hashhash))
176
1
      ResultToks.pop_back();
177
178
    // Remember that this comma was elided.
179
12.1k
    ResultToks.back().setFlag(Token::CommaAfterElided);
180
12.1k
  }
181
182
  // Never add a space, even if the comma, ##, or arg had a space.
183
12.1k
  NextTokGetsSpace = false;
184
12.1k
  return true;
185
12.1k
}
186
187
void TokenLexer::stringifyVAOPTContents(
188
    SmallVectorImpl<Token> &ResultToks, const VAOptExpansionContext &VCtx,
189
43
    const SourceLocation VAOPTClosingParenLoc) {
190
43
  const int NumToksPriorToVAOpt = VCtx.getNumberOfTokensPriorToVAOpt();
191
43
  const unsigned int NumVAOptTokens = ResultToks.size() - NumToksPriorToVAOpt;
192
43
  Token *const VAOPTTokens =
193
43
      NumVAOptTokens ? 
&ResultToks[NumToksPriorToVAOpt]15
:
nullptr28
;
194
195
43
  SmallVector<Token, 64> ConcatenatedVAOPTResultToks;
196
  // FIXME: Should we keep track within VCtx that we did or didnot
197
  // encounter pasting - and only then perform this loop.
198
199
  // Perform token pasting (concatenation) prior to stringization.
200
166
  for (unsigned int CurTokenIdx = 0; CurTokenIdx != NumVAOptTokens;
201
123
       ++CurTokenIdx) {
202
123
    if (VAOPTTokens[CurTokenIdx].is(tok::hashhash)) {
203
18
      assert(CurTokenIdx != 0 &&
204
18
             "Can not have __VAOPT__ contents begin with a ##");
205
0
      Token &LHS = VAOPTTokens[CurTokenIdx - 1];
206
18
      pasteTokens(LHS, llvm::makeArrayRef(VAOPTTokens, NumVAOptTokens),
207
18
                  CurTokenIdx);
208
      // Replace the token prior to the first ## in this iteration.
209
18
      ConcatenatedVAOPTResultToks.back() = LHS;
210
18
      if (CurTokenIdx == NumVAOptTokens)
211
0
        break;
212
18
    }
213
123
    ConcatenatedVAOPTResultToks.push_back(VAOPTTokens[CurTokenIdx]);
214
123
  }
215
216
43
  ConcatenatedVAOPTResultToks.push_back(VCtx.getEOFTok());
217
  // Get the SourceLocation that represents the start location within
218
  // the macro definition that marks where this string is substituted
219
  // into: i.e. the __VA_OPT__ and the ')' within the spelling of the
220
  // macro definition, and use it to indicate that the stringified token
221
  // was generated from that location.
222
43
  const SourceLocation ExpansionLocStartWithinMacro =
223
43
      getExpansionLocForMacroDefLoc(VCtx.getVAOptLoc());
224
43
  const SourceLocation ExpansionLocEndWithinMacro =
225
43
      getExpansionLocForMacroDefLoc(VAOPTClosingParenLoc);
226
227
43
  Token StringifiedVAOPT = MacroArgs::StringifyArgument(
228
43
      &ConcatenatedVAOPTResultToks[0], PP, VCtx.hasCharifyBefore() /*Charify*/,
229
43
      ExpansionLocStartWithinMacro, ExpansionLocEndWithinMacro);
230
231
43
  if (VCtx.getLeadingSpaceForStringifiedToken())
232
30
    StringifiedVAOPT.setFlag(Token::LeadingSpace);
233
234
43
  StringifiedVAOPT.setFlag(Token::StringifiedInMacro);
235
  // Resize (shrink) the token stream to just capture this stringified token.
236
43
  ResultToks.resize(NumToksPriorToVAOpt + 1);
237
43
  ResultToks.back() = StringifiedVAOPT;
238
43
}
239
240
/// Expand the arguments of a function-like macro so that we can quickly
241
/// return preexpanded tokens from Tokens.
242
19.6M
void TokenLexer::ExpandFunctionArguments() {
243
19.6M
  SmallVector<Token, 128> ResultToks;
244
245
  // Loop through 'Tokens', expanding them into ResultToks.  Keep
246
  // track of whether we change anything.  If not, no need to keep them.  If so,
247
  // we install the newly expanded sequence as the new 'Tokens' list.
248
19.6M
  bool MadeChange = false;
249
250
19.6M
  Optional<bool> CalledWithVariadicArguments;
251
252
19.6M
  VAOptExpansionContext VCtx(PP);
253
254
201M
  for (unsigned I = 0, E = NumTokens; I != E; 
++I181M
) {
255
181M
    const Token &CurTok = Tokens[I];
256
    // We don't want a space for the next token after a paste
257
    // operator.  In valid code, the token will get smooshed onto the
258
    // preceding one anyway. In assembler-with-cpp mode, invalid
259
    // pastes are allowed through: in this case, we do not want the
260
    // extra whitespace to be added.  For example, we want ". ## foo"
261
    // -> ".foo" not ". foo".
262
181M
    if (I != 0 && 
!Tokens[I-1].is(tok::hashhash)161M
&&
CurTok.hasLeadingSpace()154M
)
263
18.0M
      NextTokGetsSpace = true;
264
265
181M
    if (VCtx.isVAOptToken(CurTok)) {
266
129
      MadeChange = true;
267
129
      assert(Tokens[I + 1].is(tok::l_paren) &&
268
129
             "__VA_OPT__ must be followed by '('");
269
270
0
      ++I;             // Skip the l_paren
271
129
      VCtx.sawVAOptFollowedByOpeningParens(CurTok.getLocation(),
272
129
                                           ResultToks.size());
273
274
129
      continue;
275
129
    }
276
277
    // We have entered into the __VA_OPT__ context, so handle tokens
278
    // appropriately.
279
181M
    if (VCtx.isInVAOpt()) {
280
      // If we are about to process a token that is either an argument to
281
      // __VA_OPT__ or its closing rparen, then:
282
      //  1) If the token is the closing rparen that exits us out of __VA_OPT__,
283
      //  perform any necessary stringification or placemarker processing,
284
      //  and/or skip to the next token.
285
      //  2) else if macro was invoked without variadic arguments skip this
286
      //  token.
287
      //  3) else (macro was invoked with variadic arguments) process the token
288
      //  normally.
289
290
640
      if (Tokens[I].is(tok::l_paren))
291
6
        VCtx.sawOpeningParen(Tokens[I].getLocation());
292
      // Continue skipping tokens within __VA_OPT__ if the macro was not
293
      // called with variadic arguments, else let the rest of the loop handle
294
      // this token. Note sawClosingParen() returns true only if the r_paren matches
295
      // the closing r_paren of the __VA_OPT__.
296
640
      if (!Tokens[I].is(tok::r_paren) || 
!VCtx.sawClosingParen()135
) {
297
        // Lazily expand __VA_ARGS__ when we see the first __VA_OPT__.
298
511
        if (!CalledWithVariadicArguments.hasValue()) {
299
97
          CalledWithVariadicArguments =
300
97
              ActualArgs->invokedWithVariadicArgument(Macro, PP);
301
97
        }
302
511
        if (!*CalledWithVariadicArguments) {
303
          // Skip this token.
304
249
          continue;
305
249
        }
306
        // ... else the macro was called with variadic arguments, and we do not
307
        // have a closing rparen - so process this token normally.
308
511
      } else {
309
        // Current token is the closing r_paren which marks the end of the
310
        // __VA_OPT__ invocation, so handle any place-marker pasting (if
311
        // empty) by removing hashhash either before (if exists) or after. And
312
        // also stringify the entire contents if VAOPT was preceded by a hash,
313
        // but do so only after any token concatenation that needs to occur
314
        // within the contents of VAOPT.
315
316
129
        if (VCtx.hasStringifyOrCharifyBefore()) {
317
          // Replace all the tokens just added from within VAOPT into a single
318
          // stringified token. This requires token-pasting to eagerly occur
319
          // within these tokens. If either the contents of VAOPT were empty
320
          // or the macro wasn't called with any variadic arguments, the result
321
          // is a token that represents an empty string.
322
43
          stringifyVAOPTContents(ResultToks, VCtx,
323
43
                                 /*ClosingParenLoc*/ Tokens[I].getLocation());
324
325
86
        } else if (/*No tokens within VAOPT*/
326
86
                   ResultToks.size() == VCtx.getNumberOfTokensPriorToVAOpt()) {
327
          // Treat VAOPT as a placemarker token.  Eat either the '##' before the
328
          // RHS/VAOPT (if one exists, suggesting that the LHS (if any) to that
329
          // hashhash was not a placemarker) or the '##'
330
          // after VAOPT, but not both.
331
332
41
          if (ResultToks.size() && 
ResultToks.back().is(tok::hashhash)33
) {
333
12
            ResultToks.pop_back();
334
29
          } else if ((I + 1 != E) && 
Tokens[I + 1].is(tok::hashhash)25
) {
335
6
            ++I; // Skip the following hashhash.
336
6
          }
337
45
        } else {
338
          // If there's a ## before the __VA_OPT__, we might have discovered
339
          // that the __VA_OPT__ begins with a placeholder. We delay action on
340
          // that to now to avoid messing up our stashed count of tokens before
341
          // __VA_OPT__.
342
45
          if (VCtx.beginsWithPlaceholder()) {
343
7
            assert(VCtx.getNumberOfTokensPriorToVAOpt() > 0 &&
344
7
                   ResultToks.size() >= VCtx.getNumberOfTokensPriorToVAOpt() &&
345
7
                   ResultToks[VCtx.getNumberOfTokensPriorToVAOpt() - 1].is(
346
7
                       tok::hashhash) &&
347
7
                   "no token paste before __VA_OPT__");
348
0
            ResultToks.erase(ResultToks.begin() +
349
7
                             VCtx.getNumberOfTokensPriorToVAOpt() - 1);
350
7
          }
351
          // If the expansion of __VA_OPT__ ends with a placeholder, eat any
352
          // following '##' token.
353
45
          if (VCtx.endsWithPlaceholder() && 
I + 1 != E7
&&
354
45
              
Tokens[I + 1].is(tok::hashhash)7
) {
355
7
            ++I;
356
7
          }
357
45
        }
358
0
        VCtx.reset();
359
        // We processed __VA_OPT__'s closing paren (and the exit out of
360
        // __VA_OPT__), so skip to the next token.
361
129
        continue;
362
129
      }
363
640
    }
364
365
    // If we found the stringify operator, get the argument stringified.  The
366
    // preprocessor already verified that the following token is a macro
367
    // parameter or __VA_OPT__ when the #define was lexed.
368
369
181M
    if (CurTok.isOneOf(tok::hash, tok::hashat)) {
370
108k
      int ArgNo = Macro->getParameterNum(Tokens[I+1].getIdentifierInfo());
371
108k
      assert((ArgNo != -1 || VCtx.isVAOptToken(Tokens[I + 1])) &&
372
108k
             "Token following # is not an argument or __VA_OPT__!");
373
374
108k
      if (ArgNo == -1) {
375
        // Handle the __VA_OPT__ case.
376
43
        VCtx.sawHashOrHashAtBefore(NextTokGetsSpace,
377
43
                                   CurTok.is(tok::hashat));
378
43
        continue;
379
43
      }
380
      // Else handle the simple argument case.
381
108k
      SourceLocation ExpansionLocStart =
382
108k
          getExpansionLocForMacroDefLoc(CurTok.getLocation());
383
108k
      SourceLocation ExpansionLocEnd =
384
108k
          getExpansionLocForMacroDefLoc(Tokens[I+1].getLocation());
385
386
108k
      bool Charify = CurTok.is(tok::hashat);
387
108k
      const Token *UnexpArg = ActualArgs->getUnexpArgument(ArgNo);
388
108k
      Token Res = MacroArgs::StringifyArgument(
389
108k
          UnexpArg, PP, Charify, ExpansionLocStart, ExpansionLocEnd);
390
108k
      Res.setFlag(Token::StringifiedInMacro);
391
392
      // The stringified/charified string leading space flag gets set to match
393
      // the #/#@ operator.
394
108k
      if (NextTokGetsSpace)
395
43.4k
        Res.setFlag(Token::LeadingSpace);
396
397
108k
      ResultToks.push_back(Res);
398
108k
      MadeChange = true;
399
108k
      ++I;  // Skip arg name.
400
108k
      NextTokGetsSpace = false;
401
108k
      continue;
402
108k
    }
403
404
    // Find out if there is a paste (##) operator before or after the token.
405
181M
    bool NonEmptyPasteBefore =
406
181M
      !ResultToks.empty() && 
ResultToks.back().is(tok::hashhash)161M
;
407
181M
    bool PasteBefore = I != 0 && 
Tokens[I-1].is(tok::hashhash)161M
;
408
181M
    bool PasteAfter = I+1 != E && 
Tokens[I+1].is(tok::hashhash)161M
;
409
181M
    bool RParenAfter = I+1 != E && 
Tokens[I+1].is(tok::r_paren)161M
;
410
411
181M
    assert((!NonEmptyPasteBefore || PasteBefore || VCtx.isInVAOpt()) &&
412
181M
           "unexpected ## in ResultToks");
413
414
    // Otherwise, if this is not an argument token, just add the token to the
415
    // output buffer.
416
0
    IdentifierInfo *II = CurTok.getIdentifierInfo();
417
181M
    int ArgNo = II ? 
Macro->getParameterNum(II)82.7M
:
-198.8M
;
418
181M
    if (ArgNo == -1) {
419
      // This isn't an argument, just add it.
420
150M
      ResultToks.push_back(CurTok);
421
422
150M
      if (NextTokGetsSpace) {
423
17.1M
        ResultToks.back().setFlag(Token::LeadingSpace);
424
17.1M
        NextTokGetsSpace = false;
425
133M
      } else if (PasteBefore && 
!NonEmptyPasteBefore509k
)
426
9
        ResultToks.back().clearFlag(Token::LeadingSpace);
427
428
150M
      continue;
429
150M
    }
430
431
    // An argument is expanded somehow, the result is different than the
432
    // input.
433
30.5M
    MadeChange = true;
434
435
    // Otherwise, this is a use of the argument.
436
437
    // In Microsoft mode, remove the comma before __VA_ARGS__ to ensure there
438
    // are no trailing commas if __VA_ARGS__ is empty.
439
30.5M
    if (!PasteBefore && 
ActualArgs->isVarargsElidedUse()23.8M
&&
440
30.5M
        MaybeRemoveCommaBeforeVaArgs(ResultToks,
441
156k
                                     /*HasPasteOperator=*/false,
442
156k
                                     Macro, ArgNo, PP))
443
3
      continue;
444
445
    // If it is not the LHS/RHS of a ## operator, we must pre-expand the
446
    // argument and substitute the expanded tokens into the result.  This is
447
    // C99 6.10.3.1p1.
448
30.5M
    if (!PasteBefore && 
!PasteAfter23.8M
) {
449
23.2M
      const Token *ResultArgToks;
450
451
      // Only preexpand the argument if it could possibly need it.  This
452
      // avoids some work in common cases.
453
23.2M
      const Token *ArgTok = ActualArgs->getUnexpArgument(ArgNo);
454
23.2M
      if (ActualArgs->ArgNeedsPreexpansion(ArgTok, PP))
455
3.01M
        ResultArgToks = &ActualArgs->getPreExpArgument(ArgNo, PP)[0];
456
20.2M
      else
457
20.2M
        ResultArgToks = ArgTok;  // Use non-preexpanded tokens.
458
459
      // If the arg token expanded into anything, append it.
460
23.2M
      if (ResultArgToks->isNot(tok::eof)) {
461
22.6M
        size_t FirstResult = ResultToks.size();
462
22.6M
        unsigned NumToks = MacroArgs::getArgLength(ResultArgToks);
463
22.6M
        ResultToks.append(ResultArgToks, ResultArgToks+NumToks);
464
465
        // In Microsoft-compatibility mode, we follow MSVC's preprocessing
466
        // behavior by not considering single commas from nested macro
467
        // expansions as argument separators. Set a flag on the token so we can
468
        // test for this later when the macro expansion is processed.
469
22.6M
        if (PP.getLangOpts().MSVCCompat && 
NumToks == 111.7k
&&
470
22.6M
            
ResultToks.back().is(tok::comma)7.38k
)
471
6
          ResultToks.back().setFlag(Token::IgnoredComma);
472
473
        // If the '##' came from expanding an argument, turn it into 'unknown'
474
        // to avoid pasting.
475
22.6M
        for (Token &Tok : llvm::drop_begin(ResultToks, FirstResult))
476
79.6M
          if (Tok.is(tok::hashhash))
477
2
            Tok.setKind(tok::unknown);
478
479
22.6M
        if(ExpandLocStart.isValid()) {
480
22.6M
          updateLocForMacroArgTokens(CurTok.getLocation(),
481
22.6M
                                     ResultToks.begin()+FirstResult,
482
22.6M
                                     ResultToks.end());
483
22.6M
        }
484
485
        // If any tokens were substituted from the argument, the whitespace
486
        // before the first token should match the whitespace of the arg
487
        // identifier.
488
22.6M
        ResultToks[FirstResult].setFlagValue(Token::LeadingSpace,
489
22.6M
                                             NextTokGetsSpace);
490
22.6M
        ResultToks[FirstResult].setFlagValue(Token::StartOfLine, false);
491
22.6M
        NextTokGetsSpace = false;
492
22.6M
      } else {
493
        // We're creating a placeholder token. Usually this doesn't matter,
494
        // but it can affect paste behavior when at the start or end of a
495
        // __VA_OPT__.
496
639k
        if (NonEmptyPasteBefore) {
497
          // We're imagining a placeholder token is inserted here. If this is
498
          // the first token in a __VA_OPT__ after a ##, delete the ##.
499
3
          assert(VCtx.isInVAOpt() && "should only happen inside a __VA_OPT__");
500
0
          VCtx.hasPlaceholderAfterHashhashAtStart();
501
3
        }
502
639k
        if (RParenAfter)
503
375k
          VCtx.hasPlaceholderBeforeRParen();
504
639k
      }
505
0
      continue;
506
23.2M
    }
507
508
    // Okay, we have a token that is either the LHS or RHS of a paste (##)
509
    // argument.  It gets substituted as its non-pre-expanded tokens.
510
7.34M
    const Token *ArgToks = ActualArgs->getUnexpArgument(ArgNo);
511
7.34M
    unsigned NumToks = MacroArgs::getArgLength(ArgToks);
512
7.34M
    if (NumToks) {  // Not an empty argument?
513
7.29M
      bool VaArgsPseudoPaste = false;
514
      // If this is the GNU ", ## __VA_ARGS__" extension, and we just learned
515
      // that __VA_ARGS__ expands to multiple tokens, avoid a pasting error when
516
      // the expander tries to paste ',' with the first token of the __VA_ARGS__
517
      // expansion.
518
7.29M
      if (NonEmptyPasteBefore && 
ResultToks.size() >= 26.68M
&&
519
7.29M
          
ResultToks[ResultToks.size()-2].is(tok::comma)6.68M
&&
520
7.29M
          
(unsigned)ArgNo == Macro->getNumParams()-156.7k
&&
521
7.29M
          
Macro->isVariadic()56.7k
) {
522
56.7k
        VaArgsPseudoPaste = true;
523
        // Remove the paste operator, report use of the extension.
524
56.7k
        PP.Diag(ResultToks.pop_back_val().getLocation(), diag::ext_paste_comma);
525
56.7k
      }
526
527
7.29M
      ResultToks.append(ArgToks, ArgToks+NumToks);
528
529
      // If the '##' came from expanding an argument, turn it into 'unknown'
530
      // to avoid pasting.
531
7.29M
      for (Token &Tok : llvm::make_range(ResultToks.end() - NumToks,
532
19.4M
                                         ResultToks.end())) {
533
19.4M
        if (Tok.is(tok::hashhash))
534
0
          Tok.setKind(tok::unknown);
535
19.4M
      }
536
537
7.29M
      if (ExpandLocStart.isValid()) {
538
7.29M
        updateLocForMacroArgTokens(CurTok.getLocation(),
539
7.29M
                                   ResultToks.end()-NumToks, ResultToks.end());
540
7.29M
      }
541
542
      // Transfer the leading whitespace information from the token
543
      // (the macro argument) onto the first token of the
544
      // expansion. Note that we don't do this for the GNU
545
      // pseudo-paste extension ", ## __VA_ARGS__".
546
7.29M
      if (!VaArgsPseudoPaste) {
547
7.23M
        ResultToks[ResultToks.size() - NumToks].setFlagValue(Token::StartOfLine,
548
7.23M
                                                             false);
549
7.23M
        ResultToks[ResultToks.size() - NumToks].setFlagValue(
550
7.23M
            Token::LeadingSpace, NextTokGetsSpace);
551
7.23M
      }
552
553
7.29M
      NextTokGetsSpace = false;
554
7.29M
      continue;
555
7.29M
    }
556
557
    // If an empty argument is on the LHS or RHS of a paste, the standard (C99
558
    // 6.10.3.3p2,3) calls for a bunch of placemarker stuff to occur.  We
559
    // implement this by eating ## operators when a LHS or RHS expands to
560
    // empty.
561
49.9k
    if (PasteAfter) {
562
      // Discard the argument token and skip (don't copy to the expansion
563
      // buffer) the paste operator after it.
564
8.93k
      ++I;
565
8.93k
      continue;
566
8.93k
    }
567
568
41.0k
    if (RParenAfter)
569
12.0k
      VCtx.hasPlaceholderBeforeRParen();
570
571
    // If this is on the RHS of a paste operator, we've already copied the
572
    // paste operator to the ResultToks list, unless the LHS was empty too.
573
    // Remove it.
574
41.0k
    assert(PasteBefore);
575
41.0k
    if (NonEmptyPasteBefore) {
576
41.0k
      assert(ResultToks.back().is(tok::hashhash));
577
      // Do not remove the paste operator if it is the one before __VA_OPT__
578
      // (and we are still processing tokens within VA_OPT).  We handle the case
579
      // of removing the paste operator if __VA_OPT__ reduces to the notional
580
      // placemarker above when we encounter the closing paren of VA_OPT.
581
41.0k
      if (!VCtx.isInVAOpt() ||
582
41.0k
          
ResultToks.size() > VCtx.getNumberOfTokensPriorToVAOpt()4
)
583
40.9k
        ResultToks.pop_back();
584
4
      else
585
4
        VCtx.hasPlaceholderAfterHashhashAtStart();
586
41.0k
    }
587
588
    // If this is the __VA_ARGS__ token, and if the argument wasn't provided,
589
    // and if the macro had at least one real argument, and if the token before
590
    // the ## was a comma, remove the comma.  This is a GCC extension which is
591
    // disabled when using -std=c99.
592
41.0k
    if (ActualArgs->isVarargsElidedUse())
593
12.1k
      MaybeRemoveCommaBeforeVaArgs(ResultToks,
594
12.1k
                                   /*HasPasteOperator=*/true,
595
12.1k
                                   Macro, ArgNo, PP);
596
41.0k
  }
597
598
  // If anything changed, install this as the new Tokens list.
599
19.6M
  if (MadeChange) {
600
19.6M
    assert(!OwnsTokens && "This would leak if we already own the token list");
601
    // This is deleted in the dtor.
602
0
    NumTokens = ResultToks.size();
603
    // The tokens will be added to Preprocessor's cache and will be removed
604
    // when this TokenLexer finishes lexing them.
605
19.6M
    Tokens = PP.cacheMacroExpandedTokens(this, ResultToks);
606
607
    // The preprocessor cache of macro expanded tokens owns these tokens,not us.
608
19.6M
    OwnsTokens = false;
609
19.6M
  }
610
19.6M
}
611
612
/// Checks if two tokens form wide string literal.
613
static bool isWideStringLiteralFromMacro(const Token &FirstTok,
614
1.01M
                                         const Token &SecondTok) {
615
1.01M
  return FirstTok.is(tok::identifier) &&
616
1.01M
         
FirstTok.getIdentifierInfo()->isStr("L")240k
&&
SecondTok.isLiteral()3
&&
617
1.01M
         
SecondTok.stringifiedInMacro()3
;
618
1.01M
}
619
620
/// Lex - Lex and return a token from this macro stream.
621
628M
bool TokenLexer::Lex(Token &Tok) {
622
  // Lexing off the end of the macro, pop this macro off the expansion stack.
623
628M
  if (isAtEnd()) {
624
    // If this is a macro (not a token stream), mark the macro enabled now
625
    // that it is no longer being expanded.
626
54.3M
    if (Macro) 
Macro->EnableMacro()52.9M
;
627
628
54.3M
    Tok.startToken();
629
54.3M
    Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
630
54.3M
    Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace || 
NextTokGetsSpace53.9M
);
631
54.3M
    if (CurTokenIdx == 0)
632
262k
      Tok.setFlag(Token::LeadingEmptyMacro);
633
54.3M
    return PP.HandleEndOfTokenLexer(Tok);
634
54.3M
  }
635
636
573M
  SourceManager &SM = PP.getSourceManager();
637
638
  // If this is the first token of the expanded result, we inherit spacing
639
  // properties later.
640
573M
  bool isFirstToken = CurTokenIdx == 0;
641
642
  // Get the next token to return.
643
573M
  Tok = Tokens[CurTokenIdx++];
644
573M
  if (IsReinject)
645
13.7M
    Tok.setFlag(Token::IsReinjected);
646
647
573M
  bool TokenIsFromPaste = false;
648
649
  // If this token is followed by a token paste (##) operator, paste the tokens!
650
  // Note that ## is a normal token when not expanding a macro.
651
573M
  if (!isAtEnd() && 
Macro518M
&&
652
573M
      
(498M
Tokens[CurTokenIdx].is(tok::hashhash)498M
||
653
       // Special processing of L#x macros in -fms-compatibility mode.
654
       // Microsoft compiler is able to form a wide string literal from
655
       // 'L#macro_arg' construct in a function-like macro.
656
498M
       
(492M
PP.getLangOpts().MSVCCompat492M
&&
657
492M
        
isWideStringLiteralFromMacro(Tok, Tokens[CurTokenIdx])1.01M
))) {
658
    // When handling the microsoft /##/ extension, the final token is
659
    // returned by pasteTokens, not the pasted token.
660
6.16M
    if (pasteTokens(Tok))
661
4
      return true;
662
663
6.16M
    TokenIsFromPaste = true;
664
6.16M
  }
665
666
  // The token's current location indicate where the token was lexed from.  We
667
  // need this information to compute the spelling of the token, but any
668
  // diagnostics for the expanded token should appear as if they came from
669
  // ExpansionLoc.  Pull this information together into a new SourceLocation
670
  // that captures all of this.
671
573M
  if (ExpandLocStart.isValid() &&   // Don't do this for token streams.
672
      // Check that the token's location was not already set properly.
673
573M
      
SM.isBeforeInSLocAddrSpace(Tok.getLocation(), MacroStartSLocOffset)550M
) {
674
451M
    SourceLocation instLoc;
675
451M
    if (Tok.is(tok::comment)) {
676
3
      instLoc = SM.createExpansionLoc(Tok.getLocation(),
677
3
                                      ExpandLocStart,
678
3
                                      ExpandLocEnd,
679
3
                                      Tok.getLength());
680
451M
    } else {
681
451M
      instLoc = getExpansionLocForMacroDefLoc(Tok.getLocation());
682
451M
    }
683
684
451M
    Tok.setLocation(instLoc);
685
451M
  }
686
687
  // If this is the first token, set the lexical properties of the token to
688
  // match the lexical properties of the macro identifier.
689
573M
  if (isFirstToken) {
690
57.0M
    Tok.setFlagValue(Token::StartOfLine , AtStartOfLine);
691
57.0M
    Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
692
516M
  } else {
693
    // If this is not the first token, we may still need to pass through
694
    // leading whitespace if we've expanded a macro.
695
516M
    if (AtStartOfLine) 
Tok.setFlag(Token::StartOfLine)341k
;
696
516M
    if (HasLeadingSpace) 
Tok.setFlag(Token::LeadingSpace)337k
;
697
516M
  }
698
573M
  AtStartOfLine = false;
699
573M
  HasLeadingSpace = false;
700
701
  // Handle recursive expansion!
702
573M
  if (!Tok.isAnnotation() && 
Tok.getIdentifierInfo() != nullptr573M
) {
703
    // Change the kind of this identifier to the appropriate token kind, e.g.
704
    // turning "for" into a keyword.
705
229M
    IdentifierInfo *II = Tok.getIdentifierInfo();
706
229M
    Tok.setKind(II->getTokenID());
707
708
    // If this identifier was poisoned and from a paste, emit an error.  This
709
    // won't be handled by Preprocessor::HandleIdentifier because this is coming
710
    // from a macro expansion.
711
229M
    if (II->isPoisoned() && 
TokenIsFromPaste4
) {
712
2
      PP.HandlePoisonedIdentifier(Tok);
713
2
    }
714
715
229M
    if (!DisableMacroExpansion && 
II->isHandleIdentifierCase()225M
)
716
42.2M
      return PP.HandleIdentifier(Tok);
717
229M
  }
718
719
  // Otherwise, return a normal token.
720
531M
  return true;
721
573M
}
722
723
6.16M
bool TokenLexer::pasteTokens(Token &Tok) {
724
6.16M
  return pasteTokens(Tok, llvm::makeArrayRef(Tokens, NumTokens), CurTokenIdx);
725
6.16M
}
726
727
/// LHSTok is the LHS of a ## operator, and CurTokenIdx is the ##
728
/// operator.  Read the ## and RHS, and paste the LHS/RHS together.  If there
729
/// are more ## after it, chomp them iteratively.  Return the result as LHSTok.
730
/// If this returns true, the caller should immediately return the token.
731
bool TokenLexer::pasteTokens(Token &LHSTok, ArrayRef<Token> TokenStream,
732
6.16M
                             unsigned int &CurIdx) {
733
6.16M
  assert(CurIdx > 0 && "## can not be the first token within tokens");
734
0
  assert((TokenStream[CurIdx].is(tok::hashhash) ||
735
6.16M
         (PP.getLangOpts().MSVCCompat &&
736
6.16M
          isWideStringLiteralFromMacro(LHSTok, TokenStream[CurIdx]))) &&
737
6.16M
             "Token at this Index must be ## or part of the MSVC 'L "
738
6.16M
             "#macro-arg' pasting pair");
739
740
  // MSVC: If previous token was pasted, this must be a recovery from an invalid
741
  // paste operation. Ignore spaces before this token to mimic MSVC output.
742
  // Required for generating valid UUID strings in some MS headers.
743
6.16M
  if (PP.getLangOpts().MicrosoftExt && 
(CurIdx >= 2)1.56k
&&
744
6.16M
      
TokenStream[CurIdx - 2].is(tok::hashhash)27
)
745
8
    LHSTok.clearFlag(Token::LeadingSpace);
746
747
6.16M
  SmallString<128> Buffer;
748
6.16M
  const char *ResultTokStrPtr = nullptr;
749
6.16M
  SourceLocation StartLoc = LHSTok.getLocation();
750
6.16M
  SourceLocation PasteOpLoc;
751
752
14.2M
  auto IsAtEnd = [&TokenStream, &CurIdx] {
753
14.2M
    return TokenStream.size() == CurIdx;
754
14.2M
  };
755
756
7.14M
  do {
757
    // Consume the ## operator if any.
758
7.14M
    PasteOpLoc = TokenStream[CurIdx].getLocation();
759
7.14M
    if (TokenStream[CurIdx].is(tok::hashhash))
760
7.14M
      ++CurIdx;
761
7.14M
    assert(!IsAtEnd() && "No token on the RHS of a paste operator!");
762
763
    // Get the RHS token.
764
0
    const Token &RHS = TokenStream[CurIdx];
765
766
    // Allocate space for the result token.  This is guaranteed to be enough for
767
    // the two tokens.
768
7.14M
    Buffer.resize(LHSTok.getLength() + RHS.getLength());
769
770
    // Get the spelling of the LHS token in Buffer.
771
7.14M
    const char *BufPtr = &Buffer[0];
772
7.14M
    bool Invalid = false;
773
7.14M
    unsigned LHSLen = PP.getSpelling(LHSTok, BufPtr, &Invalid);
774
7.14M
    if (BufPtr != &Buffer[0])   // Really, we want the chars in Buffer!
775
7.14M
      memcpy(&Buffer[0], BufPtr, LHSLen);
776
7.14M
    if (Invalid)
777
0
      return true;
778
779
7.14M
    BufPtr = Buffer.data() + LHSLen;
780
7.14M
    unsigned RHSLen = PP.getSpelling(RHS, BufPtr, &Invalid);
781
7.14M
    if (Invalid)
782
0
      return true;
783
7.14M
    if (RHSLen && 
BufPtr != &Buffer[LHSLen]7.14M
)
784
      // Really, we want the chars in Buffer!
785
7.14M
      memcpy(&Buffer[LHSLen], BufPtr, RHSLen);
786
787
    // Trim excess space.
788
7.14M
    Buffer.resize(LHSLen+RHSLen);
789
790
    // Plop the pasted result (including the trailing newline and null) into a
791
    // scratch buffer where we can lex it.
792
7.14M
    Token ResultTokTmp;
793
7.14M
    ResultTokTmp.startToken();
794
795
    // Claim that the tmp token is a string_literal so that we can get the
796
    // character pointer back from CreateString in getLiteralData().
797
7.14M
    ResultTokTmp.setKind(tok::string_literal);
798
7.14M
    PP.CreateString(Buffer, ResultTokTmp);
799
7.14M
    SourceLocation ResultTokLoc = ResultTokTmp.getLocation();
800
7.14M
    ResultTokStrPtr = ResultTokTmp.getLiteralData();
801
802
    // Lex the resultant pasted token into Result.
803
7.14M
    Token Result;
804
805
7.14M
    if (LHSTok.isAnyIdentifier() && 
RHS.isAnyIdentifier()7.13M
) {
806
      // Common paste case: identifier+identifier = identifier.  Avoid creating
807
      // a lexer and other overhead.
808
6.56M
      PP.IncrementPasteCounter(true);
809
6.56M
      Result.startToken();
810
6.56M
      Result.setKind(tok::raw_identifier);
811
6.56M
      Result.setRawIdentifierData(ResultTokStrPtr);
812
6.56M
      Result.setLocation(ResultTokLoc);
813
6.56M
      Result.setLength(LHSLen+RHSLen);
814
6.56M
    } else {
815
580k
      PP.IncrementPasteCounter(false);
816
817
580k
      assert(ResultTokLoc.isFileID() &&
818
580k
             "Should be a raw location into scratch buffer");
819
0
      SourceManager &SourceMgr = PP.getSourceManager();
820
580k
      FileID LocFileID = SourceMgr.getFileID(ResultTokLoc);
821
822
580k
      bool Invalid = false;
823
580k
      const char *ScratchBufStart
824
580k
        = SourceMgr.getBufferData(LocFileID, &Invalid).data();
825
580k
      if (Invalid)
826
0
        return false;
827
828
      // Make a lexer to lex this string from.  Lex just this one token.
829
      // Make a lexer object so that we lex and expand the paste result.
830
580k
      Lexer TL(SourceMgr.getLocForStartOfFile(LocFileID),
831
580k
               PP.getLangOpts(), ScratchBufStart,
832
580k
               ResultTokStrPtr, ResultTokStrPtr+LHSLen+RHSLen);
833
834
      // Lex a token in raw mode.  This way it won't look up identifiers
835
      // automatically, lexing off the end will return an eof token, and
836
      // warnings are disabled.  This returns true if the result token is the
837
      // entire buffer.
838
580k
      bool isInvalid = !TL.LexFromRawLexer(Result);
839
840
      // If we got an EOF token, we didn't form even ONE token.  For example, we
841
      // did "/ ## /" to get "//".
842
580k
      isInvalid |= Result.is(tok::eof);
843
844
      // If pasting the two tokens didn't form a full new token, this is an
845
      // error.  This occurs with "x ## +"  and other stuff.  Return with LHSTok
846
      // unmodified and with RHS as the next token to lex.
847
580k
      if (isInvalid) {
848
        // Explicitly convert the token location to have proper expansion
849
        // information so that the user knows where it came from.
850
30
        SourceManager &SM = PP.getSourceManager();
851
30
        SourceLocation Loc =
852
30
          SM.createExpansionLoc(PasteOpLoc, ExpandLocStart, ExpandLocEnd, 2);
853
854
        // Test for the Microsoft extension of /##/ turning into // here on the
855
        // error path.
856
30
        if (PP.getLangOpts().MicrosoftExt && 
LHSTok.is(tok::slash)17
&&
857
30
            
RHS.is(tok::slash)4
) {
858
4
          HandleMicrosoftCommentPaste(LHSTok, Loc);
859
4
          return true;
860
4
        }
861
862
        // Do not emit the error when preprocessing assembler code.
863
26
        if (!PP.getLangOpts().AsmPreprocessor) {
864
          // If we're in microsoft extensions mode, downgrade this from a hard
865
          // error to an extension that defaults to an error.  This allows
866
          // disabling it.
867
17
          PP.Diag(Loc, PP.getLangOpts().MicrosoftExt ? 
diag::ext_pp_bad_paste_ms12
868
17
                                                     : 
diag::err_pp_bad_paste5
)
869
17
              << Buffer;
870
17
        }
871
872
        // An error has occurred so exit loop.
873
26
        break;
874
30
      }
875
876
      // Turn ## into 'unknown' to avoid # ## # from looking like a paste
877
      // operator.
878
579k
      if (Result.is(tok::hashhash))
879
2
        Result.setKind(tok::unknown);
880
579k
    }
881
882
    // Transfer properties of the LHS over the Result.
883
7.14M
    Result.setFlagValue(Token::StartOfLine , LHSTok.isAtStartOfLine());
884
7.14M
    Result.setFlagValue(Token::LeadingSpace, LHSTok.hasLeadingSpace());
885
886
    // Finally, replace LHS with the result, consume the RHS, and iterate.
887
7.14M
    ++CurIdx;
888
7.14M
    LHSTok = Result;
889
7.14M
  } while (!IsAtEnd() && 
TokenStream[CurIdx].is(tok::hashhash)5.81M
);
890
891
6.16M
  SourceLocation EndLoc = TokenStream[CurIdx - 1].getLocation();
892
893
  // The token's current location indicate where the token was lexed from.  We
894
  // need this information to compute the spelling of the token, but any
895
  // diagnostics for the expanded token should appear as if the token was
896
  // expanded from the full ## expression. Pull this information together into
897
  // a new SourceLocation that captures all of this.
898
6.16M
  SourceManager &SM = PP.getSourceManager();
899
6.16M
  if (StartLoc.isFileID())
900
5.56M
    StartLoc = getExpansionLocForMacroDefLoc(StartLoc);
901
6.16M
  if (EndLoc.isFileID())
902
36.3k
    EndLoc = getExpansionLocForMacroDefLoc(EndLoc);
903
6.16M
  FileID MacroFID = SM.getFileID(MacroExpansionStart);
904
6.76M
  while (SM.getFileID(StartLoc) != MacroFID)
905
596k
    StartLoc = SM.getImmediateExpansionRange(StartLoc).getBegin();
906
12.2M
  while (SM.getFileID(EndLoc) != MacroFID)
907
6.12M
    EndLoc = SM.getImmediateExpansionRange(EndLoc).getEnd();
908
909
6.16M
  LHSTok.setLocation(SM.createExpansionLoc(LHSTok.getLocation(), StartLoc, EndLoc,
910
6.16M
                                        LHSTok.getLength()));
911
912
  // Now that we got the result token, it will be subject to expansion.  Since
913
  // token pasting re-lexes the result token in raw mode, identifier information
914
  // isn't looked up.  As such, if the result is an identifier, look up id info.
915
6.16M
  if (LHSTok.is(tok::raw_identifier)) {
916
    // Look up the identifier info for the token.  We disabled identifier lookup
917
    // by saying we're skipping contents, so we need to do this manually.
918
6.16M
    PP.LookUpIdentifierInfo(LHSTok);
919
6.16M
  }
920
6.16M
  return false;
921
6.16M
}
922
923
/// isNextTokenLParen - If the next token lexed will pop this macro off the
924
/// expansion stack, return 2.  If the next unexpanded token is a '(', return
925
/// 1, otherwise return 0.
926
21.2M
unsigned TokenLexer::isNextTokenLParen() const {
927
  // Out of tokens?
928
21.2M
  if (isAtEnd())
929
2.27M
    return 2;
930
18.9M
  return Tokens[CurTokenIdx].is(tok::l_paren);
931
21.2M
}
932
933
/// isParsingPreprocessorDirective - Return true if we are in the middle of a
934
/// preprocessor directive.
935
503k
bool TokenLexer::isParsingPreprocessorDirective() const {
936
503k
  return Tokens[NumTokens-1].is(tok::eod) && 
!isAtEnd()29
;
937
503k
}
938
939
/// HandleMicrosoftCommentPaste - In microsoft compatibility mode, /##/ pastes
940
/// together to form a comment that comments out everything in the current
941
/// macro, other active macros, and anything left on the current physical
942
/// source line of the expanded buffer.  Handle this by returning the
943
/// first token on the next line.
944
4
void TokenLexer::HandleMicrosoftCommentPaste(Token &Tok, SourceLocation OpLoc) {
945
4
  PP.Diag(OpLoc, diag::ext_comment_paste_microsoft);
946
947
  // We 'comment out' the rest of this macro by just ignoring the rest of the
948
  // tokens that have not been lexed yet, if any.
949
950
  // Since this must be a macro, mark the macro enabled now that it is no longer
951
  // being expanded.
952
4
  assert(Macro && "Token streams can't paste comments");
953
0
  Macro->EnableMacro();
954
955
4
  PP.HandleMicrosoftCommentPaste(Tok);
956
4
}
957
958
/// If \arg loc is a file ID and points inside the current macro
959
/// definition, returns the appropriate source location pointing at the
960
/// macro expansion source location entry, otherwise it returns an invalid
961
/// SourceLocation.
962
SourceLocation
963
487M
TokenLexer::getExpansionLocForMacroDefLoc(SourceLocation loc) const {
964
487M
  assert(ExpandLocStart.isValid() && MacroExpansionStart.isValid() &&
965
487M
         "Not appropriate for token streams");
966
0
  assert(loc.isValid() && loc.isFileID());
967
968
0
  SourceManager &SM = PP.getSourceManager();
969
487M
  assert(SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength) &&
970
487M
         "Expected loc to come from the macro definition");
971
972
0
  SourceLocation::UIntTy relativeOffset = 0;
973
487M
  SM.isInSLocAddrSpace(loc, MacroDefStart, MacroDefLength, &relativeOffset);
974
487M
  return MacroExpansionStart.getLocWithOffset(relativeOffset);
975
487M
}
976
977
/// Finds the tokens that are consecutive (from the same FileID)
978
/// creates a single SLocEntry, and assigns SourceLocations to each token that
979
/// point to that SLocEntry. e.g for
980
///   assert(foo == bar);
981
/// There will be a single SLocEntry for the "foo == bar" chunk and locations
982
/// for the 'foo', '==', 'bar' tokens will point inside that chunk.
983
///
984
/// \arg begin_tokens will be updated to a position past all the found
985
/// consecutive tokens.
986
static void updateConsecutiveMacroArgTokens(SourceManager &SM,
987
                                            SourceLocation InstLoc,
988
                                            Token *&begin_tokens,
989
16.7M
                                            Token * end_tokens) {
990
16.7M
  assert(begin_tokens < end_tokens);
991
992
0
  SourceLocation FirstLoc = begin_tokens->getLocation();
993
16.7M
  SourceLocation CurLoc = FirstLoc;
994
995
  // Compare the source location offset of tokens and group together tokens that
996
  // are close, even if their locations point to different FileIDs. e.g.
997
  //
998
  //  |bar    |  foo | cake   |  (3 tokens from 3 consecutive FileIDs)
999
  //  ^                    ^
1000
  //  |bar       foo   cake|     (one SLocEntry chunk for all tokens)
1001
  //
1002
  // we can perform this "merge" since the token's spelling location depends
1003
  // on the relative offset.
1004
1005
16.7M
  Token *NextTok = begin_tokens + 1;
1006
79.5M
  for (; NextTok < end_tokens; 
++NextTok62.8M
) {
1007
69.2M
    SourceLocation NextLoc = NextTok->getLocation();
1008
69.2M
    if (CurLoc.isFileID() != NextLoc.isFileID())
1009
189k
      break; // Token from different kind of FileID.
1010
1011
69.0M
    SourceLocation::IntTy RelOffs;
1012
69.0M
    if (!SM.isInSameSLocAddrSpace(CurLoc, NextLoc, &RelOffs))
1013
0
      break; // Token from different local/loaded location.
1014
    // Check that token is not before the previous token or more than 50
1015
    // "characters" away.
1016
69.0M
    if (RelOffs < 0 || 
RelOffs > 5067.5M
)
1017
1.73M
      break;
1018
1019
67.3M
    if (CurLoc.isMacroID() && 
!SM.isWrittenInSameFile(CurLoc, NextLoc)36.0M
)
1020
4.50M
      break; // Token from a different macro.
1021
1022
62.8M
    CurLoc = NextLoc;
1023
62.8M
  }
1024
1025
  // For the consecutive tokens, find the length of the SLocEntry to contain
1026
  // all of them.
1027
16.7M
  Token &LastConsecutiveTok = *(NextTok-1);
1028
16.7M
  SourceLocation::IntTy LastRelOffs = 0;
1029
16.7M
  SM.isInSameSLocAddrSpace(FirstLoc, LastConsecutiveTok.getLocation(),
1030
16.7M
                           &LastRelOffs);
1031
16.7M
  SourceLocation::UIntTy FullLength =
1032
16.7M
      LastRelOffs + LastConsecutiveTok.getLength();
1033
1034
  // Create a macro expansion SLocEntry that will "contain" all of the tokens.
1035
16.7M
  SourceLocation Expansion =
1036
16.7M
      SM.createMacroArgExpansionLoc(FirstLoc, InstLoc,FullLength);
1037
1038
  // Change the location of the tokens from the spelling location to the new
1039
  // expanded location.
1040
96.2M
  for (; begin_tokens < NextTok; 
++begin_tokens79.5M
) {
1041
79.5M
    Token &Tok = *begin_tokens;
1042
79.5M
    SourceLocation::IntTy RelOffs = 0;
1043
79.5M
    SM.isInSameSLocAddrSpace(FirstLoc, Tok.getLocation(), &RelOffs);
1044
79.5M
    Tok.setLocation(Expansion.getLocWithOffset(RelOffs));
1045
79.5M
  }
1046
16.7M
}
1047
1048
/// Creates SLocEntries and updates the locations of macro argument
1049
/// tokens to their new expanded locations.
1050
///
1051
/// \param ArgIdSpellLoc the location of the macro argument id inside the macro
1052
/// definition.
1053
void TokenLexer::updateLocForMacroArgTokens(SourceLocation ArgIdSpellLoc,
1054
                                            Token *begin_tokens,
1055
29.8M
                                            Token *end_tokens) {
1056
29.8M
  SourceManager &SM = PP.getSourceManager();
1057
1058
29.8M
  SourceLocation InstLoc =
1059
29.8M
      getExpansionLocForMacroDefLoc(ArgIdSpellLoc);
1060
1061
46.6M
  while (begin_tokens < end_tokens) {
1062
    // If there's only one token just create a SLocEntry for it.
1063
36.3M
    if (end_tokens - begin_tokens == 1) {
1064
19.6M
      Token &Tok = *begin_tokens;
1065
19.6M
      Tok.setLocation(SM.createMacroArgExpansionLoc(Tok.getLocation(),
1066
19.6M
                                                    InstLoc,
1067
19.6M
                                                    Tok.getLength()));
1068
19.6M
      return;
1069
19.6M
    }
1070
1071
16.7M
    updateConsecutiveMacroArgTokens(SM, InstLoc, begin_tokens, end_tokens);
1072
16.7M
  }
1073
29.8M
}
1074
1075
23.5M
void TokenLexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
1076
23.5M
  AtStartOfLine = Result.isAtStartOfLine();
1077
23.5M
  HasLeadingSpace = Result.hasLeadingSpace();
1078
23.5M
}