Coverage Report

Created: 2020-02-18 08:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Lex/LiteralSupport.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
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 NumericLiteralParser, CharLiteralParser, and
10
// StringLiteralParser interfaces.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Lex/LiteralSupport.h"
15
#include "clang/Basic/CharInfo.h"
16
#include "clang/Basic/LangOptions.h"
17
#include "clang/Basic/SourceLocation.h"
18
#include "clang/Basic/TargetInfo.h"
19
#include "clang/Lex/LexDiagnostic.h"
20
#include "clang/Lex/Lexer.h"
21
#include "clang/Lex/Preprocessor.h"
22
#include "clang/Lex/Token.h"
23
#include "llvm/ADT/APInt.h"
24
#include "llvm/ADT/SmallVector.h"
25
#include "llvm/ADT/StringExtras.h"
26
#include "llvm/ADT/StringSwitch.h"
27
#include "llvm/Support/ConvertUTF.h"
28
#include "llvm/Support/ErrorHandling.h"
29
#include <algorithm>
30
#include <cassert>
31
#include <cstddef>
32
#include <cstdint>
33
#include <cstring>
34
#include <string>
35
36
using namespace clang;
37
38
4.83M
static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
39
4.83M
  switch (kind) {
40
0
  default: llvm_unreachable("Unknown token type!");
41
4.83M
  case tok::char_constant:
42
4.83M
  case tok::string_literal:
43
4.83M
  case tok::utf8_char_constant:
44
4.83M
  case tok::utf8_string_literal:
45
4.83M
    return Target.getCharWidth();
46
4.83M
  case tok::wide_char_constant:
47
1.17k
  case tok::wide_string_literal:
48
1.17k
    return Target.getWCharWidth();
49
1.17k
  case tok::utf16_char_constant:
50
161
  case tok::utf16_string_literal:
51
161
    return Target.getChar16Width();
52
161
  case tok::utf32_char_constant:
53
154
  case tok::utf32_string_literal:
54
154
    return Target.getChar32Width();
55
4.83M
  }
56
4.83M
}
57
58
static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
59
                                           FullSourceLoc TokLoc,
60
                                           const char *TokBegin,
61
                                           const char *TokRangeBegin,
62
367
                                           const char *TokRangeEnd) {
63
367
  SourceLocation Begin =
64
367
    Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
65
367
                                   TokLoc.getManager(), Features);
66
367
  SourceLocation End =
67
367
    Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
68
367
                                   TokLoc.getManager(), Features);
69
367
  return CharSourceRange::getCharRange(Begin, End);
70
367
}
71
72
/// Produce a diagnostic highlighting some portion of a literal.
73
///
74
/// Emits the diagnostic \p DiagID, highlighting the range of characters from
75
/// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
76
/// a substring of a spelling buffer for the token beginning at \p TokBegin.
77
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
78
                              const LangOptions &Features, FullSourceLoc TokLoc,
79
                              const char *TokBegin, const char *TokRangeBegin,
80
223
                              const char *TokRangeEnd, unsigned DiagID) {
81
223
  SourceLocation Begin =
82
223
    Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
83
223
                                   TokLoc.getManager(), Features);
84
223
  return Diags->Report(Begin, DiagID) <<
85
223
    MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
86
223
}
87
88
/// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
89
/// either a character or a string literal.
90
static unsigned ProcessCharEscape(const char *ThisTokBegin,
91
                                  const char *&ThisTokBuf,
92
                                  const char *ThisTokEnd, bool &HadError,
93
                                  FullSourceLoc Loc, unsigned CharWidth,
94
                                  DiagnosticsEngine *Diags,
95
60.8k
                                  const LangOptions &Features) {
96
60.8k
  const char *EscapeBegin = ThisTokBuf;
97
60.8k
98
60.8k
  // Skip the '\' char.
99
60.8k
  ++ThisTokBuf;
100
60.8k
101
60.8k
  // We know that this character can't be off the end of the buffer, because
102
60.8k
  // that would have been \", which would not have been the end of string.
103
60.8k
  unsigned ResultChar = *ThisTokBuf++;
104
60.8k
  switch (ResultChar) {
105
0
  // These map to themselves.
106
1.09k
  case '\\': case '\'': case '"': case '?': break;
107
1.09k
108
1.09k
    // These have fixed mappings.
109
1.09k
  case 'a':
110
21
    // TODO: K&R: the meaning of '\\a' is different in traditional C
111
21
    ResultChar = 7;
112
21
    break;
113
1.09k
  case 'b':
114
20
    ResultChar = 8;
115
20
    break;
116
1.09k
  case 'e':
117
15
    if (Diags)
118
15
      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
119
15
           diag::ext_nonstandard_escape) << "e";
120
15
    ResultChar = 27;
121
15
    break;
122
1.09k
  case 'E':
123
1
    if (Diags)
124
1
      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
125
1
           diag::ext_nonstandard_escape) << "E";
126
1
    ResultChar = 27;
127
1
    break;
128
1.09k
  case 'f':
129
15
    ResultChar = 12;
130
15
    break;
131
53.7k
  case 'n':
132
53.7k
    ResultChar = 10;
133
53.7k
    break;
134
1.09k
  case 'r':
135
39
    ResultChar = 13;
136
39
    break;
137
2.35k
  case 't':
138
2.35k
    ResultChar = 9;
139
2.35k
    break;
140
1.09k
  case 'v':
141
27
    ResultChar = 11;
142
27
    break;
143
1.09k
  case 'x': { // Hex escape.
144
1.02k
    ResultChar = 0;
145
1.02k
    if (ThisTokBuf == ThisTokEnd || 
!isHexDigit(*ThisTokBuf)1.02k
) {
146
6
      if (Diags)
147
6
        Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
148
6
             diag::err_hex_escape_no_digits) << "x";
149
6
      HadError = true;
150
6
      break;
151
6
    }
152
1.02k
153
1.02k
    // Hex escapes are a maximal series of hex digits.
154
1.02k
    bool Overflow = false;
155
3.29k
    for (; ThisTokBuf != ThisTokEnd; 
++ThisTokBuf2.27k
) {
156
2.52k
      int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
157
2.52k
      if (CharVal == -1) 
break252
;
158
2.27k
      // About to shift out a digit?
159
2.27k
      if (ResultChar & 0xF0000000)
160
0
        Overflow = true;
161
2.27k
      ResultChar <<= 4;
162
2.27k
      ResultChar |= CharVal;
163
2.27k
    }
164
1.02k
165
1.02k
    // See if any bits will be truncated when evaluated as a character.
166
1.02k
    if (CharWidth != 32 && 
(ResultChar >> CharWidth) != 0932
) {
167
0
      Overflow = true;
168
0
      ResultChar &= ~0U >> (32-CharWidth);
169
0
    }
170
1.02k
171
1.02k
    // Check for overflow.
172
1.02k
    if (Overflow && 
Diags0
) // Too many digits to fit in
173
0
      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
174
0
           diag::err_escape_too_large) << 0;
175
1.02k
    break;
176
1.02k
  }
177
2.45k
  case '0': case '1': case '2': case '3':
178
2.45k
  case '4': case '5': case '6': case '7': {
179
2.45k
    // Octal escapes.
180
2.45k
    --ThisTokBuf;
181
2.45k
    ResultChar = 0;
182
2.45k
183
2.45k
    // Octal escapes are a series of octal digits with maximum length 3.
184
2.45k
    // "\0123" is a two digit sequence equal to "\012" "3".
185
2.45k
    unsigned NumDigits = 0;
186
2.66k
    do {
187
2.66k
      ResultChar <<= 3;
188
2.66k
      ResultChar |= *ThisTokBuf++ - '0';
189
2.66k
      ++NumDigits;
190
2.66k
    } while (ThisTokBuf != ThisTokEnd && 
NumDigits < 31.61k
&&
191
2.66k
             
ThisTokBuf[0] >= '0'1.60k
&&
ThisTokBuf[0] <= '7'1.54k
);
192
2.45k
193
2.45k
    // Check for overflow.  Reject '\777', but not L'\777'.
194
2.45k
    if (CharWidth != 32 && 
(ResultChar >> CharWidth) != 02.27k
) {
195
1
      if (Diags)
196
1
        Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
197
1
             diag::err_escape_too_large) << 1;
198
1
      ResultChar &= ~0U >> (32-CharWidth);
199
1
    }
200
2.45k
    break;
201
2.45k
  }
202
2.45k
203
2.45k
    // Otherwise, these are not valid escapes.
204
2.45k
  
case '(': 28
case '{': 28
case '[': 28
case '%':
205
28
    // GCC accepts these as extensions.  We warn about them as such though.
206
28
    if (Diags)
207
22
      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
208
22
           diag::ext_nonstandard_escape)
209
22
        << std::string(1, ResultChar);
210
28
    break;
211
28
  default:
212
10
    if (!Diags)
213
0
      break;
214
10
215
10
    if (isPrintable(ResultChar))
216
8
      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
217
8
           diag::ext_unknown_escape)
218
8
        << std::string(1, ResultChar);
219
2
    else
220
2
      Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
221
2
           diag::ext_unknown_escape)
222
2
        << "x" + llvm::utohexstr(ResultChar);
223
10
    break;
224
60.8k
  }
225
60.8k
226
60.8k
  return ResultChar;
227
60.8k
}
228
229
static void appendCodePoint(unsigned Codepoint,
230
180
                            llvm::SmallVectorImpl<char> &Str) {
231
180
  char ResultBuf[4];
232
180
  char *ResultPtr = ResultBuf;
233
180
  bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
234
180
  (void)Res;
235
180
  assert(Res && "Unexpected conversion failure");
236
180
  Str.append(ResultBuf, ResultPtr);
237
180
}
238
239
783
void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
240
3.01k
  for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; 
++I2.23k
) {
241
2.23k
    if (*I != '\\') {
242
2.05k
      Buf.push_back(*I);
243
2.05k
      continue;
244
2.05k
    }
245
180
246
180
    ++I;
247
180
    assert(*I == 'u' || *I == 'U');
248
180
249
180
    unsigned NumHexDigits;
250
180
    if (*I == 'u')
251
159
      NumHexDigits = 4;
252
21
    else
253
21
      NumHexDigits = 8;
254
180
255
180
    assert(I + NumHexDigits <= E);
256
180
257
180
    uint32_t CodePoint = 0;
258
984
    for (++I; NumHexDigits != 0; 
++I, --NumHexDigits804
) {
259
804
      unsigned Value = llvm::hexDigitValue(*I);
260
804
      assert(Value != -1U);
261
804
262
804
      CodePoint <<= 4;
263
804
      CodePoint += Value;
264
804
    }
265
180
266
180
    appendCodePoint(CodePoint, Buf);
267
180
    --I;
268
180
  }
