LLVM 22.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#include <cstring>
27
28using namespace llvm;
29
30namespace {
31// A list of supported preprocessing directives with their
32// internal token kinds and names.
33struct PreprocessorDir {
36};
37} // end anonymous namespace
38
39/// Returns true if `C` is a valid character in an identifier. If `First` is
40/// true, returns true if `C` is a valid first character of an identifier,
41/// else returns true if `C` is a valid non-first character of an identifier.
42/// Identifiers match the following regular expression:
43/// [a-zA-Z_][0-9a-zA-Z_]*
44static bool isValidIDChar(char C, bool First) {
45 if (C == '_' || isAlpha(C))
46 return true;
47 return !First && isDigit(C);
48}
49
50constexpr PreprocessorDir PreprocessorDirs[] = {{tgtok::Ifdef, "ifdef"},
51 {tgtok::Ifndef, "ifndef"},
52 {tgtok::Else, "else"},
53 {tgtok::Endif, "endif"},
54 {tgtok::Define, "define"}};
55
56// Returns a pointer past the end of a valid macro name at the start of `Str`.
57// Valid macro names match the regular expression [a-zA-Z_][0-9a-zA-Z_]*.
58static const char *lexMacroName(StringRef Str) {
59 assert(!Str.empty());
60
61 // Macro names start with [a-zA-Z_].
62 const char *Next = Str.begin();
63 if (!isValidIDChar(*Next, /*First=*/true))
64 return Next;
65 // Eat the first character of the name.
66 ++Next;
67
68 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
69 const char *End = Str.end();
70 while (Next != End && isValidIDChar(*Next, /*First=*/false))
71 ++Next;
72 return Next;
73}
74
76 CurBuffer = SrcMgr.getMainFileID();
77 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
78 CurPtr = CurBuf.begin();
79 TokStart = nullptr;
80
81 // Pretend that we enter the "top-level" include file.
82 PrepIncludeStack.emplace_back();
83
84 // Add all macros defined on the command line to the DefinedMacros set.
85 // Check invalid macro names and print fatal error if we find one.
86 for (StringRef MacroName : Macros) {
87 const char *End = lexMacroName(MacroName);
88 if (End != MacroName.end())
89 PrintFatalError("invalid macro name `" + MacroName +
90 "` specified on command line");
91
92 DefinedMacros.insert(MacroName);
93 }
94}
95
96SMLoc TGLexer::getLoc() const { return SMLoc::getFromPointer(TokStart); }
97
99 return {getLoc(), SMLoc::getFromPointer(CurPtr)};
100}
101
102/// ReturnError - Set the error to the specified string at the specified
103/// location. This is defined to always return tgtok::Error.
104tgtok::TokKind TGLexer::ReturnError(SMLoc Loc, const Twine &Msg) {
105 PrintError(Loc, Msg);
106 return tgtok::Error;
107}
108
109tgtok::TokKind TGLexer::ReturnError(const char *Loc, const Twine &Msg) {
110 return ReturnError(SMLoc::getFromPointer(Loc), Msg);
111}
112
113bool TGLexer::processEOF() {
114 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
115 if (ParentIncludeLoc != SMLoc()) {
116 // If prepExitInclude() detects a problem with the preprocessing
117 // control stack, it will return false. Pretend that we reached
118 // the final EOF and stop lexing more tokens by returning false
119 // to LexToken().
120 if (!prepExitInclude(false))
121 return false;
122
123 CurBuffer = SrcMgr.FindBufferContainingLoc(ParentIncludeLoc);
124 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
125 CurPtr = ParentIncludeLoc.getPointer();
126 // Make sure TokStart points into the parent file's buffer.
127 // LexToken() assigns to it before calling getNextChar(),
128 // so it is pointing into the included file now.
129 TokStart = CurPtr;
130 return true;
131 }
132
133 // Pretend that we exit the "top-level" include file.
134 // Note that in case of an error (e.g. control stack imbalance)
135 // the routine will issue a fatal error.
136 prepExitInclude(true);
137 return false;
138}
139
140int TGLexer::getNextChar() {
141 char CurChar = *CurPtr++;
142 switch (CurChar) {
143 default:
144 return (unsigned char)CurChar;
145
146 case 0: {
147 // A NUL character in the stream is either the end of the current buffer or
148 // a spurious NUL in the file. Disambiguate that here.
149 if (CurPtr - 1 == CurBuf.end()) {
150 --CurPtr; // Arrange for another call to return EOF again.
151 return EOF;
152 }
154 "NUL character is invalid in source; treated as space");
155 return ' ';
156 }
157
158 case '\n':
159 case '\r':
160 // Handle the newline character by ignoring it and incrementing the line
161 // count. However, be careful about 'dos style' files with \n\r in them.
162 // Only treat a \n\r or \r\n as a single line.
163 if ((*CurPtr == '\n' || (*CurPtr == '\r')) && *CurPtr != CurChar)
164 ++CurPtr; // Eat the two char newline sequence.
165 return '\n';
166 }
167}
168
169int TGLexer::peekNextChar(int Index) const { return *(CurPtr + Index); }
170
171tgtok::TokKind TGLexer::LexToken(bool FileOrLineStart) {
172 while (true) {
173 TokStart = CurPtr;
174 // This always consumes at least one character.
175 int CurChar = getNextChar();
176
177 switch (CurChar) {
178 default:
179 // Handle letters: [a-zA-Z_]
180 if (isValidIDChar(CurChar, /*First=*/true))
181 return LexIdentifier();
182
183 // Unknown character, emit an error.
184 return ReturnError(TokStart, "unexpected character");
185 case EOF:
186 // Lex next token, if we just left an include file.
187 if (processEOF()) {
188 // Leaving an include file means that the next symbol is located at the
189 // end of the 'include "..."' construct.
190 FileOrLineStart = false;
191 break;
192 }
193
194 // Return EOF denoting the end of lexing.
195 return tgtok::Eof;
196
197 case ':':
198 return tgtok::colon;
199 case ';':
200 return tgtok::semi;
201 case ',':
202 return tgtok::comma;
203 case '<':
204 return tgtok::less;
205 case '>':
206 return tgtok::greater;
207 case ']':
208 return tgtok::r_square;
209 case '{':
210 return tgtok::l_brace;
211 case '}':
212 return tgtok::r_brace;
213 case '(':
214 return tgtok::l_paren;
215 case ')':
216 return tgtok::r_paren;
217 case '=':
218 return tgtok::equal;
219 case '?':
220 return tgtok::question;
221 case '#':
222 if (FileOrLineStart) {
223 tgtok::TokKind Kind = prepIsDirective();
224 if (Kind != tgtok::Error)
225 return lexPreprocessor(Kind);
226 }
227
228 return tgtok::paste;
229
230 // The period is a separate case so we can recognize the "..."
231 // range punctuator.
232 case '.':
233 if (peekNextChar(0) == '.') {
234 ++CurPtr; // Eat second dot.
235 if (peekNextChar(0) == '.') {
236 ++CurPtr; // Eat third dot.
237 return tgtok::dotdotdot;
238 }
239 return ReturnError(TokStart, "invalid '..' punctuation");
240 }
241 return tgtok::dot;
242
243 case '\r':
244 llvm_unreachable("getNextChar() must never return '\r'");
245
246 case ' ':
247 case '\t':
248 // Ignore whitespace.
249 break;
250 case '\n':
251 // Ignore whitespace, and identify the new line.
252 FileOrLineStart = true;
253 break;
254 case '/':
255 // If this is the start of a // comment, skip until the end of the line or
256 // the end of the buffer.
257 if (*CurPtr == '/')
258 SkipBCPLComment();
259 else if (*CurPtr == '*') {
260 if (SkipCComment())
261 return tgtok::Error;
262 } else // Otherwise, this is an error.
263 return ReturnError(TokStart, "unexpected character");
264 break;
265 case '-':
266 case '+':
267 case '0':
268 case '1':
269 case '2':
270 case '3':
271 case '4':
272 case '5':
273 case '6':
274 case '7':
275 case '8':
276 case '9': {
277 int NextChar = 0;
278 if (isDigit(CurChar)) {
279 // Allow identifiers to start with a number if it is followed by
280 // an identifier. This can happen with paste operations like
281 // foo#8i.
282 int i = 0;
283 do {
284 NextChar = peekNextChar(i++);
285 } while (isDigit(NextChar));
286
287 if (NextChar == 'x' || NextChar == 'b') {
288 // If this is [0-9]b[01] or [0-9]x[0-9A-fa-f] this is most
289 // likely a number.
290 int NextNextChar = peekNextChar(i);
291 switch (NextNextChar) {
292 default:
293 break;
294 case '0':
295 case '1':
296 if (NextChar == 'b')
297 return LexNumber();
298 [[fallthrough]];
299 case '2':
300 case '3':
301 case '4':
302 case '5':
303 case '6':
304 case '7':
305 case '8':
306 case '9':
307 case 'a':
308 case 'b':
309 case 'c':
310 case 'd':
311 case 'e':
312 case 'f':
313 case 'A':
314 case 'B':
315 case 'C':
316 case 'D':
317 case 'E':
318 case 'F':
319 if (NextChar == 'x')
320 return LexNumber();
321 break;
322 }
323 }
324 }
325
326 if (isValidIDChar(NextChar, /*First=*/true))
327 return LexIdentifier();
328
329 return LexNumber();
330 }
331 case '"':
332 return LexString();
333 case '$':
334 return LexVarName();
335 case '[':
336 return LexBracket();
337 case '!':
338 return LexExclaim();
339 }
340 }
341}
342
343/// LexString - Lex "[^"]*"
344tgtok::TokKind TGLexer::LexString() {
345 const char *StrStart = CurPtr;
346
347 CurStrVal = "";
348
349 while (*CurPtr != '"') {
350 // If we hit the end of the buffer, report an error.
351 if (*CurPtr == 0 && CurPtr == CurBuf.end())
352 return ReturnError(StrStart, "end of file in string literal");
353
354 if (*CurPtr == '\n' || *CurPtr == '\r')
355 return ReturnError(StrStart, "end of line in string literal");
356
357 if (*CurPtr != '\\') {
358 CurStrVal += *CurPtr++;
359 continue;
360 }
361
362 ++CurPtr;
363
364 switch (*CurPtr) {
365 case '\\':
366 case '\'':
367 case '"':
368 // These turn into their literal character.
369 CurStrVal += *CurPtr++;
370 break;
371 case 't':
372 CurStrVal += '\t';
373 ++CurPtr;
374 break;
375 case 'n':
376 CurStrVal += '\n';
377 ++CurPtr;
378 break;
379
380 case '\n':
381 case '\r':
382 return ReturnError(CurPtr, "escaped newlines not supported in tblgen");
383
384 // If we hit the end of the buffer, report an error.
385 case '\0':
386 if (CurPtr == CurBuf.end())
387 return ReturnError(StrStart, "end of file in string literal");
388 [[fallthrough]];
389 default:
390 return ReturnError(CurPtr, "invalid escape in string literal");
391 }
392 }
393
394 ++CurPtr;
395 return tgtok::StrVal;
396}
397
398tgtok::TokKind TGLexer::LexVarName() {
399 if (!isValidIDChar(CurPtr[0], /*First=*/true))
400 return ReturnError(TokStart, "invalid variable name");
401
402 // Otherwise, we're ok, consume the rest of the characters.
403 const char *VarNameStart = CurPtr++;
404
405 while (isValidIDChar(*CurPtr, /*First=*/false))
406 ++CurPtr;
407
408 CurStrVal.assign(VarNameStart, CurPtr);
409 return tgtok::VarName;
410}
411
412tgtok::TokKind TGLexer::LexIdentifier() {
413 // The first letter is [a-zA-Z_].
414 const char *IdentStart = TokStart;
415
416 // Match the rest of the identifier regex: [0-9a-zA-Z_]*
417 while (isValidIDChar(*CurPtr, /*First=*/false))
418 ++CurPtr;
419
420 // Check to see if this identifier is a reserved keyword.
421 StringRef Str(IdentStart, CurPtr - IdentStart);
422
424 .Case("int", tgtok::Int)
425 .Case("bit", tgtok::Bit)
426 .Case("bits", tgtok::Bits)
427 .Case("string", tgtok::String)
428 .Case("list", tgtok::List)
429 .Case("code", tgtok::Code)
430 .Case("dag", tgtok::Dag)
431 .Case("class", tgtok::Class)
432 .Case("def", tgtok::Def)
433 .Case("true", tgtok::TrueVal)
434 .Case("false", tgtok::FalseVal)
435 .Case("foreach", tgtok::Foreach)
436 .Case("defm", tgtok::Defm)
437 .Case("defset", tgtok::Defset)
438 .Case("deftype", tgtok::Deftype)
439 .Case("multiclass", tgtok::MultiClass)
440 .Case("field", tgtok::Field)
441 .Case("let", tgtok::Let)
442 .Case("in", tgtok::In)
443 .Case("defvar", tgtok::Defvar)
444 .Case("include", tgtok::Include)
445 .Case("if", tgtok::If)
446 .Case("then", tgtok::Then)
447 .Case("else", tgtok::ElseKW)
448 .Case("assert", tgtok::Assert)
449 .Case("dump", tgtok::Dump)
451
452 // A couple of tokens require special processing.
453 switch (Kind) {
454 case tgtok::Include:
455 if (LexInclude())
456 return tgtok::Error;
457 return Lex();
458 case tgtok::Id:
459 CurStrVal.assign(Str.begin(), Str.end());
460 break;
461 default:
462 break;
463 }
464
465 return Kind;
466}
467
468/// LexInclude - We just read the "include" token. Get the string token that
469/// comes next and enter the include.
470bool TGLexer::LexInclude() {
471 // The token after the include must be a string.
472 tgtok::TokKind Tok = LexToken();
473 if (Tok == tgtok::Error)
474 return true;
475 if (Tok != tgtok::StrVal) {
476 PrintError(getLoc(), "expected filename after include");
477 return true;
478 }
479
480 // Get the string.
481 std::string Filename = CurStrVal;
482 std::string IncludedFile;
483
484 CurBuffer = SrcMgr.AddIncludeFile(Filename, SMLoc::getFromPointer(CurPtr),
485 IncludedFile);
486 if (!CurBuffer) {
487 PrintError(getLoc(), "could not find include file '" + Filename + "'");
488 return true;
489 }
490
491 Dependencies.insert(IncludedFile);
492 // Save the line number and lex buffer of the includer.
493 CurBuf = SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer();
494 CurPtr = CurBuf.begin();
495
496 PrepIncludeStack.emplace_back();
497 return false;
498}
499
500/// SkipBCPLComment - Skip over the comment by finding the next CR or LF.
501/// Or we may end up at the end of the buffer.
502void TGLexer::SkipBCPLComment() {
503 ++CurPtr; // Skip the second slash.
504 auto EOLPos = CurBuf.find_first_of("\r\n", CurPtr - CurBuf.data());
505 CurPtr = (EOLPos == StringRef::npos) ? CurBuf.end() : CurBuf.data() + EOLPos;
506}
507
508/// SkipCComment - This skips C-style /**/ comments. The only difference from C
509/// is that we allow nesting.
510bool TGLexer::SkipCComment() {
511 ++CurPtr; // Skip the star.
512 unsigned CommentDepth = 1;
513
514 while (true) {
515 int CurChar = getNextChar();
516 switch (CurChar) {
517 case EOF:
518 PrintError(TokStart, "unterminated comment");
519 return true;
520 case '*':
521 // End of the comment?
522 if (CurPtr[0] != '/')
523 break;
524
525 ++CurPtr; // End the */.
526 if (--CommentDepth == 0)
527 return false;
528 break;
529 case '/':
530 // Start of a nested comment?
531 if (CurPtr[0] != '*')
532 break;
533 ++CurPtr;
534 ++CommentDepth;
535 break;
536 }
537 }
538}
539
540/// LexNumber - Lex:
541/// [-+]?[0-9]+
542/// 0x[0-9a-fA-F]+
543/// 0b[01]+
544tgtok::TokKind TGLexer::LexNumber() {
545 unsigned Base = 0;
546 const char *NumStart;
547
548 // Check if it's a hex or a binary value.
549 if (CurPtr[-1] == '0') {
550 NumStart = CurPtr + 1;
551 if (CurPtr[0] == 'x') {
552 Base = 16;
553 do
554 ++CurPtr;
555 while (isHexDigit(CurPtr[0]));
556 } else if (CurPtr[0] == 'b') {
557 Base = 2;
558 do
559 ++CurPtr;
560 while (CurPtr[0] == '0' || CurPtr[0] == '1');
561 }
562 }
563
564 // For a hex or binary value, we always convert it to an unsigned value.
565 bool IsMinus = false;
566
567 // Check if it's a decimal value.
568 if (Base == 0) {
569 // Check for a sign without a digit.
570 if (!isDigit(CurPtr[0])) {
571 if (CurPtr[-1] == '-')
572 return tgtok::minus;
573 else if (CurPtr[-1] == '+')
574 return tgtok::plus;
575 }
576
577 Base = 10;
578 NumStart = TokStart;
579 IsMinus = CurPtr[-1] == '-';
580
581 while (isDigit(CurPtr[0]))
582 ++CurPtr;
583 }
584
585 // Requires at least one digit.
586 if (CurPtr == NumStart)
587 return ReturnError(TokStart, "invalid number");
588
589 errno = 0;
590 if (IsMinus)
591 CurIntVal = strtoll(NumStart, nullptr, Base);
592 else
593 CurIntVal = strtoull(NumStart, nullptr, Base);
594
595 if (errno == EINVAL)
596 return ReturnError(TokStart, "invalid number");
597 if (errno == ERANGE)
598 return ReturnError(TokStart, "number out of range");
599
600 return Base == 2 ? tgtok::BinaryIntVal : tgtok::IntVal;
601}
602
603/// LexBracket - We just read '['. If this is a code block, return it,
604/// otherwise return the bracket. Match: '[' and '[{ ( [^}]+ | }[^]] )* }]'
605tgtok::TokKind TGLexer::LexBracket() {
606 if (CurPtr[0] != '{')
607 return tgtok::l_square;
608 ++CurPtr;
609 const char *CodeStart = CurPtr;
610 while (true) {
611 int Char = getNextChar();
612 if (Char == EOF)
613 break;
614
615 if (Char != '}')
616 continue;
617
618 Char = getNextChar();
619 if (Char == EOF)
620 break;
621 if (Char == ']') {
622 CurStrVal.assign(CodeStart, CurPtr - 2);
623 return tgtok::CodeFragment;
624 }
625 }
626
627 return ReturnError(CodeStart - 2, "unterminated code block");
628}
629
630/// LexExclaim - Lex '!' and '![a-zA-Z]+'.
631tgtok::TokKind TGLexer::LexExclaim() {
632 if (!isAlpha(*CurPtr))
633 return ReturnError(CurPtr - 1, "invalid \"!operator\"");
634
635 const char *Start = CurPtr++;
636 while (isAlpha(*CurPtr))
637 ++CurPtr;
638
639 // Check to see which operator this is.
641 StringSwitch<tgtok::TokKind>(StringRef(Start, CurPtr - Start))
642 .Case("eq", tgtok::XEq)
643 .Case("ne", tgtok::XNe)
644 .Case("le", tgtok::XLe)
645 .Case("lt", tgtok::XLt)
646 .Case("ge", tgtok::XGe)
647 .Case("gt", tgtok::XGt)
648 .Case("if", tgtok::XIf)
649 .Case("cond", tgtok::XCond)
650 .Case("isa", tgtok::XIsA)
651 .Case("head", tgtok::XHead)
652 .Case("tail", tgtok::XTail)
653 .Case("size", tgtok::XSize)
654 .Case("con", tgtok::XConcat)
655 .Case("dag", tgtok::XDag)
656 .Case("add", tgtok::XADD)
657 .Case("sub", tgtok::XSUB)
658 .Case("mul", tgtok::XMUL)
659 .Case("div", tgtok::XDIV)
660 .Case("not", tgtok::XNOT)
661 .Case("logtwo", tgtok::XLOG2)
662 .Case("and", tgtok::XAND)
663 .Case("or", tgtok::XOR)
664 .Case("xor", tgtok::XXOR)
665 .Case("shl", tgtok::XSHL)
666 .Case("sra", tgtok::XSRA)
667 .Case("srl", tgtok::XSRL)
668 .Case("cast", tgtok::XCast)
669 .Case("empty", tgtok::XEmpty)
670 .Case("subst", tgtok::XSubst)
671 .Case("foldl", tgtok::XFoldl)
672 .Case("foreach", tgtok::XForEach)
673 .Case("filter", tgtok::XFilter)
674 .Case("listconcat", tgtok::XListConcat)
675 .Case("listflatten", tgtok::XListFlatten)
676 .Case("listsplat", tgtok::XListSplat)
677 .Case("listremove", tgtok::XListRemove)
678 .Case("range", tgtok::XRange)
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 .Cases("setdagop", "setop", tgtok::XSetDagOp) // !setop is deprecated.
686 .Cases("getdagop", "getop", tgtok::XGetDagOp) // !getop is deprecated.
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)
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 != '\n')
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!")
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)
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:50
static bool isValidIDChar(char C, bool First)
Returns true if C is a valid character in an identifier.
Definition: TGLexer.cpp:44
static const char * lexMacroName(StringRef Str)
Definition: TGLexer.cpp:58
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:71
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:32
unsigned getMainFileID() const
Definition: SourceMgr.h:133
const MemoryBuffer * getMemoryBuffer(unsigned i) const
Definition: SourceMgr.h:126
SMLoc getParentIncludeLoc(unsigned i) const
Definition: SourceMgr.h:138
LLVM_ABI unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition: SourceMgr.cpp:73
LLVM_ABI 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:280
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
iterator begin() const
Definition: StringRef.h:120
constexpr const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:148
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:384
iterator end() const
Definition: StringRef.h:122
static constexpr size_t npos
Definition: StringRef.h:57
std::pair< typename Base::iterator, bool > insert(StringRef key)
Definition: StringSet.h:39
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:68
R Default(T Value)
Definition: StringSwitch.h:177
StringSwitch & Cases(StringLiteral S0, StringLiteral S1, T Value)
Definition: StringSwitch.h:87
SMRange getLocRange() const
Definition: TGLexer.cpp:98
tgtok::TokKind Lex()
Definition: TGLexer.h:219
SMLoc getLoc() const
Definition: TGLexer.cpp:96
TGLexer(SourceMgr &SrcMgr, ArrayRef< std::string > Macros)
Definition: TGLexer.cpp:75
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.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
support::ulittle32_t Word
Definition: IRSymtab.h:53
@ r_square
Definition: TGLexer.h:41
@ XListSplat
Definition: TGLexer.h:124
@ XSetDagArg
Definition: TGLexer.h:162
@ XInstances
Definition: TGLexer.h:140
@ XGetDagName
Definition: TGLexer.h:161
@ l_square
Definition: TGLexer.h:40
@ CodeFragment
Definition: TGLexer.h:172
@ XInterleave
Definition: TGLexer.h:126
@ XSetDagOpName
Definition: TGLexer.h:153
@ MultiClass
Definition: TGLexer.h:104
@ BinaryIntVal
Definition: TGLexer.h:66
@ XSetDagName
Definition: TGLexer.h:163
@ XGetDagArg
Definition: TGLexer.h:160
@ XListConcat
Definition: TGLexer.h:122
@ XInitialized
Definition: TGLexer.h:139
@ XStrConcat
Definition: TGLexer.h:125
@ XListFlatten
Definition: TGLexer.h:123
@ FalseVal
Definition: TGLexer.h:59
@ dotdotdot
Definition: TGLexer.h:55
@ question
Definition: TGLexer.h:53
@ XGetDagOpName
Definition: TGLexer.h:154
@ XListRemove
Definition: TGLexer.h:156
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:1744
void PrintFatalError(const Twine &Msg)
Definition: Error.cpp:132
void PrintError(const Twine &Msg)
Definition: Error.cpp:104
SourceMgr SrcMgr
Definition: Error.cpp:24
void PrintWarning(const Twine &Msg)
Definition: Error.cpp:92
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.