Coverage Report

Created: 2020-02-15 09:57

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