269
783
}
270
271
/// ProcessUCNEscape - Read the Universal Character Name, check constraints and
272
/// return the UTF32.
273
static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
274
                             const char *ThisTokEnd,
275
                             uint32_t &UcnVal, unsigned short &UcnLen,
276
                             FullSourceLoc Loc, DiagnosticsEngine *Diags,
277
                             const LangOptions &Features,
278
380
                             bool in_char_string_literal = false) {
279
380
  const char *UcnBegin = ThisTokBuf;
280
380
281
380
  // Skip the '\u' char's.
282
380
  ThisTokBuf += 2;
283
380
284
380
  if (ThisTokBuf == ThisTokEnd || 
!isHexDigit(*ThisTokBuf)377
) {
285
4
    if (Diags)
286
4
      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
287
4
           diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
288
4
    return false;
289
4
  }
290
376
  UcnLen = (ThisTokBuf[-1] == 'u' ? 
4288
:
888
);
291
376
  unsigned short UcnLenSave = UcnLen;
292
2.21k
  for (; ThisTokBuf != ThisTokEnd && 
UcnLenSave1.96k
;
++ThisTokBuf, UcnLenSave--1.83k
) {
293
1.84k
    int CharVal = llvm::hexDigitValue(ThisTokBuf[0]);
294
1.84k
    if (CharVal == -1) 
break4
;
295
1.83k
    UcnVal <<= 4;
296
1.83k
    UcnVal |= CharVal;
297
1.83k
  }
298
376
  // If we didn't consume the proper number of digits, there is a problem.
299
376
  if (UcnLenSave) {
300
6
    if (Diags)
301
6
      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
302
6
           diag::err_ucn_escape_incomplete);
303
6
    return false;
304
6
  }
305
370
306
370
  // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
307
370
  if ((0xD800 <= UcnVal && 
UcnVal <= 0xDFFF118
) || // surrogate codepoints
308
370
      
UcnVal > 0x10FFFF354
) { // maximum legal UTF32 value
309
19
    if (Diags)
310
19
      Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
311
19
           diag::err_ucn_escape_invalid);
312
19
    return false;
313
19
  }
314
351
315
351
  // C++11 allows UCNs that refer to control characters and basic source
316
351
  // characters inside character and string literals
317
351
  if (UcnVal < 0xa0 &&
318
351
      
(115
UcnVal != 0x24115
&&
UcnVal != 0x40111
&&
UcnVal != 0x60107
)) { // $, @, `
319
103
    bool IsError = (!Features.CPlusPlus11 || 
!in_char_string_literal70
);
320
103
    if (Diags) {
321
103
      char BasicSCSChar = UcnVal;
322
103
      if (UcnVal >= 0x20 && 
UcnVal < 0x7f79
)
323
48
        Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
324
48
             IsError ? 
diag::err_ucn_escape_basic_scs18
:
325
48
                       
diag::warn_cxx98_compat_literal_ucn_escape_basic_scs30
)
326
48
            << StringRef(&BasicSCSChar, 1);
327
55
      else
328
55
        Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
329
55
             IsError ? 
diag::err_ucn_control_character15
:
330
55
                       
diag::warn_cxx98_compat_literal_ucn_control_character40
);
331
103
    }
332
103
    if (IsError)
333
33
      return false;
334
318
  }
335
318
336
318
  if (!Features.CPlusPlus && 
!Features.C99108
&&
Diags2
)
337
2
    Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
338
2
         diag::warn_ucn_not_valid_in_c89_literal);
339
318
340
318
  return true;
341
318
}
342
343
/// MeasureUCNEscape - Determine the number of bytes within the resulting string
344
/// which this UCN will occupy.
345
static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
346
                            const char *ThisTokEnd, unsigned CharByteWidth,
347
6
                            const LangOptions &Features, bool &HadError) {
348
6
  // UTF-32: 4 bytes per escape.
349
6
  if (CharByteWidth == 4)
350
0
    return 4;
351
6
352
6
  uint32_t UcnVal = 0;
353
6
  unsigned short UcnLen = 0;
354
6
  FullSourceLoc Loc;
355
6
356
6
  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
357
6
                        UcnLen, Loc, nullptr, Features, true)) {
358
0
    HadError = true;
359
0
    return 0;
360
0
  }
361
6
362
6
  // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
363
6
  if (CharByteWidth == 2)
364
0
    return UcnVal <= 0xFFFF ? 2 : 4;
365
6
366
6
  // UTF-8.
367
6
  if (UcnVal < 0x80)
368
0
    return 1;
369
6
  if (UcnVal < 0x800)
370
0
    return 2;
371
6
  if (UcnVal < 0x10000)
372
3
    return 3;
373
3
  return 4;
374
3
}
375
376
/// EncodeUCNEscape - Read the Universal Character Name, check constraints and
377
/// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
378
/// StringLiteralParser. When we decide to implement UCN's for identifiers,
379
/// we will likely rework our support for UCN's.
380
static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
381
                            const char *ThisTokEnd,
382
                            char *&ResultBuf, bool &HadError,
383
                            FullSourceLoc Loc, unsigned CharByteWidth,
384
                            DiagnosticsEngine *Diags,
385
267
                            const LangOptions &Features) {
386
267
  typedef uint32_t UTF32;
387
267
  UTF32 UcnVal = 0;
388
267
  unsigned short UcnLen = 0;
389
267
  if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
390
267
                        Loc, Diags, Features, true)) {
391
33
    HadError = true;
392
33
    return;
393
33
  }
394
234
395
234
  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
396
234
         "only character widths of 1, 2, or 4 bytes supported");
397
234
398
234
  (void)UcnLen;
399
234
  assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
400
234
401
234
  if (CharByteWidth == 4) {
402
66
    // FIXME: Make the type of the result buffer correct instead of
403
66
    // using reinterpret_cast.
404
66
    llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
405
66
    *ResultPtr = UcnVal;
406
66
    ResultBuf += 4;
407
66
    return;
408
66
  }
409
168
410
168
  if (CharByteWidth == 2) {
411
53
    // FIXME: Make the type of the result buffer correct instead of
412
53
    // using reinterpret_cast.
413
53
    llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
414
53
415
53
    if (UcnVal <= (UTF32)0xFFFF) {
416
39
      *ResultPtr = UcnVal;
417
39
      ResultBuf += 2;
418
39
      return;
419
39
    }
420
14
421
14
    // Convert to UTF16.
422
14
    UcnVal -= 0x10000;
423
14
    *ResultPtr     = 0xD800 + (UcnVal >> 10);
424
14
    *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
425
14
    ResultBuf += 4;
426
14
    return;
427
14
  }
428
115
429
115
  assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
430
115
431
115
  // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
432
115
  // The conversion below was inspired by:
433
115
  //   http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
434
115
  // First, we determine how many bytes the result will require.
435
115
  typedef uint8_t UTF8;
436
115
437
115
  unsigned short bytesToWrite = 0;
438
115
  if (UcnVal < (UTF32)0x80)
439
28
    bytesToWrite = 1;
440
87
  else if (UcnVal < (UTF32)0x800)
441
15
    bytesToWrite = 2;
442
72
  else if (UcnVal < (UTF32)0x10000)
443
48
    bytesToWrite = 3;
444
24
  else
445
24
    bytesToWrite = 4;
446
115
447
115
  const unsigned byteMask = 0xBF;
448
115
  const unsigned byteMark = 0x80;
449
115
450
115
  // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
451
115
  // into the first byte, depending on how many bytes follow.
452
115
  static const UTF8 firstByteMark[5] = {
453
115
    0x00, 0x00, 0xC0, 0xE0, 0xF0
454
115
  };
455
115
  // Finally, we write the bytes into ResultBuf.
456
115
  ResultBuf += bytesToWrite;
457
115
  switch (bytesToWrite) { // note: everything falls through.
458
24
  case 4:
459
24
    *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
460
24
    LLVM_FALLTHROUGH;
461
72
  case 3:
462
72
    *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
463
72
    LLVM_FALLTHROUGH;
464
87
  case 2:
465
87
    *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
466
87
    LLVM_FALLTHROUGH;
467
115
  case 1:
468
115
    *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
469
115
  }
470
115
  // Update the buffer.
471
115
  ResultBuf += bytesToWrite;
472
115
}
473
474
///       integer-constant: [C99 6.4.4.1]
475
///         decimal-constant integer-suffix
476
///         octal-constant integer-suffix
477
///         hexadecimal-constant integer-suffix
478
///         binary-literal integer-suffix [GNU, C++1y]
479
///       user-defined-integer-literal: [C++11 lex.ext]
480
///         decimal-literal ud-suffix
481
///         octal-literal ud-suffix
482
///         hexadecimal-literal ud-suffix
483
///         binary-literal ud-suffix [GNU, C++1y]
484
///       decimal-constant:
485
///         nonzero-digit
486
///         decimal-constant digit
487
///       octal-constant:
488
///         0
489
///         octal-constant octal-digit
490
///       hexadecimal-constant:
491
///         hexadecimal-prefix hexadecimal-digit
492
///         hexadecimal-constant hexadecimal-digit
493
///       hexadecimal-prefix: one of
494
///         0x 0X
495
///       binary-literal:
496
///         0b binary-digit
497
///         0B binary-digit
498
///         binary-literal binary-digit
499
///       integer-suffix:
500
///         unsigned-suffix [long-suffix]
501
///         unsigned-suffix [long-long-suffix]
502
///         long-suffix [unsigned-suffix]
503
///         long-long-suffix [unsigned-sufix]
504
///       nonzero-digit:
505
///         1 2 3 4 5 6 7 8 9
506
///       octal-digit:
507
///         0 1 2 3 4 5 6 7
508
///       hexadecimal-digit:
509
///         0 1 2 3 4 5 6 7 8 9
510
///         a b c d e f
511
///         A B C D E F
512
///       binary-digit:
513
///         0
514
///         1
515
///       unsigned-suffix: one of
516
///         u U
517
///       long-suffix: one of
518
///         l L
519
///       long-long-suffix: one of
520
///         ll LL
521
///
522
///       floating-constant: [C99 6.4.4.2]
523
///         TODO: add rules...
524
///
525
NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
526
                                           SourceLocation TokLoc,
527
                                           Preprocessor &PP)
528
8.60M
  : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
529
8.60M
530
8.60M
  // This routine assumes that the range begin/end matches the regex for integer
531
8.60M
  // and FP constants (specifically, the 'pp-number' regex), and assumes that
