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