LLVM 20.0.0git
TGLexer.cpp
Go to the documentation of this file.
1//===- TGLexer.cpp - Lexer for TableGen -----------------------------------===//
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// Implement the Lexer for TableGen.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TGLexer.h"
14#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/Config/config.h" // for strtoull()/strtoll() define
22#include "llvm/TableGen/Error.h"
23#include <algorithm>
24#include <cerrno>
25#include <cstdint>
26#include <cstdio>
27#include <cstdlib>
28#include <cstring>
29
30using namespace llvm;
31
32namespace {
33// A list of supported preprocessing directives with their
34// internal token kinds and names.
35struct PreprocessorDir {
38};
39} // end anonymous namespace
40
41/// Returns true if `C` is a valid character in an identifier. If `First` is
42/// true, returns true if `C` is a valid first character of an identifier,
43/// else returns true if `C` is a valid non-first character of an identifier.
44/// Identifiers match the following regular expression:
45/// [a-zA-Z_][0-9a-zA-Z_]*
46static bool isValidIDChar(char C, bool First) {
47 if (C == '_' || isAlpha(C))
48 return true;
49 return !First && isDigit(C);
50}
51
52constexpr PreprocessorDir PreprocessorDirs[] = {{tgtok::Ifdef, "ifdef"},
53 {tgtok::Ifndef, "ifndef"},
54 {tgtok::Else, "else"},
55 {tgtok::Endif, "endif"},
56 {tgtok::Define, "define"}};
57
58// Returns a pointer past the end of a valid macro name at the start of `Str`.
59// Valid macro names match the regular expression [a-zA-Z_][0-9a-zA-Z_]*.
60static const char *lexMacroName(StringRef Str) {
61 assert(!Str.empty());
62
63 // Macro names start with [a-zA-Z_].
64 const char *Next = Str.begin();
65 if (!isValidIDChar(*Next, /*First=*/true))
66 return Next;
67 // Eat the first character of the name.
68 ++Next;
69
70 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
71 const char *End = Str.end();
72 while (Next != End && isValidIDChar(*Next, /*First=*/false))
73 ++Next;
74 return Next;
75}
76
78 CurBuffer = SrcMgr.getMainFileID();
79 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
80 CurPtr = CurBuf.begin();
81 TokStart = nullptr;
82
83 // Pretend that we enter the "top-level" include file.
84 PrepIncludeStack.push_back(
85 std::make_unique<std::vector<PreprocessorControlDesc>>());
86
87 // Add all macros defined on the command line to the DefinedMacros set.
88 // Check invalid macro names and print fatal error if we find one.
89 for (StringRef MacroName : Macros) {
90 const char *End = lexMacroName(MacroName);
91 if (End != MacroName.end())
92 PrintFatalError("Invalid macro name `" + MacroName +
93 "` specified on command line");
94
95 DefinedMacros.insert(MacroName);
96 }
97}
98
100 return SMLoc::getFromPointer(TokStart);
101}
102
104 return {getLoc(), SMLoc::getFromPointer(CurPtr)};
105}
106
107/// ReturnError - Set the error to the specified string at the specified
108/// location. This is defined to always return tgtok::Error.
109tgtok::TokKind TGLexer::ReturnError(SMLoc Loc, const Twine &Msg) {
110 PrintError(Loc, Msg);
111 return tgtok::Error;
112}
113
114tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
115 return ReturnError(SMLoc::getFromPointer(Loc), Msg);
116}
117
118bool TGLexer::processEOF() {
119 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
120 if (ParentIncludeLoc != SMLoc()) {
121 // If prepExitInclude() detects a problem with the preprocessing
122 // control stack, it will return false. Pretend that we reached
123 // the final EOF and stop lexing more tokens by returning false
124 // to LexToken().
125 if (!prepExitInclude(false))
126 return false;
127
128 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
129 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
130 CurPtr = ParentIncludeLoc.getPointer();
131 // Make sure TokStart points into the parent file's buffer.
132 // LexToken() assigns to it before calling getNextChar(),
133 // so it is pointing into the included file now.
134 TokStart = CurPtr;
135 return true;
136 }
137
138 // Pretend that we exit the "top-level" include file.
139 // Note that in case of an error (e.g. control stack imbalance)
140 // the routine will issue a fatal error.
141 prepExitInclude(true);
142 return false;
143}
144
145int TGLexer::getNextChar() {
146 char CurChar = *CurPtr++;
147 switch (CurChar) {
148 default:
149 return (unsigned char)CurChar;
150
151 case 0: {
152 // A NUL character in the stream is either the end of the current buffer or
153 // a spurious NUL in the file. Disambiguate that here.
154 if (CurPtr - 1 == CurBuf.end()) {
155 --CurPtr; // Arrange for another call to return EOF again.
156 return EOF;
157 }
159 "NUL character is invalid in source; treated as space");
160 return ' ';
161 }
162
163 case '\n':
164 case '\r':
165 // Handle the newline character by ignoring it and incrementing the line
166 // count. However, be careful about 'dos style' files with \n\r in them.
167 // Only treat a \n\r or \r\n as a single line.
168 if ((*CurPtr == '\n' || (*CurPtr == '\r')) &&
169 *CurPtr != CurChar)
170 ++CurPtr; // Eat the two char newline sequence.
171 return '\n';
172 }
173}
174
175int TGLexer::peekNextChar(int Index) const {
176 return *(CurPtr + Index);
177}
178
179tgtok::TokKind TGLexer::LexToken(bool FileOrLineStart) {
180 TokStart = CurPtr;
181 // This always consumes at least one character.
182 int CurChar = getNextChar();
183
184 switch (CurChar) {
185 default:
186 // Handle letters: [a-zA-Z_]
187 if (isValidIDChar(CurChar, /*First=*/true))
188 return LexIdentifier();
189
190 // Unknown character, emit an error.
191 return ReturnError(TokStart, "Unexpected character");
192 case EOF:
193 // Lex next token, if we just left an include file.
194 // Note that leaving an include file means that the next
195 // symbol is located at the end of the 'include "..."'
196 // construct, so LexToken() is called with default
197 // false parameter.
198 if (processEOF())
199 return LexToken();
200
201 // Return EOF denoting the end of lexing.
202 return tgtok::Eof;
203
204 case ':': return tgtok::colon;
205 case ';': return tgtok::semi;
206 case ',': return tgtok::comma;
207 case '<': return tgtok::less;
208 case '>': return tgtok::greater;
209 case ']': return tgtok::r_square;
210 case '{': return tgtok::l_brace;
211 case '}': return tgtok::r_brace;
212 case '(': return tgtok::l_paren;
213 case ')': return tgtok::r_paren;
214 case '=': return tgtok::equal;
215 case '?': return tgtok::question;
216 case '#':
217 if (FileOrLineStart) {
218 tgtok::TokKind Kind = prepIsDirective();
219 if (Kind != tgtok::Error)
220 return lexPreprocessor(Kind);
221 }
222
223 return tgtok::paste;
224
225 // The period is a separate case so we can recognize the "..."
226 // range punctuator.
227 case '.':
228 if (peekNextChar(0) == '.') {
229 ++CurPtr; // Eat second dot.
230 if (peekNextChar(0) == '.') {
231 ++CurPtr; // Eat third dot.
232 return tgtok::dotdotdot;
233 }
234 return ReturnError(TokStart, "Invalid '..' punctuation");
235 }
236 return tgtok::dot;
237
238 case '\r':
239 PrintFatalError("getNextChar() must never return '\r'");
240 return tgtok::Error;
241
242 case ' ':
243 case '\t':
244 // Ignore whitespace.
245 return LexToken(FileOrLineStart);
246 case '\n':
247 // Ignore whitespace, and identify the new line.
248 return LexToken(true);
249 case '/':
250 // If this is the start of a // comment, skip until the end of the line or
251 // the end of the buffer.
252 if (*CurPtr == '/')
253 SkipBCPLComment();
254 else if (*CurPtr == '*') {
255 if (SkipCComment())
256 return tgtok::Error;
257 } else // Otherwise, this is an error.
258 return ReturnError(TokStart, "Unexpected character");
259 return LexToken(FileOrLineStart);
260 case '-': case '+':
261 case '0': case '1': case '2': case '3': case '4': case '5': case '6':
262 case '7': case '8': case '9': {
263 int NextChar = 0;
264 if (isDigit(CurChar)) {
265 // Allow identifiers to start with a number if it is followed by
266 // an identifier. This can happen with paste operations like
267 // foo#8i.
268 int i = 0;
269 do {
270 NextChar = peekNextChar(i++);
271 } while (isDigit(NextChar));
272
273 if (NextChar == 'x' || NextChar == 'b') {
274 // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
275 // likely a number.
276 int NextNextChar = peekNextChar(i);
277 switch (NextNextChar) {
278 default:
279 break;
280 case '0': case '1':
281 if (NextChar == 'b')
282 return LexNumber();
283 [[fallthrough]];
284 case '2': case '3': case '4': case '5':
285 case '6': case '7': case '8': case '9':
286 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
287 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
288 if (NextChar == 'x')
289 return LexNumber();
290 break;
291 }
292 }
293 }
294
295 if (isValidIDChar(NextChar, /*First=*/true))
296 return LexIdentifier();
297
298 return LexNumber();
299 }
300 case '"': return LexString();
301 case '$': return LexVarName();
302 case '[': return LexBracket();
303 case '!': return LexExclaim();
304 }
305}
306
307/// LexString - Lex "[^"]*"
308tgtok::TokKind TGLexer::LexString() {
309 const char *StrStart = CurPtr;
310
311 CurStrVal = "";
312
313 while (*CurPtr != '"') {
314 // If we hit the end of the buffer, report an error.
315 if (*CurPtr == 0 && CurPtr == CurBuf.end())
316 return ReturnError(StrStart, "End of file in string literal");
317
318 if (*CurPtr == '\n' || *CurPtr == '\r')
319 return ReturnError(StrStart, "End of line in string literal");
320
321 if (*CurPtr != '\\') {
322 CurStrVal += *CurPtr++;
323 continue;
324 }
325
326 ++CurPtr;
327
328 switch (*CurPtr) {
329 case '\\': case '\'': case '"':
330 // These turn into their literal character.
331 CurStrVal += *CurPtr++;
332 break;
333 case 't':
334 CurStrVal += '\t';
335 ++CurPtr;
336 break;
337 case 'n':
338 CurStrVal += '\n';
339 ++CurPtr;
340 break;
341
342 case '\n':
343 case '\r':
344 return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
345
346 // If we hit the end of the buffer, report an error.
347 case '\0':
348 if (CurPtr == CurBuf.end())
349 return ReturnError(StrStart, "End of file in string literal");
350 [[fallthrough]];
351 default:
352 return ReturnError(CurPtr, "invalid escape in string literal");
353 }
354 }
355
356 ++CurPtr;
357 return tgtok::StrVal;
358}
359
360tgtok::TokKind TGLexer::LexVarName() {
361 if (!isValidIDChar(CurPtr[0], /*First=*/true))
362 return ReturnError(TokStart, "Invalid variable name");
363
364 // Otherwise, we're ok, consume the rest of the characters.
365 const char *VarNameStart = CurPtr++;
366
367 while (isValidIDChar(*CurPtr, /*First=*/false))
368 ++CurPtr;
369
370 CurStrVal.assign(VarNameStart, CurPtr);
371 return tgtok::VarName;
372}
373
374tgtok::TokKind TGLexer::LexIdentifier() {
375 // The first letter is [a-zA-Z_].
376 const char *IdentStart = TokStart;
377
378 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
379 while (isValidIDChar(*CurPtr, /*First=*/false))
380 ++CurPtr;
381
382 // Check to see if this identifier is a reserved keyword.
383 StringRef Str(IdentStart, CurPtr-IdentStart);
384
386 .Case("int", tgtok::Int)
387 .Case("bit", tgtok::Bit)
388 .Case("bits", tgtok::Bits)
389 .Case("string", tgtok::String)
390 .Case("list", tgtok::List)
391 .Case("code", tgtok::Code)
392 .Case("dag", tgtok::Dag)
393 .Case("class", tgtok::Class)
394 .Case("def", tgtok::Def)
395 .Case("true", tgtok::TrueVal)
396 .Case("false", tgtok::FalseVal)
397 .Case("foreach", tgtok::Foreach)
398 .Case("defm", tgtok::Defm)
399 .Case("defset", tgtok::Defset)
400 .Case("deftype", tgtok::Deftype)
401 .Case("multiclass", tgtok::MultiClass)
402 .Case("field", tgtok::Field)
403 .Case("let", tgtok::Let)
404 .Case("in", tgtok::In)
405 .Case("defvar", tgtok::Defvar)
406 .Case("include", tgtok::Include)
407 .Case("if", tgtok::If)
408 .Case("then", tgtok::Then)
409 .Case("else", tgtok::ElseKW)
410 .Case("assert", tgtok::Assert)
411 .Case("dump", tgtok::Dump)
413
414 // A couple of tokens require special processing.
415 switch (Kind) {
416 case tgtok::Include:
417 if (LexInclude()) return tgtok::Error;
418 return Lex();
419 case tgtok::Id:
420 CurStrVal.assign(Str.begin(), Str.end());
421 break;
422 default:
423 break;
424 }
425
426 return Kind;
427}
428
429/// LexInclude - We just read the "include" token. Get the string token that
430/// comes next and enter the include.
431bool TGLexer::LexInclude() {
432 // The token after the include must be a string.
433 tgtok::TokKind Tok = LexToken();
434 if (Tok == tgtok::Error) return true;
435 if (Tok != tgtok::StrVal) {
436 PrintError(getLoc(), "Expected filename after include");
437 return true;
438 }
439
440 // Get the string.
441 std::string Filename = CurStrVal;
442 std::string IncludedFile;
443
444 CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
445 IncludedFile);
446 if (!CurBuffer) {
447 PrintError(getLoc(), "Could not find include file '" + Filename + "'");
448 return true;
449 }
450
451 Dependencies.insert(IncludedFile);
452 // Save the line number and lex buffer of the includer.
453 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
454 CurPtr = CurBuf.begin();
455
456 PrepIncludeStack.push_back(
457 std::make_unique<std::vector<PreprocessorControlDesc>>());
458 return false;
459}
460
461/// SkipBCPLComment - Skip over the comment by finding the next CR or LF.
462/// Or we may end up at the end of the buffer.
463void TGLexer::SkipBCPLComment() {
464 ++CurPtr; // skip the second slash.
465 auto EOLPos = CurBuf.find_first_of("\r\n", CurPtr - CurBuf.data());
466 CurPtr = (EOLPos == StringRef::npos) ? CurBuf.end() : CurBuf.data() + EOLPos;
467}
468
469/// SkipCComment - This skips C-style /**/ comments. The only difference from C
470/// is that we allow nesting.
471bool TGLexer::SkipCComment() {
472 ++CurPtr; // skip the star.
473 unsigned CommentDepth = 1;
474
475 while (true) {
476 int CurChar = getNextChar();
477 switch (CurChar) {
478 case EOF:
479 PrintError(TokStart, "Unterminated comment!");
480 return true;
481 case '*':
482 // End of the comment?
483 if (CurPtr[0] != '/') break;
484
485 ++CurPtr; // End the */.
486 if (--CommentDepth == 0)
487 return false;
488 break;
489 case '/':
490 // Start of a nested comment?
491 if (CurPtr[0] != '*') break;
492 ++CurPtr;
493 ++CommentDepth;
494 break;
495 }
496 }
497}
498
499/// LexNumber - Lex:
500/// [-+]?[0-9]+
501/// 0x[0-9a-fA-F]+
502/// 0b[01]+
503tgtok::TokKind TGLexer::LexNumber() {
504 unsigned Base = 0;
505 const char *NumStart;
506
507 // Check if it's a hex or a binary value.
508 if (CurPtr[-1] == '0') {
509 NumStart = CurPtr + 1;
510 if (CurPtr[0] == 'x') {
511 Base = 16;
512 do
513 ++CurPtr;
514 while (isHexDigit(CurPtr[0]));
515 } else if (CurPtr[0] == 'b') {
516 Base = 2;
517 do
518 ++CurPtr;
519 while (CurPtr[0] == '0' || CurPtr[0] == '1');
520 }
521 }
522
523 // For a hex or binary value, we always convert it to an unsigned value.
524 bool IsMinus = false;
525
526 // Check if it's a decimal value.
527 if (Base == 0) {
528 // Check for a sign without a digit.
529 if (!isDigit(CurPtr[0])) {
530 if (CurPtr[-1] == '-')
531 return tgtok::minus;
532 else if (CurPtr[-1] == '+')
533 return tgtok::plus;
534 }
535
536 Base = 10;
537 NumStart = TokStart;
538 IsMinus = CurPtr[-1] == '-';
539
540 while (isDigit(CurPtr[0]))
541 ++CurPtr;
542 }
543
544 // Requires at least one digit.
545 if (CurPtr == NumStart)
546 return ReturnError(TokStart, "Invalid number");
547
548 errno = 0;
549 if (IsMinus)
550 CurIntVal = strtoll(NumStart, nullptr, Base);
551 else
552 CurIntVal = strtoull(NumStart, nullptr, Base);
553
554 if (errno == EINVAL)
555 return ReturnError(TokStart, "Invalid number");
556 if (errno == ERANGE)
557 return ReturnError(TokStart, "Number out of range");
558
559 return Base == 2 ? tgtok::BinaryIntVal : tgtok::IntVal;
560}
561
562/// LexBracket - We just read '['. If this is a code block, return it,
563/// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
564tgtok::TokKind TGLexer::LexBracket() {
565 if (CurPtr[0] != '{')
566 return tgtok::l_square;
567 ++CurPtr;
568 const char *CodeStart = CurPtr;
569 while (true) {
570 int Char = getNextChar();
571 if (Char == EOF) break;
572
573 if (Char != '}') continue;
574
575 Char = getNextChar();
576 if (Char == EOF) break;
577 if (Char == ']') {
578 CurStrVal.assign(CodeStart, CurPtr-2);
579 return tgtok::CodeFragment;
580 }
581 }
582
583 return ReturnError(CodeStart - 2, "Unterminated code block");
584}
585
586/// LexExclaim - Lex '!' and '![a-zA-Z]+'.
587tgtok::TokKind TGLexer::LexExclaim() {
588 if (!isAlpha(*CurPtr))
589 return ReturnError(CurPtr - 1, "Invalid \"!operator\"");
590
591 const char *Start = CurPtr++;
592 while (isAlpha(*CurPtr))
593 ++CurPtr;
594
595 // Check to see which operator this is.
597 StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
598 .Case("eq", tgtok::XEq)
599 .Case("ne", tgtok::XNe)
600 .Case("le", tgtok::XLe)
601 .Case("lt", tgtok::XLt)
602 .Case("ge", tgtok::XGe)
603 .Case("gt", tgtok::XGt)
604 .Case("if", tgtok::XIf)
605 .Case("cond", tgtok::XCond)
606 .Case("isa", tgtok::XIsA)
607 .Case("head", tgtok::XHead)
608 .Case("tail", tgtok::XTail)
609 .Case("size", tgtok::XSize)
610 .Case("con", tgtok::XConcat)
611 .Case("dag", tgtok::XDag)
612 .Case("add", tgtok::XADD)
613 .Case("sub", tgtok::XSUB)
614 .Case("mul", tgtok::XMUL)
615 .Case("div", tgtok::XDIV)
616 .Case("not", tgtok::XNOT)
617 .Case("logtwo", tgtok::XLOG2)
618 .Case("and", tgtok::XAND)
619 .Case("or", tgtok::XOR)
620 .Case("xor", tgtok::XXOR)
621 .Case("shl", tgtok::XSHL)
622 .Case("sra", tgtok::XSRA)
623 .Case("srl", tgtok::XSRL)
624 .Case("cast", tgtok::XCast)
625 .Case("empty", tgtok::XEmpty)
626 .Case("subst", tgtok::XSubst)
627 .Case("foldl", tgtok::XFoldl)
628 .Case("foreach", tgtok::XForEach)
629 .Case("filter", tgtok::XFilter)
630 .Case("listconcat", tgtok::XListConcat)
631 .Case("listsplat", tgtok::XListSplat)
632 .Case("listremove", tgtok::XListRemove)
633 .Case("range", tgtok::XRange)
634 .Case("strconcat", tgtok::XStrConcat)
635 .Case("interleave", tgtok::XInterleave)
636 .Case("substr", tgtok::XSubstr)
637 .Case("find", tgtok::XFind)
638 .Cases("setdagop", "setop", tgtok::XSetDagOp) // !setop is deprecated.
639 .Cases("getdagop", "getop", tgtok::XGetDagOp) // !getop is deprecated.
640 .Case("getdagarg", tgtok::XGetDagArg)
641 .Case("getdagname", tgtok::XGetDagName)
642 .Case("setdagarg", tgtok::XSetDagArg)
643 .Case("setdagname", tgtok::XSetDagName)
644 .Case("exists", tgtok::XExists)
645 .Case("tolower", tgtok::XToLower)
646 .Case("toupper", tgtok::XToUpper)
647 .Case("repr", tgtok::XRepr)
649
650 return Kind != tgtok::Error ? Kind : ReturnError(Start-1, "Unknown operator");
651}
652
653bool TGLexer::prepExitInclude(bool IncludeStackMustBeEmpty) {
654 // Report an error, if preprocessor control stack for the current
655 // file is not empty.
656 if (!PrepIncludeStack.back()->empty()) {
657 prepReportPreprocessorStackError();
658
659 return false;
660 }
661
662 // Pop the preprocessing controls from the include stack.
663 if (PrepIncludeStack.empty()) {
664 PrintFatalError("Preprocessor include stack is empty");
665 }
666
667 PrepIncludeStack.pop_back();
668
669 if (IncludeStackMustBeEmpty) {
670 if (!PrepIncludeStack.empty())
671 PrintFatalError("Preprocessor include stack is not empty");
672 } else {
673 if (PrepIncludeStack.empty())
674 PrintFatalError("Preprocessor include stack is empty");
675 }
676
677 return true;
678}
679
680tgtok::TokKind TGLexer::prepIsDirective() const {
681 for (const auto [Kind, Word] : PreprocessorDirs) {
682 if (StringRef(CurPtr, Word.size()) != Word)
683 continue;
684 int NextChar = peekNextChar(Word.size());
685
686 // Check for whitespace after the directive. If there is no whitespace,
687 // then we do not recognize it as a preprocessing directive.
688
689 // New line and EOF may follow only #else/#endif. It will be reported
690 // as an error for #ifdef/#define after the call to prepLexMacroName().
691 if (NextChar == ' ' || NextChar == '\t' || NextChar == EOF ||
692 NextChar == '\n' ||
693 // It looks like TableGen does not support '\r' as the actual
694 // carriage return, e.g. getNextChar() treats a single '\r'
695 // as '\n'. So we do the same here.
696 NextChar == '\r')
697 return Kind;
698
699 // Allow comments after some directives, e.g.:
700 // #else// OR #else/**/
701 // #endif// OR #endif/**/
702 //
703 // Note that we do allow comments after #ifdef/#define here, e.g.
704 // #ifdef/**/ AND #ifdef//
705 // #define/**/ AND #define//
706 //
707 // These cases will be reported as incorrect after calling
708 // prepLexMacroName(). We could have supported C-style comments
709 // after #ifdef/#define, but this would complicate the code
710 // for little benefit.
711 if (NextChar == '/') {
712 NextChar = peekNextChar(Word.size() + 1);
713
714 if (NextChar == '*' || NextChar == '/')
715 return Kind;
716
717 // Pretend that we do not recognize the directive.
718 }
719 }
720
721 return tgtok::Error;
722}
723
724bool TGLexer::prepEatPreprocessorDirective(tgtok::TokKind Kind) {
725 TokStart = CurPtr;
726
727 for (const auto [PKind, PWord] : PreprocessorDirs)
728 if (PKind == Kind) {
729 // Advance CurPtr to the end of the preprocessing word.
730 CurPtr += PWord.size();
731 return true;
732 }
733
734 PrintFatalError("Unsupported preprocessing token in "
735 "prepEatPreprocessorDirective()");
736 return false;
737}
738
739tgtok::TokKind TGLexer::lexPreprocessor(tgtok::TokKind Kind,
740 bool ReturnNextLiveToken) {
741 // We must be looking at a preprocessing directive. Eat it!
742 if (!prepEatPreprocessorDirective(Kind))
743 PrintFatalError("lexPreprocessor() called for unknown "
744 "preprocessor directive");
745
746 if (Kind == tgtok::Ifdef || Kind == tgtok::Ifndef) {
747 StringRef MacroName = prepLexMacroName();
748 StringRef IfTokName = Kind == tgtok::Ifdef ? "#ifdef" : "#ifndef";
749 if (MacroName.empty())
750 return ReturnError(TokStart, "Expected macro name after " + IfTokName);
751
752 bool MacroIsDefined = DefinedMacros.count(MacroName) != 0;
753
754 // Canonicalize ifndef's MacroIsDefined to its ifdef equivalent.
755 if (Kind == tgtok::Ifndef)
756 MacroIsDefined = !MacroIsDefined;
757
758 // Regardless of whether we are processing tokens or not,
759 // we put the #ifdef control on stack.
760 // Note that MacroIsDefined has been canonicalized against ifdef.
761 PrepIncludeStack.back()->push_back(
762 {tgtok::Ifdef, MacroIsDefined, SMLoc::getFromPointer(TokStart)});
763
764 if (!prepSkipDirectiveEnd())
765 return ReturnError(CurPtr, "Only comments are supported after " +
766 IfTokName + " NAME");
767
768 // If we were not processing tokens before this #ifdef,
769 // then just return back to the lines skipping code.
770 if (!ReturnNextLiveToken)
771 return Kind;
772
773 // If we were processing tokens before this #ifdef,
774 // and the macro is defined, then just return the next token.
775 if (MacroIsDefined)
776 return LexToken();
777
778 // We were processing tokens before this #ifdef, and the macro
779 // is not defined, so we have to start skipping the lines.
780 // If the skipping is successful, it will return the token following
781 // either #else or #endif corresponding to this #ifdef.
782 if (prepSkipRegion(ReturnNextLiveToken))
783 return LexToken();
784
785 return tgtok::Error;
786 } else if (Kind == tgtok::Else) {
787 // Check if this #else is correct before calling prepSkipDirectiveEnd(),
788 // which will move CurPtr away from the beginning of #else.
789 if (PrepIncludeStack.back()->empty())
790 return ReturnError(TokStart, "#else without #ifdef or #ifndef");
791
792 PreprocessorControlDesc IfdefEntry = PrepIncludeStack.back()->back();
793
794 if (IfdefEntry.Kind != tgtok::Ifdef) {
795 PrintError(TokStart, "double #else");
796 return ReturnError(IfdefEntry.SrcPos, "Previous #else is here");
797 }
798
799 // Replace the corresponding #ifdef's control with its negation
800 // on the control stack.
801 PrepIncludeStack.back()->pop_back();
802 PrepIncludeStack.back()->push_back(
803 {Kind, !IfdefEntry.IsDefined, SMLoc::getFromPointer(TokStart)});
804
805 if (!prepSkipDirectiveEnd())
806 return ReturnError(CurPtr, "Only comments are supported after #else");
807
808 // If we were processing tokens before this #else,
809 // we have to start skipping lines until the matching #endif.
810 if (ReturnNextLiveToken) {
811 if (prepSkipRegion(ReturnNextLiveToken))
812 return LexToken();
813
814 return tgtok::Error;
815 }
816
817 // Return to the lines skipping code.
818 return Kind;
819 } else if (Kind == tgtok::Endif) {
820 // Check if this #endif is correct before calling prepSkipDirectiveEnd(),
821 // which will move CurPtr away from the beginning of #endif.
822 if (PrepIncludeStack.back()->empty())
823 return ReturnError(TokStart, "#endif without #ifdef");
824
825 auto &IfdefOrElseEntry = PrepIncludeStack.back()->back();
826
827 if (IfdefOrElseEntry.Kind != tgtok::Ifdef &&
828 IfdefOrElseEntry.Kind != tgtok::Else) {
829 PrintFatalError("Invalid preprocessor control on the stack");
830 return tgtok::Error;
831 }
832
833 if (!prepSkipDirectiveEnd())
834 return ReturnError(CurPtr, "Only comments are supported after #endif");
835
836 PrepIncludeStack.back()->pop_back();
837
838 // If we were processing tokens before this #endif, then
839 // we should continue it.
840 if (ReturnNextLiveToken) {
841 return LexToken();
842 }
843
844 // Return to the lines skipping code.
845 return Kind;
846 } else if (Kind == tgtok::Define) {
847 StringRef MacroName = prepLexMacroName();
848 if (MacroName.empty())
849 return ReturnError(TokStart, "Expected macro name after #define");
850
851 if (!DefinedMacros.insert(MacroName).second)
853 "Duplicate definition of macro: " + Twine(MacroName));
854
855 if (!prepSkipDirectiveEnd())
856 return ReturnError(CurPtr,
857 "Only comments are supported after #define NAME");
858
859 if (!ReturnNextLiveToken) {
860 PrintFatalError("#define must be ignored during the lines skipping");
861 return tgtok::Error;
862 }
863
864 return LexToken();
865 }
866
867 PrintFatalError("Preprocessing directive is not supported");
868 return tgtok::Error;
869}
870
871bool TGLexer::prepSkipRegion(bool MustNeverBeFalse) {
872 if (!MustNeverBeFalse)
873 PrintFatalError("Invalid recursion.");
874
875 do {
876 // Skip all symbols to the line end.
877 while (*CurPtr != '\n')
878 ++CurPtr;
879
880 // Find the first non-whitespace symbol in the next line(s).
881 if (!prepSkipLineBegin())
882 return false;
883
884 // If the first non-blank/comment symbol on the line is '#',
885 // it may be a start of preprocessing directive.
886 //
887 // If it is not '#' just go to the next line.
888 if (*CurPtr == '#')
889 ++CurPtr;
890 else
891 continue;
892
893 tgtok::TokKind Kind = prepIsDirective();
894
895 // If we did not find a preprocessing directive or it is #define,
896 // then just skip to the next line. We do not have to do anything
897 // for #define in the line-skipping mode.
898 if (Kind == tgtok::Error || Kind == tgtok::Define)
899 continue;
900
901 tgtok::TokKind ProcessedKind = lexPreprocessor(Kind, false);
902
903 // If lexPreprocessor() encountered an error during lexing this
904 // preprocessor idiom, then return false to the calling lexPreprocessor().
905 // This will force tgtok::Error to be returned to the tokens processing.
906 if (ProcessedKind == tgtok::Error)
907 return false;
908
909 if (Kind != ProcessedKind)
910 PrintFatalError("prepIsDirective() and lexPreprocessor() "
911 "returned different token kinds");
912
913 // If this preprocessing directive enables tokens processing,
914 // then return to the lexPreprocessor() and get to the next token.
915 // We can move from line-skipping mode to processing tokens only
916 // due to #else or #endif.
917 if (prepIsProcessingEnabled()) {
918 if (Kind != tgtok::Else && Kind != tgtok::Endif) {
919 PrintFatalError("Tokens processing was enabled by an unexpected "
920 "preprocessing directive");
921 return false;
922 }
923
924 return true;
925 }
926 } while (CurPtr != CurBuf.end());
927
928 // We have reached the end of the file, but never left the lines-skipping
929 // mode. This means there is no matching #endif.
930 prepReportPreprocessorStackError();
931 return false;
932}
933
934StringRef TGLexer::prepLexMacroName() {
935 // Skip whitespaces between the preprocessing directive and the macro name.
936 while (*CurPtr == ' ' || *CurPtr == '\t')
937 ++CurPtr;
938
939 TokStart = CurPtr;
940 CurPtr = lexMacroName(StringRef(CurPtr, CurBuf.end() - CurPtr));
941 return StringRef(TokStart, CurPtr - TokStart);
942}
943
944bool TGLexer::prepSkipLineBegin() {
945 while (CurPtr != CurBuf.end()) {
946 switch (*CurPtr) {
947 case ' ':
948 case '\t':
949 case '\n':
950 case '\r':
951 break;
952
953 case '/': {
954 int NextChar = peekNextChar(1);
955 if (NextChar == '*') {
956 // Skip C-style comment.
957 // Note that we do not care about skipping the C++-style comments.
958 // If the line contains "//", it may not contain any processable
959 // preprocessing directive. Just return CurPtr pointing to
960 // the first '/' in this case. We also do not care about
961 // incorrect symbols after the first '/' - we are in lines-skipping
962 // mode, so incorrect code is allowed to some extent.
963
964 // Set TokStart to the beginning of the comment to enable proper
965 // diagnostic printing in case of error in SkipCComment().
966 TokStart = CurPtr;
967
968 // CurPtr must point to '*' before call to SkipCComment().
969 ++CurPtr;
970 if (SkipCComment())
971 return false;
972 } else {
973 // CurPtr points to the non-whitespace '/'.
974 return true;
975 }
976
977 // We must not increment CurPtr after the comment was lexed.
978 continue;
979 }
980
981 default:
982 return true;
983 }
984
985 ++CurPtr;
986 }
987
988 // We have reached the end of the file. Return to the lines skipping
989 // code, and allow it to handle the EOF as needed.
990 return true;
991}
992
993bool TGLexer::prepSkipDirectiveEnd() {
994 while (CurPtr != CurBuf.end()) {
995 switch (*CurPtr) {
996 case ' ':
997 case '\t':
998 break;
999
1000 case '\n':
1001 case '\r':
1002 return true;
1003
1004 case '/': {
1005 int NextChar = peekNextChar(1);
1006 if (NextChar == '/') {
1007 // Skip C++-style comment.
1008 // We may just return true now, but let's skip to the line/buffer end
1009 // to simplify the method specification.
1010 ++CurPtr;
1011 SkipBCPLComment();
1012 } else if (NextChar == '*') {
1013 // When we are skipping C-style comment at the end of a preprocessing
1014 // directive, we can skip several lines. If any meaningful TD token
1015 // follows the end of the C-style comment on the same line, it will
1016 // be considered as an invalid usage of TD token.
1017 // For example, we want to forbid usages like this one:
1018 // #define MACRO class Class {}
1019 // But with C-style comments we also disallow the following:
1020 // #define MACRO /* This macro is used
1021 // to ... */ class Class {}
1022 // One can argue that this should be allowed, but it does not seem
1023 // to be worth of the complication. Moreover, this matches
1024 // the C preprocessor behavior.
1025
1026 // Set TokStart to the beginning of the comment to enable proper
1027 // diagnostic printer in case of error in SkipCComment().
1028 TokStart = CurPtr;
1029 ++CurPtr;
1030 if (SkipCComment())
1031 return false;
1032 } else {
1033 TokStart = CurPtr;
1034 PrintError(CurPtr, "Unexpected character");
1035 return false;
1036 }
1037
1038 // We must not increment CurPtr after the comment was lexed.
1039 continue;
1040 }
1041
1042 default:
1043 // Do not allow any non-whitespaces after the directive.
1044 TokStart = CurPtr;
1045 return false;
1046 }
1047
1048 ++CurPtr;
1049 }
1050
1051 return true;
1052}
1053
1054bool TGLexer::prepIsProcessingEnabled() {
1055 for (const PreprocessorControlDesc &I :
1056 llvm::reverse(*PrepIncludeStack.back()))
1057 if (!I.IsDefined)
1058 return false;
1059
1060 return true;
1061}
1062
1063void TGLexer::prepReportPreprocessorStackError() {
1064 if (PrepIncludeStack.back()->empty())
1065 PrintFatalError("prepReportPreprocessorStackError() called with "
1066 "empty control stack");
1067
1068 auto &PrepControl = PrepIncludeStack.back()->back();
1069 PrintError(CurBuf.end(), "Reached EOF without matching #endif");
1070 PrintError(PrepControl.SrcPos, "The latest preprocessor control is here");
1071
1072 TokStart = CurPtr;
1073}
bool End
Definition: ELF_riscv.cpp:480
#define I(x, y, z)
Definition: MD5.cpp:58
static bool isDigit(const char C)
static bool isHexDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some functions that are useful when dealing with strings.
This file implements the StringSwitch template, which mimics a switch() statement whose cases are str...
constexpr PreprocessorDir PreprocessorDirs[]
Definition: TGLexer.cpp:52
static bool isValidIDChar(char C, bool First)
Returns true if C is a valid character in an identifier.
Definition: TGLexer.cpp:46
static const char * lexMacroName(StringRef Str)
Definition: TGLexer.cpp:60
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
StringRef getBuffer() const
Definition: MemoryBuffer.h:70
Represents a location in source code.
Definition: SMLoc.h:23
static SMLoc getFromPointer(const char *Ptr)
Definition: SMLoc.h:36
constexpr const char * getPointer() const
Definition: SMLoc.h:34
Represents a range in source code.
Definition: SMLoc.h:48
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition: SourceMgr.h:31
unsigned getMainFileID() const
Definition: SourceMgr.h:132
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:125
SMLoc getParentIncludeLoc(unsigned i) const
Definition: SourceMgr.h:137
unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition: SourceMgr.cpp:73
unsigned AddIncludeFile(const std::string &Filename, SMLoc IncludeLoc, std::string &IncludedFile)
Search for a file with the specified name in the current directory or in one of the IncludeDirs.
Definition: SourceMgr.cpp:41
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:276
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
iterator begin() const
Definition: StringRef.h:111
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:131
size_t find_first_of(char C, size_t From=0) const
Find the first character in the string that is C, or npos if not found.
Definition: StringRef.h:362
iterator end() const
Definition: StringRef.h:113
static constexpr size_t npos
Definition: StringRef.h:52
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:38
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:44
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:69
R Default(T Value)
Definition: StringSwitch.h:182
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:90
SMRange getLocRange() const
Definition: TGLexer.cpp:103
tgtok::TokKind Lex()
Definition: TGLexer.h:215
SMLoc getLoc() const
Definition: TGLexer.cpp:99
TGLexer(SourceMgr &SrcMgr, ArrayRef< std::string > Macros)
Definition: TGLexer.cpp:77
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
support::ulittle32_t Word
Definition: IRSymtab.h:52
@ r_square
Definition: TGLexer.h:41
@ XListSplat
Definition: TGLexer.h:125
@ XSetDagArg
Definition: TGLexer.h:158
@ XGetDagName
Definition: TGLexer.h:157
@ l_square
Definition: TGLexer.h:40
@ CodeFragment
Definition: TGLexer.h:168
@ XInterleave
Definition: TGLexer.h:127
@ MultiClass
Definition: TGLexer.h:106
@ BinaryIntVal
Definition: TGLexer.h:66
@ XSetDagName
Definition: TGLexer.h:159
@ XGetDagArg
Definition: TGLexer.h:156
@ XListConcat
Definition: TGLexer.h:124
@ XStrConcat
Definition: TGLexer.h:126
@ FalseVal
Definition: TGLexer.h:59
@ dotdotdot
Definition: TGLexer.h:55
@ question
Definition: TGLexer.h:53
@ XListRemove
Definition: TGLexer.h:152
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
void PrintFatalError(const Twine &Msg)
Definition: Error.cpp:125
void PrintError(const Twine &Msg)
Definition: Error.cpp:101
SourceMgr SrcMgr
Definition: Error.cpp:24
void PrintWarning(const Twine &Msg)
Definition: Error.cpp:89
auto reverse(ContainerTy &&C)
Definition: STLExtras.h:419
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.