532
8.60M
  // the byte at "*end" is both valid and not part of the regex.  Because of
533
8.60M
  // this, it doesn't have to check for 'overscan' in various places.
534
8.60M
  assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?");
535
8.60M
536
8.60M
  s = DigitsBegin = ThisTokBegin;
537
8.60M
  saw_exponent = false;
538
8.60M
  saw_period = false;
539
8.60M
  saw_ud_suffix = false;
540
8.60M
  saw_fixed_point_suffix = false;
541
8.60M
  isLong = false;
542
8.60M
  isUnsigned = false;
543
8.60M
  isLongLong = false;
544
8.60M
  isHalf = false;
545
8.60M
  isFloat = false;
546
8.60M
  isImaginary = false;
547
8.60M
  isFloat16 = false;
548
8.60M
  isFloat128 = false;
549
8.60M
  MicrosoftInteger = 0;
550
8.60M
  isFract = false;
551
8.60M
  isAccum = false;
552
8.60M
  hadError = false;
553
8.60M
554
8.60M
  if (*s == '0') { // parse radix
555
1.61M
    ParseNumberStartingWithZero(TokLoc);
556
1.61M
    if (hadError)
557
29
      return;
558
6.99M
  } else { // the first digit is non-zero
559
6.99M
    radix = 10;
560
6.99M
    s = SkipDigits(s);
561
6.99M
    if (s == ThisTokEnd) {
562
6.42M
      // Done.
563
6.42M
    } else {
564
571k
      ParseDecimalOrOctalCommon(TokLoc);
565
571k
      if (hadError)
566
7
        return;
567
8.60M
    }
568
6.99M
  }
569
8.60M
570
8.60M
  SuffixBegin = s;
571
8.60M
  checkSeparator(TokLoc, s, CSK_AfterDigits);
572
8.60M
573
8.60M
  // Initial scan to lookahead for fixed point suffix.
574
8.60M
  if (PP.getLangOpts().FixedPoint) {
575
946
    for (const char *c = s; c != ThisTokEnd; 
++c474
) {
576
925
      if (*c == 'r' || 
*c == 'k'807
||
*c == 'R'474
||
*c == 'K'474
) {
577
451
        saw_fixed_point_suffix = true;
578
451
        break;
579
451
      }
580
925
    }
581
472
  }
582
8.60M
583
8.60M
  // Parse the suffix.  At this point we can classify whether we have an FP or
584
8.60M
  // integer constant.
585
8.60M
  bool isFPConstant = isFloatingLiteral();
586
8.60M
587
8.60M
  // Loop over all of the characters of the suffix.  If we see something bad,
588
8.60M
  // we break out of the loop.
589
9.33M
  for (; s != ThisTokEnd; 
++s725k
) {
590
725k
    switch (*s) {
591
124
    case 'R':
592
124
    case 'r':
593
124
      if (!PP.getLangOpts().FixedPoint) 
break6
;
594
118
      if (isFract || 
isAccum117
)
break1
;
595
117
      if (!(saw_period || 
saw_exponent26
))
break20
;
596
97
      isFract = true;
597
97
      continue;
598
338
    case 'K':
599
338
    case 'k':
600
338
      if (!PP.getLangOpts().FixedPoint) 
break6
;
601
332
      if (isFract || 
isAccum331
)
break2
;
602
330
      if (!(saw_period || 
saw_exponent43
))
break23
;
603
307
      isAccum = true;
604
307
      continue;
605
307
    case 'h':      // FP Suffix for "half".
606
248
    case 'H':
607
248
      // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
608
248
      if (!(PP.getLangOpts().Half || 
PP.getLangOpts().FixedPoint233
))
break3
;
609
245
      if (isIntegerLiteral()) 
break0
; // Error for integer constant.
610
245
      if (isHalf || 
isFloat244
||
isLong243
)
break3
; // HH, FH, LH invalid.
611
242
      isHalf = true;
612
242
      continue;  // Success.
613
6.63k
    case 'f':      // FP Suffix for "float"
614
6.63k
    case 'F':
615
6.63k
      if (!isFPConstant) 
break4
; // Error for integer constant.
616
6.63k
      if (isHalf || 
isFloat6.62k
||
isLong6.62k
||
isFloat1286.62k
)
617
1
        break; // HF, FF, LF, QF invalid.
618
6.62k
619
6.62k
      // CUDA host and device may have different _Float16 support, therefore
620
6.62k
      // allows f16 literals to avoid false alarm.
621
6.62k
      // ToDo: more precise check for CUDA.
622
6.62k
      if ((PP.getTargetInfo().hasFloat16Type() || 
PP.getLangOpts().CUDA6.31k
) &&
623
6.62k
          
s + 2 < ThisTokEnd346
&&
s[1] == '1'122
&&
s[2] == '6'122
) {
624
122
        s += 2; // success, eat up 2 characters.
625
122
        isFloat16 = true;
626
122
        continue;
627
122
      }
628
6.50k
629
6.50k
      isFloat = true;
630
6.50k
      continue;  // Success.
631
6.50k
    case 'q':    // FP Suffix for "__float128"
632
171
    case 'Q':
633
171
      if (!isFPConstant) 
break1
; // Error for integer constant.
634
170
      if (isHalf || isFloat || isLong || isFloat128)
635
0
        break; // HQ, FQ, LQ, QQ invalid.
636
170
      isFloat128 = true;
637
170
      continue;  // Success.
638
130k
    case 'u':
639
130k
    case 'U':
640
130k
      if (isFPConstant) 
break0
; // Error for floating constant.
641
130k
      if (isUnsigned) 
break0
; // Cannot be repeated.
642
130k
      isUnsigned = true;
643
130k
      continue;  // Success.
644
587k
    case 'l':
645
587k
    case 'L':
646
587k
      if (isLong || isLongLong) 
break0
; // Cannot be repeated.
647
587k
      if (isHalf || isFloat || isFloat128) 
break0
; // LH, LF, LQ invalid.
648
587k
649
587k
      // Check for long long.  The L's need to be adjacent and the same case.
650
587k
      if (s[1] == s[0]) {
651
40.1k
        assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
652
40.1k
        if (isFPConstant) 
break0
; // long long invalid for floats.
653
40.1k
        isLongLong = true;
654
40.1k
        ++s;  // Eat both of them.
655
547k
      } else {
656
547k
        isLong = true;
657
547k
      }
658
587k
      continue;  // Success.
659
587k
    case 'i':
660
287
    case 'I':
661
287
      if (PP.getLangOpts().MicrosoftExt) {
662
68
        if (isLong || 
isLongLong65
||
MicrosoftInteger62
)
663
6
          break;
664
62
665
62
        if (!isFPConstant) {
666
54
          // Allow i8, i16, i32, and i64.
667
54
          switch (s[1]) {
668
10
          case '8':
669
10
            s += 2; // i8 suffix
670
10
            MicrosoftInteger = 8;
671
10
            break;
672
9
          case '1':
673
9
            if (s[2] == '6') {
674
9
              s += 3; // i16 suffix
675
9
              MicrosoftInteger = 16;
676
9
            }
677
9
            break;
678
9
          case '3':
679
9
            if (s[2] == '2') {
680
9
              s += 3; // i32 suffix
681
9
              MicrosoftInteger = 32;
682
9
            }
683
9
            break;
684
23
          case '6':
685
23
            if (s[2] == '4') {
686
23
              s += 3; // i64 suffix
687
23
              MicrosoftInteger = 64;
688
23
            }
689
23
            break;
690
3
          default:
691
3
            break;
692
62
          }
693
62
        }
694
62
        if (MicrosoftInteger) {
695
51
          assert(s <= ThisTokEnd && "didn't maximally munch?");
696
51
          break;
697
51
        }
698
230
      }
699
230
      LLVM_FALLTHROUGH;
700
356
    case 'j':
701
356
    case 'J':
702
356
      if (isImaginary) 
break0
; // Cannot be repeated.
703
356
      isImaginary = true;
704
356
      continue;  // Success.
705
262
    }
706
262
    // If we reached here, there was an error or a ud-suffix.
707
262
    break;
708
262
  }
709
8.60M
710
8.60M
  // "i", "if", and "il" are user-defined suffixes in C++1y.
711
8.60M
  if (s != ThisTokEnd || 
isImaginary8.60M
) {
712
567
    // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
713
567
    expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
714
567
    if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) {
715
152
      if (!isImaginary) {
716
115
        // Any suffix pieces we might have parsed are actually part of the
717
115
        // ud-suffix.
718
115
        isLong = false;
719
115
        isUnsigned = false;
720
115
        isLongLong = false;
721
115
        isFloat = false;
722
115
        isFloat16 = false;
723
115
        isHalf = false;
724
115
        isImaginary = false;
725
115
        MicrosoftInteger = 0;
726
115
        saw_fixed_point_suffix = false;
727
115
        isFract = false;
728
115
        isAccum = false;
729
115
      }
730
152
731
152
      saw_ud_suffix = true;
732
152
      return;
733
152
    }
734
415
735
415
    if (s != ThisTokEnd) {
736
96
      // Report an error if there are any.
737
96
      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin),
738
96
              diag::err_invalid_suffix_constant)
739
96
          << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant;
740
96
      hadError = true;
741
96
    }
742
415
  }
743
8.60M
744
8.60M
  
if (8.60M
!hadError8.60M
&&
saw_fixed_point_suffix8.60M
) {
745
401
    assert(isFract || isAccum);
746
401
  }
747
8.60M
}
748
749
/// ParseDecimalOrOctalCommon - This method is called for decimal or octal
750
/// numbers. It issues an error for illegal digits, and handles floating point
751
/// parsing. If it detects a floating point number, the radix is set to 10.
752
594k
void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
753
594k
  assert((radix == 8 || radix == 10) && "Unexpected radix");
754
594k
755
594k
  // If we have a hex digit other than 'e' (which denotes a FP exponent) then
756
594k
  // the code is using an incorrect base.
757
594k
  if (isHexDigit(*s) && 
*s != 'e'296
&&
*s != 'E'42
&&
758
594k
      
!isValidUDSuffix(PP.getLangOpts(), StringRef(s, ThisTokEnd - s))10
) {
759
8
    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
760
8
            diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 
17
:
01
);
761
8
    hadError = true;
762
8
    return;
763
8
  }
764
594k
765
594k
  if (*s == '.') {
766
34.7k
    checkSeparator(TokLoc, s, CSK_AfterDigits);
767
34.7k
    s++;
768
34.7k
    radix = 10;
769
34.7k
    saw_period = true;
770
34.7k
    checkSeparator(TokLoc, s, CSK_BeforeDigits);
771
34.7k
    s = SkipDigits(s); // Skip suffix.
772
34.7k
  }
773
594k
  if (*s == 'e' || 
*s == 'E'584k
) { // exponent
774
10.0k
    checkSeparator(TokLoc, s, CSK_AfterDigits);
775
10.0k
    const char *Exponent = s;
776
10.0k
    s++;
777
10.0k
    radix = 10;
778
10.0k
    saw_exponent = true;
779
10.0k
    if (s != ThisTokEnd && 
(10.0k
*s == '+'10.0k
||
*s == '-'8.22k
))
s++9.72k
; // sign
780
10.0k
    const char *first_non_digit = SkipDigits(s);
781
10.0k
    if (containsDigits(s, first_non_digit)) {
782
10.0k
      checkSeparator(TokLoc, s, CSK_BeforeDigits);
783
10.0k
      s = first_non_digit;
784
10.0k
    } else {
785
4
      if (!hadError) {
786
3
        PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
787
3
                diag::err_exponent_has_no_digits);
788
3
        hadError = true;
789
3
      }
790
4
      return;
791
4
    }
792
10.0k
  }
793
594k
}
794
795
/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
796
/// suffixes as ud-suffixes, because the diagnostic experience is better if we
797
/// treat it as an invalid suffix.
798
bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
799
876
                                           StringRef Suffix) {
800
876
  if (!LangOpts.CPlusPlus11 || 
Suffix.empty()624
)
801
252
    return false;
802
624
803
624
  // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
804
624
  if (Suffix[0] == '_')
805
101
    return true;
806
523
807
523
  // In C++11, there are no library suffixes.
808
523
  if (!LangOpts.CPlusPlus14)
809
22
    return false;
810
501
811
501
  // In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
812
501
  // Per tweaked N3660, "il", "i", and "if" are also used in the library.
813
501
  // In C++2a "d" and "y" are used in the library.
814
501
  return llvm::StringSwitch<bool>(Suffix)
815
501
      .Cases("h", "min", "s", true)
816
501
      .Cases("ms", "us", "ns", true)
817
501
      .Cases("il", "i", "if", true)
818
501
      .Cases("d", "y", LangOpts.CPlusPlus2a)
819
501
      .Default(false);
820
501
}
821
822
void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
823
                                          const char *Pos,
824
8.69M
                                          CheckSeparatorKind IsAfterDigits) {
825
8.69M
  if (IsAfterDigits == CSK_AfterDigits) {
826
8.65M
    if (Pos == ThisTokBegin)
827
679
      return;
828
8.64M
    --Pos;
829
8.64M
  } else 
if (44.9k
Pos == ThisTokEnd44.9k
)
830
641
    return;
831
8.69M
832
8.69M
  if (isDigitSeparator(*Pos)) {
833
20
    PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin),
834
20
            diag::err_digit_separator_not_between_digits)
835
20
      << IsAfterDigits;
836
20
    hadError = true;
837
20
  }
838
8.69M
}
839
840
/// ParseNumberStartingWithZero - This method is called when the first character
841
/// of the number is found to be a zero.  This means it is either an octal
842
/// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
843
/// a floating point number (01239.123e4).  Eat the prefix, determining the
844
/// radix etc.
845
1.61M
void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
846
1.61M
  assert(s[0] == '0' && "Invalid method call");
847
1.61M
  s++;
848
1.61M
849
1.61M
  int c1 = s[0];
850
1.61M
851
1.61M
  // Handle a hex number like 0x1234.
852
1.61M
  if ((c1 == 'x' || 
c1 == 'X'523k
) &&
(1.08M
isHexDigit(s[1])1.08M
||
s[1] == '.'14
)) {
853
1.08M
    s++;
854
1.08M
    assert(s < ThisTokEnd && "didn't maximally munch?");
855
1.08M
    radix = 16;
856
1.08M
    DigitsBegin = s;
857
1.08M
    s = SkipHexDigits(s);
858
1.08M
    bool HasSignificandDigits = containsDigits(DigitsBegin, s);
859
1.08M
    if (s == ThisTokEnd) {
860
1.03M
      // Done.
861
1.03M
    } else 
if (54.0k
*s == '.'54.0k
) {
862
58
      s++;
863
58
      saw_period = true;
864
58
      const char *floatDigitsBegin = s;
865
58
      s = SkipHexDigits(s);
866
58
      if (containsDigits(floatDigitsBegin, s))
867
49
        HasSignificandDigits = true;
868
58
      if (HasSignificandDigits)
869
53
        checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
870
58
    }
871
1.08M
872
1.08M
    if (!HasSignificandDigits) {
873
5
      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
874
5
              diag::err_hex_constant_requires)
875
5
          << PP.getLangOpts().CPlusPlus << 1;
876
5
      hadError = true;
877
5
      return;
878
5
    }
879
1.08M
880
1.08M
    // A binary exponent can appear with or with a '.'. If dotted, the
881
1.08M
    // binary exponent is required.
882
1.08M
    if (*s == 'p' || 
*s == 'P'1.08M
) {
883
82
      checkSeparator(TokLoc, s, CSK_AfterDigits);
884
82
      const char *Exponent = s;
885
82
      s++;
886
82
      saw_exponent = true;
887
82
      if (s != ThisTokEnd && 
(81
*s == '+'81
||
*s == '-'61
))
s++40
; // sign
888
82
      const char *first_non_digit = SkipDigits(s);
889
82
      if (!containsDigits(s, first_non_digit)) {
890
2
        if (!hadError) {
891
1
          PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin),
892
1
                  diag::err_exponent_has_no_digits);
893
1
          hadError = true;
894
1
        }
895
2
        return;
896
2
      }
897
80
      checkSeparator(TokLoc, s, CSK_BeforeDigits);
898
80
      s = first_non_digit;
899
80
900
80
      if (!PP.getLangOpts().HexFloats)
901
21
        PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus
902
21
                            ? 
diag::ext_hex_literal_invalid18
903
21
                            : 
diag::ext_hex_constant_invalid3
);
904
59
      else if (PP.getLangOpts().CPlusPlus17)
905
4
        PP.Diag(TokLoc, diag::warn_cxx17_hex_literal);
906
1.08M
    } else if (saw_period) {
907
2
      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin),
908
2
              diag::err_hex_constant_requires)
909
2
          << PP.getLangOpts().CPlusPlus << 0;
910
2
      hadError = true;
911
2
    }
912
1.08M
    
return1.08M
;
913
523k
  }
914
523k
915
523k
  // Handle simple binary numbers 0b01010
916
523k
  if ((c1 == 'b' || 
c1 == 'B'523k
) &&
(53
s[1] == '0'53
||
s[1] == '1'41
)) {
917
49
    // 0b101010 is a C++1y / GCC extension.
918
49
    PP.Diag(TokLoc,
919
49
            PP.getLangOpts().CPlusPlus14
920
49
              ? 
diag::warn_cxx11_compat_binary_literal27
921
49
              : PP.getLangOpts().CPlusPlus
922
22
                ? 
diag::ext_binary_literal_cxx146
923
22
                : 
diag::ext_binary_literal16
);
924
49
    ++s;
925
49
    assert(s < ThisTokEnd && "didn't maximally munch?");
926
49
    radix = 2;
927
49
    DigitsBegin = s;
928
49
    s = SkipBinaryDigits(s);
929
49
    if (s == ThisTokEnd) {
930
42
      // Done.
931
42
    } else 
if (7
isHexDigit(*s)7
&&
932
7
               !isValidUDSuffix(PP.getLangOpts(),
933
3
                                StringRef(s, ThisTokEnd - s))) {
934
2
      PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin),
935
2
              diag::err_invalid_digit) << StringRef(s, 1) << 2;
936
2
      hadError = true;
937
2
    }
938
49
    // Other suffixes will be diagnosed by the caller.
939
49
    return;
940
49
  }
941
523k
942
523k
  // For now, the radix is set to 8. If we discover that we have a
943
523k
  // floating point constant, the radix will change to 10. Octal floating
944
523k
  // point constants are not permitted (only decimal and hexadecimal).
945
523k
  radix = 8;
946
523k
  DigitsBegin = s;
947
523k
  s = SkipOctalDigits(s);
948
523k
  if (s == ThisTokEnd)
949
500k
    return; // Done, simple octal number like 01234
950
23.4k
951
23.4k
  // If we have some other non-octal digit that *is* a decimal digit, see if
952
23.4k
  // this is part of a floating point number like 094.123 or 09e1.
953
23.4k
  if (isDigit(*s)) {
954
3
    const char *EndDecimal = SkipDigits(s);
955
3
    if (EndDecimal[0] == '.' || 
EndDecimal[0] == 'e'2
||
EndDecimal[0] == 'E'2
) {
956
1
      s = EndDecimal;
957
1
      radix = 10;
958
1
    }
959
3
  }
960
23.4k
961
23.4k
  ParseDecimalOrOctalCommon(TokLoc);
962
23.4k
}
963
964
8.57M
static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
965
8.57M
  switch (Radix) {
966
46
  case 2:
967
46
    return NumDigits <= 64;
968
510k
  case 8:
969
510k
    return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
970
6.97M
  case 10:
971
6.97M
    return NumDigits <= 19; // floor(log10(2^64))
972
1.08M
  case 16:
973
1.08M
    return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
974
0
  default:
975
0
    llvm_unreachable("impossible Radix");
976
8.57M
  }
977
8.57M
}
978
979
/// GetIntegerValue - Convert this numeric literal value to an APInt that
980
/// matches Val's input width.  If there is an overflow, set Val to the low bits
981
/// of the result and return true.  Otherwise, return false.
982
8.57M
bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
983
8.57M
  // Fast path: Compute a conservative bound on the maximum number of
984
8.57M
  // bits per digit in this radix. If we can't possibly overflow a
985
8.57M
  // uint64 based on that bound then do the simple conversion to
986
8.57M
  // integer. This avoids the expensive overflow checking below, and
987
8.57M
  // handles the common cases that matter (small decimal integers and
988
8.57M
  // hex/octal values which don't overflow).
989
8.57M
  const unsigned NumDigits = SuffixBegin - DigitsBegin;
990
8.57M
  if (alwaysFitsInto64Bits(radix, NumDigits)) {
991
8.57M
    uint64_t N = 0;
992
32.6M
    for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; 
++Ptr24.0M
)
993
24.0M
      if (!isDigitSeparator(*Ptr))
994
24.0M
        N = N * radix + llvm::hexDigitValue(*Ptr);
995
8.57M
996
8.57M
    // This will truncate the value to Val's input width. Simply check
997
8.57M
    // for overflow by comparing.
998
8.57M
    Val = N;
999
8.57M
    return Val.getZExtValue() != N;
1000
8.57M
  }
1001
153
1002
153
  Val = 0;
1003
153
  const char *Ptr = DigitsBegin;
1004
153
1005
153
  llvm::APInt RadixVal(Val.getBitWidth(), radix);
1006
153
  llvm::APInt CharVal(Val.getBitWidth(), 0);
1007
153
  llvm::APInt OldVal = Val;
1008
153
1009
153
  bool OverflowOccurred = false;
1010
3.24k
  while (Ptr < SuffixBegin) {
1011
3.09k
    if (isDigitSeparator(*Ptr)) {
1012
30
      ++Ptr;
1013
30
      continue;
1014
30
    }
1015
3.06k
1016
3.06k
    unsigned C = llvm::hexDigitValue(*Ptr++);
1017
3.06k
1018
3.06k
    // If this letter is out of bound for this radix, reject it.
1019
3.06k
    assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1020
3.06k
1021
3.06k
    CharVal = C;
1022
3.06k
1023
3.06k
    // Add the digit to the value in the appropriate radix.  If adding in digits
1024
3.06k
    // made the value smaller, then this overflowed.
1025
3.06k
    OldVal = Val;
1026
3.06k
1027
3.06k
    // Multiply by radix, did overflow occur on the multiply?
1028
3.06k
    Val *= RadixVal;
1029
3.06k
    OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
1030
3.06k
1031
3.06k
    // Add value, did overflow occur on the value?
1032
3.06k
    //   (a + b) ult b  <=> overflow
1033
3.06k
    Val += CharVal;
1034
3.06k
    OverflowOccurred |= Val.ult(CharVal);
1035
3.06k
  }
1036
153
  return OverflowOccurred;
1037
153
}
1038
1039
llvm::APFloat::opStatus
1040
34.6k
NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
1041
34.6k
  using llvm::APFloat;
1042
34.6k
1043
34.6k
  unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
1044
34.6k
1045
34.6k
  llvm::SmallString<16> Buffer;
1046
34.6k
  StringRef Str(ThisTokBegin, n);
1047
34.6k
  if (Str.find('\'') != StringRef::npos) {
1048
4
    Buffer.reserve(n);
1049
4
    std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
1050
4
                        &isDigitSeparator);
1051
4
    Str = Buffer;
1052
4
  }
1053
34.6k
1054
34.6k
  auto StatusOrErr =
1055
34.6k
      Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
1056
34.6k
  assert(StatusOrErr && "Invalid floating point representation");
1057
34.6k
  return !errorToBool(StatusOrErr.takeError()) ? *StatusOrErr
1058
34.6k
                                               : 
APFloat::opInvalidOp0
;
1059
34.6k
}
1060
1061
211
static inline bool IsExponentPart(char c) {
1062
211
  return c == 'p' || 
c == 'P'177
||
c == 'e'175
||
c == 'E'158
;
1063
211
}
1064
1065
401
bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
1066
401
  assert(radix == 16 || radix == 10);
1067
401
1068
401
  // Find how many digits are needed to store the whole literal.
1069
401
  unsigned NumDigits = SuffixBegin - DigitsBegin;
1070
401
  if (saw_period) 
--NumDigits375
;
1071
401
1072
401
  // Initial scan of the exponent if it exists
1073
401
  bool ExpOverflowOccurred = false;
1074
401
  bool NegativeExponent = false;
1075
401
  const char *ExponentBegin;
1076
401
  uint64_t Exponent = 0;
1077
401
  int64_t BaseShift = 0;
1078
401
  if (saw_exponent) {
1079
55
    const char *Ptr = DigitsBegin;
1080
55
1081
211
    while (!IsExponentPart(*Ptr)) 
++Ptr156
;
1082
55
    ExponentBegin = Ptr;
1083
55
    ++Ptr;
1084
55
    NegativeExponent = *Ptr == '-';
1085
55
    if (NegativeExponent) 
++Ptr19
;
1086
55
1087
55
    unsigned NumExpDigits = SuffixBegin - Ptr;
1088
55
    if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
1089
54
      llvm::StringRef ExpStr(Ptr, NumExpDigits);
1090
54
      llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
1091
54
      Exponent = ExpInt.getZExtValue();
1092
54
    } else {
1093
1
      ExpOverflowOccurred = true;
1094
1
    }
1095
55
1096
55
    if (NegativeExponent) 
BaseShift -= Exponent19
;
1097
36
    else BaseShift += Exponent;
1098
55
  }
1099
401
1100
401
  // Number of bits needed for decimal literal is
1101
401
  //   ceil(NumDigits * log2(10))       Integral part
1102
401
  // + Scale                            Fractional part
1103
401
  // + ceil(Exponent * log2(10))        Exponent
1104
401
  // --------------------------------------------------
1105
401
  //   ceil((NumDigits + Exponent) * log2(10)) + Scale
1106
401
  //
1107
401
  // But for simplicity in handling integers, we can round up log2(10) to 4,
1108
401
  // making:
1109
401
  // 4 * (NumDigits + Exponent) + Scale
1110
401
  //
1111
401
  // Number of digits needed for hexadecimal literal is
1112
401
  //   4 * NumDigits                    Integral part
1113
401
  // + Scale                            Fractional part
1114
401
  // + Exponent                         Exponent
1115
401
  // --------------------------------------------------
1116
401
  //   (4 * NumDigits) + Scale + Exponent
1117
401
  uint64_t NumBitsNeeded;
1118
401
  if (radix == 10)
1119
365
    NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
1120
36
  else
1121
36
    NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
1122
401
1123
401
  if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
1124
0
    ExpOverflowOccurred = true;
1125
401
  llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
1126
401
1127
401
  bool FoundDecimal = false;
1128
401
1129
401
  int64_t FractBaseShift = 0;
1130
401
  const char *End = saw_exponent ? 
ExponentBegin55
:
SuffixBegin346
;
1131
2.00k
  for (const char *Ptr = DigitsBegin; Ptr < End; 
++Ptr1.60k
) {
1132
1.60k
    if (*Ptr == '.') {
1133
375
      FoundDecimal = true;
1134
375
      continue;
1135
375
    }
1136
1.23k
1137
1.23k
    // Normal reading of an integer
1138
1.23k
    unsigned C = llvm::hexDigitValue(*Ptr);
1139
1.23k
    assert(C < radix && "NumericLiteralParser ctor should have rejected this");
1140
1.23k
1141
1.23k
    Val *= radix;
1142
1.23k
    Val += C;
1143
1.23k
1144
1.23k
    if (FoundDecimal)
1145
784
      // Keep track of how much we will need to adjust this value by from the
1146
784
      // number of digits past the radix point.
1147
784
      --FractBaseShift;
1148
1.23k
  }
1149
401
1150
401
  // For a radix of 16, we will be multiplying by 2 instead of 16.
1151
401
  if (radix == 16) 
FractBaseShift *= 436
;
1152
401
  BaseShift += FractBaseShift;
1153
401
1154
401
  Val <<= Scale;
1155
401
1156
401
  uint64_t Base = (radix == 16) ? 
236
:
10365
;
1157
401
  if (BaseShift > 0) {
1158
132
    for (int64_t i = 0; i < BaseShift; 
++i124
) {
1159
124
      Val *= Base;
1160
124
    }
1161
393
  } else if (BaseShift < 0) {
1162
1.45k
    for (int64_t i = BaseShift; i < 0 && 
!Val.isNullValue()1.09k
;
++i1.07k
)
1163
1.07k
      Val = Val.udiv(Base);
1164
378
  }
1165
401
1166
401
  bool IntOverflowOccurred = false;
1167
401
  auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
1168
401
  if (Val.getBitWidth() > StoreVal.getBitWidth()) {
1169
185
    IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
1170
185
    StoreVal = Val.trunc(StoreVal.getBitWidth());
1171
216
  } else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
1172
199
    IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
1173
199
    StoreVal = Val.zext(StoreVal.getBitWidth());
1174
199
  } else {
1175
17
    StoreVal = Val;
1176
17
  }
1177
401
1178
401
  return IntOverflowOccurred || 
ExpOverflowOccurred374
;
1179
401
}
1180
1181
/// \verbatim
1182
///       user-defined-character-literal: [C++11 lex.ext]
1183
///         character-literal ud-suffix
1184
///       ud-suffix:
1185
///         identifier
1186
///       character-literal: [C++11 lex.ccon]
1187
///         ' c-char-sequence '
1188
///         u' c-char-sequence '
1189
///         U' c-char-sequence '
1190
///         L' c-char-sequence '
1191
///         u8' c-char-sequence ' [C++1z lex.ccon]
1192
///       c-char-sequence:
1193
///         c-char
1194
///         c-char-sequence c-char
1195
///       c-char:
1196
///         any member of the source character set except the single-quote ',
1197
///           backslash \, or new-line character
1198
///         escape-sequence
1199
///         universal-character-name
1200
///       escape-sequence:
1201
///         simple-escape-sequence
1202
///         octal-escape-sequence
1203
///         hexadecimal-escape-sequence
1204
///       simple-escape-sequence:
1205
///         one of \' \" \? \\ \a \b \f \n \r \t \v
1206
///       octal-escape-sequence:
1207
///         \ octal-digit
1208
///         \ octal-digit octal-digit
1209
///         \ octal-digit octal-digit octal-digit
1210
///       hexadecimal-escape-sequence:
1211
///         \x hexadecimal-digit
1212
///         hexadecimal-escape-sequence hexadecimal-digit
1213
///       universal-character-name: [C++11 lex.charset]
1214
///         \u hex-quad
1215
///         \U hex-quad hex-quad
1216
///       hex-quad:
1217
///         hex-digit hex-digit hex-digit hex-digit
1218
/// \endverbatim
1219
///
1220
CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
1221
                                     SourceLocation Loc, Preprocessor &PP,
1222
708k
                                     tok::TokenKind kind) {
1223
708k
  // At this point we know that the character matches the regex "(L|u|U)?'.*'".
1224
708k
  HadError = false;
1225
708k
1226
708k
  Kind = kind;
1227
708k
1228
708k
  const char *TokBegin = begin;
1229
708k
1230
708k
  // Skip over wide character determinant.
1231
708k
  if (Kind != tok::char_constant)
1232
1.22k
    ++begin;
1233
708k
  if (Kind == tok::utf8_char_constant)
1234
27
    ++begin;
1235
708k
1236
708k
  // Skip over the entry quote.
1237
708k
  assert(begin[0] == '\'' && "Invalid token lexed");
1238
708k
  ++begin;
1239
708k
1240
708k
  // Remove an optional ud-suffix.
1241
708k
  if (end[-1] != '\'') {
1242
44
    const char *UDSuffixEnd = end;
1243
172
    do {
1244
172
      --end;
1245
172
    } while (end[-1] != '\'');
1246
44
    // FIXME: Don't bother with this if !tok.hasUCN().
1247
44
    expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
1248
44
    UDSuffixOffset = end - TokBegin;
1249
44
  }
1250
708k
1251
708k
  // Trim the ending quote.
1252
708k
  assert(end != begin && "Invalid token lexed");
1253
708k
  --end;
1254
708k
1255
708k
  // FIXME: The "Value" is an uint64_t so we can handle char literals of
1256
708k
  // up to 64-bits.
1257
708k
  // FIXME: This extensively assumes that 'char' is 8-bits.
1258
708k
  assert(PP.getTargetInfo().getCharWidth() == 8 &&
1259
708k
         "Assumes char is 8 bits");
1260
708k
  assert(PP.getTargetInfo().getIntWidth() <= 64 &&
1261
708k
         (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
1262
708k
         "Assumes sizeof(int) on target is <= 64 and a multiple of char");
1263
708k
  assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
1264
708k
         "Assumes sizeof(wchar) on target is <= 64");
1265
708k
1266
708k
  SmallVector<uint32_t, 4> codepoint_buffer;
1267
708k
  codepoint_buffer.resize(end - begin);
1268
708k
  uint32_t *buffer_begin = &codepoint_buffer.front();
1269
708k
  uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
1270
708k
1271
708k
  // Unicode escapes representing characters that cannot be correctly
1272
708k
  // represented in a single code unit are disallowed in character literals
1273
708k
  // by this implementation.
1274
708k
  uint32_t largest_character_for_kind;
1275
708k
  if (tok::wide_char_constant == Kind) {
1276
1.04k
    largest_character_for_kind =
1277
1.04k
        0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
1278
707k
  } else if (tok::utf8_char_constant == Kind) {
1279
27
    largest_character_for_kind = 0x7F;
1280
707k
  } else if (tok::utf16_char_constant == Kind) {
1281
80
    largest_character_for_kind = 0xFFFF;
1282
706k
  } else if (tok::utf32_char_constant == Kind) {
1283
71
    largest_character_for_kind = 0x10FFFF;
1284
706k
  } else {
1285
706k
    largest_character_for_kind = 0x7Fu;
1286
706k
  }
1287
708k
1288
1.41M
  while (begin != end) {
1289
709k
    // Is this a span of non-escape characters?
1290
709k
    if (begin[0] != '\\') {
1291
704k
      char const *start = begin;
1292
2.73M
      do {
1293
2.73M
        ++begin;
1294
2.73M
      } while (begin != end && 
*begin != '\\'2.02M
);
1295
704k
1296
704k
      char const *tmp_in_start = start;
1297
704k
      uint32_t *tmp_out_start = buffer_begin;
1298
704k
      llvm::ConversionResult res =
1299
704k
          llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
1300
704k
                             reinterpret_cast<llvm::UTF8 const *>(begin),
1301
704k
                             &buffer_begin, buffer_end, llvm::strictConversion);
1302
704k
      if (res != llvm::conversionOK) {
1303
6
        // If we see bad encoding for unprefixed character literals, warn and
1304
6
        // simply copy the byte values, for compatibility with gcc and
1305
6
        // older versions of clang.
1306
6
        bool NoErrorOnBadEncoding = isAscii();
1307
6
        unsigned Msg = diag::err_bad_character_encoding;
1308
6
        if (NoErrorOnBadEncoding)
1309
3
          Msg = diag::warn_bad_character_encoding;
1310
6
        PP.Diag(Loc, Msg);
1311
6
        if (NoErrorOnBadEncoding) {
1312
3
          start = tmp_in_start;
1313
3
          buffer_begin = tmp_out_start;
1314
7
          for (; start != begin; 
++start, ++buffer_begin4
)
1315
4
            *buffer_begin = static_cast<uint8_t>(*start);
1316
3
        } else {
1317
3
          HadError = true;
1318
3
        }
1319
704k
      } else {
1320
3.43M
        for (; tmp_out_start < buffer_begin; 
++tmp_out_start2.73M
) {
1321
2.73M
          if (*tmp_out_start > largest_character_for_kind) {
1322
13
            HadError = true;
1323
13
            PP.Diag(Loc, diag::err_character_too_large);
1324
13
          }
1325
2.73M
        }
1326
704k
      }
1327
704k
1328
704k
      continue;
1329
704k
    }
1330
4.89k
    // Is this a Universal Character Name escape?
1331
4.89k
    if (begin[1] == 'u' || 
begin[1] == 'U'4.80k
) {
1332
107
      unsigned short UcnLen = 0;
1333
107
      if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
1334
107
                            FullSourceLoc(Loc, PP.getSourceManager()),
1335
107
                            &PP.getDiagnostics(), PP.getLangOpts(), true)) {
1336
29
        HadError = true;
1337
78
      } else if (*buffer_begin > largest_character_for_kind) {
1338
8
        HadError = true;
1339
8
        PP.Diag(Loc, diag::err_character_too_large);
1340
8
      }
1341
107
1342
107
      ++buffer_begin;
1343
107
      continue;
1344
107
    }
1345
4.79k
    unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
1346
4.79k
    uint64_t result =
1347
4.79k
      ProcessCharEscape(TokBegin, begin, end, HadError,
1348
4.79k
                        FullSourceLoc(Loc,PP.getSourceManager()),
1349
4.79k
                        CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
1350
4.79k
    *buffer_begin++ = result;
1351
4.79k
  }
1352
708k
1353
708k
  unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
1354
708k
1355
708k
  if (NumCharsSoFar > 1) {
1356
676k
    if (isWide())
1357
17
      PP.Diag(Loc, diag::warn_extraneous_char_constant);
1358
676k
    else if (isAscii() && 
NumCharsSoFar == 4676k
)
1359
676k
      PP.Diag(Loc, diag::ext_four_char_character_literal);
1360
31
    else if (isAscii())
1361
26
      PP.Diag(Loc, diag::ext_multichar_character_literal);
1362
5
    else
1363
5
      PP.Diag(Loc, diag::err_multichar_utf_character_literal);
1364
676k
    IsMultiChar = true;
1365
676k
  } else {
1366
31.8k
    IsMultiChar = false;
1367
31.8k
  }
1368
708k
1369
708k
  llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
1370
708k
1371
708k
  // Narrow character literals act as though their value is concatenated
1372
708k
  // in this implementation, but warn on overflow.
1373
708k
  bool multi_char_too_long = false;
1374
708k
  if (isAscii() && 
isMultiChar()706k
) {
1375
676k
    LitVal = 0;
1376
3.38M
    for (size_t i = 0; i < NumCharsSoFar; 
++i2.70M
) {
1377
2.70M
      // check for enough leading zeros to shift into
1378
2.70M
      multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
1379
2.70M
      LitVal <<= 8;
1380
2.70M
      LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
1381
2.70M
    }
1382
676k
  } else 
if (31.9k
NumCharsSoFar > 031.9k
) {
1383
31.9k
    // otherwise just take the last character
1384
31.9k
    LitVal = buffer_begin[-1];
1385
31.9k
  }
1386
708k
1387
708k
  if (!HadError && 
multi_char_too_long708k
) {
1388
5
    PP.Diag(Loc, diag::warn_char_constant_too_large);
1389
5
  }
1390
708k
1391
708k
  // Transfer the value from APInt to uint64_t
1392
708k
  Value = LitVal.getZExtValue();
1393
708k
1394
708k
  // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
1395
708k
  // if 'char' is signed for this target (C99 6.4.4.4p10).  Note that multiple
1396
708k
  // character constants are not sign extended in the this implementation:
1397
708k
  // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
1398
708k
  if (isAscii() && 
NumCharsSoFar == 1706k
&&
(Value & 128)30.6k
&&
1399
708k
      
PP.getLangOpts().CharIsSigned101
)
1400
79
    Value = (signed char)Value;
1401
708k
}
1402
1403
/// \verbatim
1404
///       string-literal: [C++0x lex.string]
1405
///         encoding-prefix " [s-char-sequence] "
1406
///         encoding-prefix R raw-string
1407
///       encoding-prefix:
1408
///         u8
1409
///         u
1410
///         U
1411
///         L
1412
///       s-char-sequence:
1413
///         s-char
1414
///         s-char-sequence s-char
1415
///       s-char:
1416
///         any member of the source character set except the double-quote ",
1417
///           backslash \, or new-line character
1418
///         escape-sequence
1419
///         universal-character-name
1420
///       raw-string:
1421
///         " d-char-sequence ( r-char-sequence ) d-char-sequence "
1422
///       r-char-sequence:
1423
///         r-char
1424
///         r-char-sequence r-char
1425
///       r-char:
1426
///         any member of the source character set, except a right parenthesis )
1427
///           followed by the initial d-char-sequence (which may be empty)
1428
///           followed by a double quote ".
1429
///       d-char-sequence:
1430
///         d-char
1431
///         d-char-sequence d-char
1432
///       d-char:
1433
///         any member of the basic source character set except:
1434
///           space, the left parenthesis (, the right parenthesis ),
1435
///           the backslash \, and the control characters representing horizontal
1436
///           tab, vertical tab, form feed, and newline.
1437
///       escape-sequence: [C++0x lex.ccon]
1438
///         simple-escape-sequence
1439
///         octal-escape-sequence
1440
///         hexadecimal-escape-sequence
1441
///       simple-escape-sequence:
1442
///         one of \' \" \? \\ \a \b \f \n \r \t \v
1443
///       octal-escape-sequence:
1444
///         \ octal-digit
1445
///         \ octal-digit octal-digit
1446
///         \ octal-digit octal-digit octal-digit
1447
///       hexadecimal-escape-sequence:
1448
///         \x hexadecimal-digit
1449
///         hexadecimal-escape-sequence hexadecimal-digit
1450
///       universal-character-name:
1451
///         \u hex-quad
1452
///         \U hex-quad hex-quad
1453
///       hex-quad:
1454
///         hex-digit hex-digit hex-digit hex-digit
1455
/// \endverbatim
1456
///
1457
StringLiteralParser::
1458
StringLiteralParser(ArrayRef<Token> StringToks,
1459
                    Preprocessor &PP, bool Complain)
1460
  : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
1461
    Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr),
1462
    MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
1463
3.41M
    ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
1464
3.41M
  init(StringToks);
1465
3.41M
}
1466
1467
4.82M
void StringLiteralParser::init(ArrayRef<Token> StringToks){
1468
4.82M
  // The literal token may have come from an invalid source location (e.g. due
1469
4.82M
  // to a PCH error), in which case the token length will be 0.
1470
4.82M
  if (StringToks.empty() || StringToks[0].getLength() < 2)
1471
0
    return DiagnoseLexingError(SourceLocation());
1472
4.82M
1473
4.82M
  // Scan all of the string portions, remember the max individual token length,
1474
4.82M
  // computing a bound on the concatenated string length, and see whether any
1475
4.82M
  // piece is a wide-string.  If any of the string portions is a wide-string
1476
4.82M
  // literal, the result is a wide-string literal [C99 6.4.5p4].
1477
4.82M
  assert(!StringToks.empty() && "expected at least one token");
1478
4.82M
  MaxTokenLength = StringToks[0].getLength();
1479
4.82M
  assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
1480
4.82M
  SizeBound = StringToks[0].getLength()-2;  // -2 for "".
1481
4.82M
  Kind = StringToks[0].getKind();
1482
4.82M
1483
4.82M
  hadError = false;
1484
4.82M
1485
4.82M
  // Implement Translation Phase #6: concatenation of string literals
1486
4.82M
  /// (C99 5.1.1.2p1).  The common case is only one string fragment.
1487
5.04M
  for (unsigned i = 1; i != StringToks.size(); 
++i219k
) {
1488
219k
    if (StringToks[i].getLength() < 2)
1489
0
      return DiagnoseLexingError(StringToks[i].getLocation());
1490
219k
1491
219k
    // The string could be shorter than this if it needs cleaning, but this is a
1492
219k
    // reasonable bound, which is all we need.
1493
219k
    assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
1494
219k
    SizeBound += StringToks[i].getLength()-2;  // -2 for "".
1495
219k
1496
219k
    // Remember maximum string piece length.
1497
219k
    if (StringToks[i].getLength() > MaxTokenLength)
1498
189k
      MaxTokenLength = StringToks[i].getLength();
1499
219k
1500
219k
    // Remember if we see any wide or utf-8/16/32 strings.
1501
219k
    // Also check for illegal concatenations.
1502
219k
    if (StringToks[i].isNot(Kind) && 
StringToks[i].isNot(tok::string_literal)80
) {
1503
53
      if (isAscii()) {
1504
17
        Kind = StringToks[i].getKind();
1505
36
      } else {
1506
36
        if (Diags)
1507
36
          Diags->Report(StringToks[i].getLocation(),
1508
36
                        diag::err_unsupported_string_concat);
1509
36
        hadError = true;
1510
36
      }
1511
53
    }
1512
219k
  }
1513
4.82M
1514
4.82M
  // Include space for the null terminator.
1515
4.82M
  ++SizeBound;
1516
4.82M
1517
4.82M
  // TODO: K&R warning: "traditional C rejects string constant concatenation"
1518
4.82M
1519
4.82M
  // Get the width in bytes of char/wchar_t/char16_t/char32_t
1520
4.82M
  CharByteWidth = getCharWidth(Kind, Target);
1521
4.82M
  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1522
4.82M
  CharByteWidth /= 8;
1523
4.82M
1524
4.82M
  // The output buffer size needs to be large enough to hold wide characters.
1525
4.82M
  // This is a worst-case assumption which basically corresponds to L"" "long".
1526
4.82M
  SizeBound *= CharByteWidth;
1527
4.82M
1528
4.82M
  // Size the temporary buffer to hold the result string data.
1529
4.82M
  ResultBuf.resize(SizeBound);
1530
4.82M
1531
4.82M
  // Likewise, but for each string piece.
1532
4.82M
  SmallString<512> TokenBuf;
1533
4.82M
  TokenBuf.resize(MaxTokenLength);
1534
4.82M
1535
4.82M
  // Loop over all the strings, getting their spelling, and expanding them to
1536
4.82M
  // wide strings as appropriate.
1537
4.82M
  ResultPtr = &ResultBuf[0];   // Next byte to fill in.
1538
4.82M
1539
4.82M
  Pascal = false;
1540
4.82M
1541
4.82M
  SourceLocation UDSuffixTokLoc;
1542
4.82M
1543
9.87M
  for (unsigned i = 0, e = StringToks.size(); i != e; 
++i5.04M
) {
1544
5.04M
    const char *ThisTokBuf = &TokenBuf[0];
1545
5.04M
    // Get the spelling of the token, which eliminates trigraphs, etc.  We know
1546
5.04M
    // that ThisTokBuf points to a buffer that is big enough for the whole token
1547
5.04M
    // and 'spelled' tokens can only shrink.
1548
5.04M
    bool StringInvalid = false;
1549
5.04M
    unsigned ThisTokLen =
1550
5.04M
      Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
1551
5.04M
                         &StringInvalid);
1552
5.04M
    if (StringInvalid)
1553
0
      return DiagnoseLexingError(StringToks[i].getLocation());
1554
5.04M
1555
5.04M
    const char *ThisTokBegin = ThisTokBuf;
1556
5.04M
    const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
1557
5.04M
1558
5.04M
    // Remove an optional ud-suffix.
1559
5.04M
    if (ThisTokEnd[-1] != '"') {
1560
263
      const char *UDSuffixEnd = ThisTokEnd;
1561
917
      do {
1562
917
        --ThisTokEnd;
1563
917
      } while (ThisTokEnd[-1] != '"');
1564
263
1565
263
      StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
1566
263
1567
263
      if (UDSuffixBuf.empty()) {
1568
245
        if (StringToks[i].hasUCN())
1569
8
          expandUCNs(UDSuffixBuf, UDSuffix);
1570
237
        else
1571
237
          UDSuffixBuf.assign(UDSuffix);
1572
245
        UDSuffixToken = i;
1573
245
        UDSuffixOffset = ThisTokEnd - ThisTokBuf;
1574
245
        UDSuffixTokLoc = StringToks[i].getLocation();
1575
245
      } else {
1576
18
        SmallString<32> ExpandedUDSuffix;
1577
18
        if (StringToks[i].hasUCN()) {
1578
9
          expandUCNs(ExpandedUDSuffix, UDSuffix);
1579
9
          UDSuffix = ExpandedUDSuffix;
1580
9
        }
1581
18
1582
18
        // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
1583
18
        // result of a concatenation involving at least one user-defined-string-
1584
18
        // literal, all the participating user-defined-string-literals shall
1585
18
        // have the same ud-suffix.
1586
18
        if (UDSuffixBuf != UDSuffix) {
1587
6
          if (Diags) {
1588
6
            SourceLocation TokLoc = StringToks[i].getLocation();
1589
6
            Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
1590
6
              << UDSuffixBuf << UDSuffix
1591
6
              << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
1592
6
              << SourceRange(TokLoc, TokLoc);
1593
6
          }
1594
6
          hadError = true;
1595
6
        }
1596
18
      }
1597
263
    }
1598
5.04M
1599
5.04M
    // Strip the end quote.
1600
5.04M
    --ThisTokEnd;
1601
5.04M
1602
5.04M
    // TODO: Input character set mapping support.
1603
5.04M
1604
5.04M
    // Skip marker for wide or unicode strings.
1605
5.04M
    if (ThisTokBuf[0] == 'L' || 
ThisTokBuf[0] == 'u'5.04M
||
ThisTokBuf[0] == 'U'5.04M
) {
1606
1.46k
      ++ThisTokBuf;
1607
1.46k
      // Skip 8 of u8 marker for utf8 strings.
1608
1.46k
      if (ThisTokBuf[0] == '8')
1609
120
        ++ThisTokBuf;
1610
1.46k
    }
1611
5.04M
1612
5.04M
    // Check for raw string
1613
5.04M
    if (ThisTokBuf[0] == 'R') {
1614
106
      ThisTokBuf += 2; // skip R"
1615
106
1616
106
      const char *Prefix = ThisTokBuf;
1617
241
      while (ThisTokBuf[0] != '(')
1618
135
        ++ThisTokBuf;
1619
106
      ++ThisTokBuf; // skip '('
1620
106
1621
106
      // Remove same number of characters from the end
1622
106
      ThisTokEnd -= ThisTokBuf - Prefix;
1623
106
      assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal");
1624
106
1625
106
      // C++14 [lex.string]p4: A source-file new-line in a raw string literal
1626
106
      // results in a new-line in the resulting execution string-literal.
1627
106
      StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
1628
209
      while (!RemainingTokenSpan.empty()) {
1629
103
        // Split the string literal on \r\n boundaries.
1630
103
        size_t CRLFPos = RemainingTokenSpan.find("\r\n");
1631
103
        StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
1632
103
        StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
1633
103
1634
103
        // Copy everything before the \r\n sequence into the string literal.
1635
103
        if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
1636
6
          hadError = true;
1637
103
1638
103
        // Point into the \n inside the \r\n sequence and operate on the
1639
103
        // remaining portion of the literal.
1640
103
        RemainingTokenSpan = AfterCRLF.substr(1);
1641
103
      }
1642
5.04M
    } else {
1643
5.04M
      if (ThisTokBuf[0] != '"') {
1644
0
        // The file may have come from PCH and then changed after loading the
1645
0
        // PCH; Fail gracefully.
1646
0
        return DiagnoseLexingError(StringToks[i].getLocation());
1647
0
      }
1648
5.04M
      ++ThisTokBuf; // skip "
1649
5.04M
1650
5.04M
      // Check if this is a pascal string
1651
5.04M
      if (Features.PascalStrings && 
ThisTokBuf + 1 != ThisTokEnd96
&&
1652
5.04M
          
ThisTokBuf[0] == '\\'96
&&
ThisTokBuf[1] == 'p'15
) {
1653
15
1654
15
        // If the \p sequence is found in the first token, we have a pascal string
1655
15
        // Otherwise, if we already have a pascal string, ignore the first \p
1656
15
        if (i == 0) {
1657
15
          ++ThisTokBuf;
1658
15
          Pascal = true;
1659
15
        } else 
if (0
Pascal0
)
1660
0
          ThisTokBuf += 2;
1661
15
      }
1662
5.04M
1663
10.0M
      while (ThisTokBuf != ThisTokEnd) {
1664
5.00M
        // Is this a span of non-escape characters?
1665
5.00M
        if (ThisTokBuf[0] != '\\') {
1666
4.95M
          const char *InStart = ThisTokBuf;
1667
66.3M
          do {
1668
66.3M
            ++ThisTokBuf;
1669
66.3M
          } while (ThisTokBuf != ThisTokEnd && 
ThisTokBuf[0] != '\\'61.4M
);
1670
4.95M
1671
4.95M
          // Copy the character span over.
1672
4.95M
          if (CopyStringFragment(StringToks[i], ThisTokBegin,
1673
4.95M
                                 StringRef(InStart, ThisTokBuf - InStart)))
1674
8
            hadError = true;
1675
4.95M
          continue;
1676
4.95M
        }
1677
55.8k
        // Is this a Universal Character Name escape?
1678
55.8k
        if (ThisTokBuf[1] == 'u' || 
ThisTokBuf[1] == 'U'55.6k
) {
1679
267
          EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
1680
267
                          ResultPtr, hadError,
1681
267
                          FullSourceLoc(StringToks[i].getLocation(), SM),
1682
267
                          CharByteWidth, Diags, Features);
1683
267
          continue;
1684
267
        }
1685
55.5k
        // Otherwise, this is a non-UCN escape character.  Process it.
1686
55.5k
        unsigned ResultChar =
1687
55.5k
          ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
1688
55.5k
                            FullSourceLoc(StringToks[i].getLocation(), SM),
1689
55.5k
                            CharByteWidth*8, Diags, Features);
1690
55.5k
1691
55.5k
        if (CharByteWidth == 4) {
1692
217
          // FIXME: Make the type of the result buffer correct instead of
1693
217
          // using reinterpret_cast.
1694
217
          llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
1695
217
          *ResultWidePtr = ResultChar;
1696
217
          ResultPtr += 4;
1697
55.3k
        } else if (CharByteWidth == 2) {
1698
24
          // FIXME: Make the type of the result buffer correct instead of
1699
24
          // using reinterpret_cast.
1700
24
          llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
1701
24
          *ResultWidePtr = ResultChar & 0xFFFF;
1702
24
          ResultPtr += 2;
1703
55.3k
        } else {
1704
55.3k
          assert(CharByteWidth == 1 && "Unexpected char width");
1705
55.3k
          *ResultPtr++ = ResultChar & 0xFF;
1706
55.3k
        }
1707
55.5k
      }
1708
5.04M
    }
1709
5.04M
  }
1710
4.82M
1711
4.82M
  if (Pascal) {
1712
15
    if (CharByteWidth == 4) {
1713
1
      // FIXME: Make the type of the result buffer correct instead of
1714
1
      // using reinterpret_cast.
1715
1
      llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
1716
1
      ResultWidePtr[0] = GetNumStringChars() - 1;
1717
14
    } else if (CharByteWidth == 2) {
1718
3
      // FIXME: Make the type of the result buffer correct instead of
1719
3
      // using reinterpret_cast.
1720
3
      llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
1721
3
      ResultWidePtr[0] = GetNumStringChars() - 1;
1722
11
    } else {
1723
11
      assert(CharByteWidth == 1 && "Unexpected char width");
1724
11
      ResultBuf[0] = GetNumStringChars() - 1;
1725
11
    }
1726
15
1727
15
    // Verify that pascal strings aren't too large.
1728
15
    if (GetStringLength() > 256) {
1729
0
      if (Diags)
1730
0
        Diags->Report(StringToks.front().getLocation(),
1731
0
                      diag::err_pascal_string_too_long)
1732
0
          << SourceRange(StringToks.front().getLocation(),
1733
0
                         StringToks.back().getLocation());
1734
0
      hadError = true;
1735
0
      return;
1736
0
    }
1737
4.82M
  } else if (Diags) {
1738
3.41M
    // Complain if this string literal has too many characters.
1739
3.41M
    unsigned MaxChars = Features.CPlusPlus? 
655361.85M
:
Features.C99 1.56M
?
40951.56M
:
509767
;
1740
3.41M
1741
3.41M
    if (GetNumStringChars() > MaxChars)
1742
1
      Diags->Report(StringToks.front().getLocation(),
1743
1
                    diag::ext_string_too_long)
1744
1
        << GetNumStringChars() << MaxChars
1745
1
        << (Features.CPlusPlus ? 
20
: Features.C99 ?
10
: 0)
1746
1
        << SourceRange(StringToks.front().getLocation(),
1747
1
                       StringToks.back().getLocation());
1748
3.41M
  }
1749
4.82M
}
1750
1751
212
static const char *resyncUTF8(const char *Err, const char *End) {
1752
212
  if (Err == End)
1753
0
    return End;
1754
212
  End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
1755
239
  while (++Err != End && 
(*Err & 0xC0) == 0x80186
)
1756
27
    ;
1757
212
  return Err;
1758
212
}
1759
1760
/// This function copies from Fragment, which is a sequence of bytes
1761
/// within Tok's contents (which begin at TokBegin) into ResultPtr.
1762
/// Performs widening for multi-byte characters.
1763
bool StringLiteralParser::CopyStringFragment(const Token &Tok,
1764
                                             const char *TokBegin,
1765
4.95M
                                             StringRef Fragment) {
1766
4.95M
  const llvm::UTF8 *ErrorPtrTmp;
1767
4.95M
  if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
1768
4.95M
    return false;
1769
39
1770
39
  // If we see bad encoding for unprefixed string literals, warn and
1771
39
  // simply copy the byte values, for compatibility with gcc and older
1772
39
  // versions of clang.
1773
39
  bool NoErrorOnBadEncoding = isAscii();
1774
39
  if (NoErrorOnBadEncoding) {
1775
20
    memcpy(ResultPtr, Fragment.data(), Fragment.size());
1776
20
    ResultPtr += Fragment.size();
1777
20
  }
1778
39
1779
39
  if (Diags) {
1780
34
    const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1781
34
1782
34
    FullSourceLoc SourceLoc(Tok.getLocation(), SM);
1783
34
    const DiagnosticBuilder &Builder =
1784
34
      Diag(Diags, Features, SourceLoc, TokBegin,
1785
34
           ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
1786
34
           NoErrorOnBadEncoding ? 
diag::warn_bad_string_encoding20
1787
34
                                : 
diag::err_bad_string_encoding14
);
1788
34
1789
34
    const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1790
34
    StringRef NextFragment(NextStart, Fragment.end()-NextStart);
1791
34
1792
34
    // Decode into a dummy buffer.
1793
34
    SmallString<512> Dummy;
1794
34
    Dummy.reserve(Fragment.size() * CharByteWidth);
1795
34
    char *Ptr = Dummy.data();
1796
34
1797
178
    while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
1798
144
      const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
1799
144
      NextStart = resyncUTF8(ErrorPtr, Fragment.end());
1800
144
      Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
1801
144
                                     ErrorPtr, NextStart);
1802
144
      NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
1803
144
    }
1804
34
  }
1805
39
  return !NoErrorOnBadEncoding;
1806
39
}
1807
1808
0
void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
1809
0
  hadError = true;
1810
0
  if (Diags)
1811
0
    Diags->Report(Loc, diag::err_lexing_string);
1812
0
}
1813
1814
/// getOffsetOfStringByte - This function returns the offset of the
1815
/// specified byte of the string data represented by Token.  This handles
1816
/// advancing over escape sequences in the string.
1817
unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
1818
25.0k
                                                    unsigned ByteNo) const {
1819
25.0k
  // Get the spelling of the token.
1820
25.0k
  SmallString<32> SpellingBuffer;
1821
25.0k
  SpellingBuffer.resize(Tok.getLength());
1822
25.0k
1823
25.0k
  bool StringInvalid = false;
1824
25.0k
  const char *SpellingPtr = &SpellingBuffer[0];
1825
25.0k
  unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
1826
25.0k
                                       &StringInvalid);
1827
25.0k
  if (StringInvalid)
1828
0
    return 0;
1829
25.0k
1830
25.0k
  const char *SpellingStart = SpellingPtr;
1831
25.0k
  const char *SpellingEnd = SpellingPtr+TokLen;
1832
25.0k
1833
25.0k
  // Handle UTF-8 strings just like narrow strings.
1834
25.0k
  if (SpellingPtr[0] == 'u' && 
SpellingPtr[1] == '8'3
)
1835
3
    SpellingPtr += 2;
1836
25.0k
1837
25.0k
  assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
1838
25.0k
         SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
1839
25.0k
1840
25.0k
  // For raw string literals, this is easy.
1841
25.0k
  if (SpellingPtr[0] == 'R') {
1842
6
    assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
1843
6
    // Skip 'R"'.
1844
6
    SpellingPtr += 2;
1845
35
    while (*SpellingPtr != '(') {
1846
29
      ++SpellingPtr;
1847
29
      assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
1848
29
    }
1849
6
    // Skip '('.
1850
6
    ++SpellingPtr;
1851
6
    return SpellingPtr - SpellingStart + ByteNo;
1852
6
  }
1853
25.0k
1854
25.0k
  // Skip over the leading quote
1855
25.0k
  assert(SpellingPtr[0] == '"' && "Should be a string literal!");
1856
25.0k
  ++SpellingPtr;
1857
25.0k
1858
25.0k
  // Skip over bytes until we find the offset we're looking for.
1859
384k
  while (ByteNo) {
1860
359k
    assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
1861
359k
1862
359k
    // Step over non-escapes simply.
1863
359k
    if (*SpellingPtr != '\\') {
1864
358k
      ++SpellingPtr;
1865
358k
      --ByteNo;
1866
358k
      continue;
1867
358k
    }
1868
516
1869
516
    // Otherwise, this is an escape character.  Advance over it.
1870
516
    bool HadError = false;
1871
516
    if (SpellingPtr[1] == 'u' || 
SpellingPtr[1] == 'U'513
) {
1872
6
      const char *EscapePtr = SpellingPtr;
1873
6
      unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
1874
6
                                      1, Features, HadError);
1875
6
      if (Len > ByteNo) {
1876
6
        // ByteNo is somewhere within the escape sequence.
1877
6
        SpellingPtr = EscapePtr;
1878
6
        break;
1879
6
      }
1880
0
      ByteNo -= Len;
1881
510
    } else {
1882
510
      ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
1883
510
                        FullSourceLoc(Tok.getLocation(), SM),
1884
510
                        CharByteWidth*8, Diags, Features);
1885
510
      --ByteNo;
1886
510
    }
1887
516
    assert(!HadError && "This method isn't valid on erroneous strings");
1888
510
  }
1889
25.0k
1890
25.0k
  return SpellingPtr-SpellingStart;
1891
25.0k
}
1892
1893
/// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
1894
/// suffixes as ud-suffixes, because the diagnostic experience is better if we
1895
/// treat it as an invalid suffix.
1896
bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
1897
296
                                          StringRef Suffix) {
1898
296
  return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||
1899
296
         
Suffix == "sv"48
;
1900
296
}