1 //===- Pragma.cpp - Pragma registration and handling ----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the PragmaHandler/PragmaTable interfaces and implements
10 // pragma related methods of the Preprocessor class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Lex/Pragma.h"
15 #include "clang/Basic/CLWarnings.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/LLVM.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/Module.h"
21 #include "clang/Basic/SourceLocation.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TokenKinds.h"
24 #include "clang/Lex/HeaderSearch.h"
25 #include "clang/Lex/LexDiagnostic.h"
26 #include "clang/Lex/Lexer.h"
27 #include "clang/Lex/LiteralSupport.h"
28 #include "clang/Lex/MacroInfo.h"
29 #include "clang/Lex/ModuleLoader.h"
30 #include "clang/Lex/PPCallbacks.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorLexer.h"
33 #include "clang/Lex/PreprocessorOptions.h"
34 #include "clang/Lex/Token.h"
35 #include "clang/Lex/TokenLexer.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/DenseMap.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringRef.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/Timer.h"
43 #include <algorithm>
44 #include <cassert>
45 #include <cstddef>
46 #include <cstdint>
47 #include <optional>
48 #include <string>
49 #include <utility>
50 #include <vector>
51
52 using namespace clang;
53
54 // Out-of-line destructor to provide a home for the class.
55 PragmaHandler::~PragmaHandler() = default;
56
57 //===----------------------------------------------------------------------===//
58 // EmptyPragmaHandler Implementation.
59 //===----------------------------------------------------------------------===//
60
EmptyPragmaHandler(StringRef Name)61 EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
62
HandlePragma(Preprocessor & PP,PragmaIntroducer Introducer,Token & FirstToken)63 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
64 PragmaIntroducer Introducer,
65 Token &FirstToken) {}
66
67 //===----------------------------------------------------------------------===//
68 // PragmaNamespace Implementation.
69 //===----------------------------------------------------------------------===//
70
71 /// FindHandler - Check to see if there is already a handler for the
72 /// specified name. If not, return the handler for the null identifier if it
73 /// exists, otherwise return null. If IgnoreNull is true (the default) then
74 /// the null handler isn't returned on failure to match.
FindHandler(StringRef Name,bool IgnoreNull) const75 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
76 bool IgnoreNull) const {
77 auto I = Handlers.find(Name);
78 if (I != Handlers.end())
79 return I->getValue().get();
80 if (IgnoreNull)
81 return nullptr;
82 I = Handlers.find(StringRef());
83 if (I != Handlers.end())
84 return I->getValue().get();
85 return nullptr;
86 }
87
AddPragma(PragmaHandler * Handler)88 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
89 assert(!Handlers.count(Handler->getName()) &&
90 "A handler with this name is already registered in this namespace");
91 Handlers[Handler->getName()].reset(Handler);
92 }
93
RemovePragmaHandler(PragmaHandler * Handler)94 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
95 auto I = Handlers.find(Handler->getName());
96 assert(I != Handlers.end() &&
97 "Handler not registered in this namespace");
98 // Release ownership back to the caller.
99 I->getValue().release();
100 Handlers.erase(I);
101 }
102
HandlePragma(Preprocessor & PP,PragmaIntroducer Introducer,Token & Tok)103 void PragmaNamespace::HandlePragma(Preprocessor &PP,
104 PragmaIntroducer Introducer, Token &Tok) {
105 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
106 // expand it, the user can have a STDC #define, that should not affect this.
107 PP.LexUnexpandedToken(Tok);
108
109 // Get the handler for this token. If there is no handler, ignore the pragma.
110 PragmaHandler *Handler
111 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
112 : StringRef(),
113 /*IgnoreNull=*/false);
114 if (!Handler) {
115 PP.Diag(Tok, diag::warn_pragma_ignored);
116 return;
117 }
118
119 // Otherwise, pass it down.
120 Handler->HandlePragma(PP, Introducer, Tok);
121 }
122
123 //===----------------------------------------------------------------------===//
124 // Preprocessor Pragma Directive Handling.
125 //===----------------------------------------------------------------------===//
126
127 namespace {
128 // TokenCollector provides the option to collect tokens that were "read"
129 // and return them to the stream to be read later.
130 // Currently used when reading _Pragma/__pragma directives.
131 struct TokenCollector {
132 Preprocessor &Self;
133 bool Collect;
134 SmallVector<Token, 3> Tokens;
135 Token &Tok;
136
lex__anon851a8f8a0111::TokenCollector137 void lex() {
138 if (Collect)
139 Tokens.push_back(Tok);
140 Self.Lex(Tok);
141 }
142
revert__anon851a8f8a0111::TokenCollector143 void revert() {
144 assert(Collect && "did not collect tokens");
145 assert(!Tokens.empty() && "collected unexpected number of tokens");
146
147 // Push the ( "string" ) tokens into the token stream.
148 auto Toks = std::make_unique<Token[]>(Tokens.size());
149 std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
150 Toks[Tokens.size() - 1] = Tok;
151 Self.EnterTokenStream(std::move(Toks), Tokens.size(),
152 /*DisableMacroExpansion*/ true,
153 /*IsReinject*/ true);
154
155 // ... and return the pragma token unchanged.
156 Tok = *Tokens.begin();
157 }
158 };
159 } // namespace
160
161 /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
162 /// rest of the pragma, passing it to the registered pragma handlers.
HandlePragmaDirective(PragmaIntroducer Introducer)163 void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
164 if (Callbacks)
165 Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
166
167 if (!PragmasEnabled)
168 return;
169
170 ++NumPragma;
171
172 // Invoke the first level of pragma handlers which reads the namespace id.
173 Token Tok;
174 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
175
176 // If the pragma handler didn't read the rest of the line, consume it now.
177 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
178 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
179 DiscardUntilEndOfDirective();
180 }
181
182 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
183 /// return the first token after the directive. The _Pragma token has just
184 /// been read into 'Tok'.
Handle_Pragma(Token & Tok)185 void Preprocessor::Handle_Pragma(Token &Tok) {
186 // C11 6.10.3.4/3:
187 // all pragma unary operator expressions within [a completely
188 // macro-replaced preprocessing token sequence] are [...] processed [after
189 // rescanning is complete]
190 //
191 // This means that we execute _Pragma operators in two cases:
192 //
193 // 1) on token sequences that would otherwise be produced as the output of
194 // phase 4 of preprocessing, and
195 // 2) on token sequences formed as the macro-replaced token sequence of a
196 // macro argument
197 //
198 // Case #2 appears to be a wording bug: only _Pragmas that would survive to
199 // the end of phase 4 should actually be executed. Discussion on the WG14
200 // mailing list suggests that a _Pragma operator is notionally checked early,
201 // but only pragmas that survive to the end of phase 4 should be executed.
202 //
203 // In Case #2, we check the syntax now, but then put the tokens back into the
204 // token stream for later consumption.
205
206 TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
207
208 // Remember the pragma token location.
209 SourceLocation PragmaLoc = Tok.getLocation();
210
211 // Read the '('.
212 Toks.lex();
213 if (Tok.isNot(tok::l_paren)) {
214 Diag(PragmaLoc, diag::err__Pragma_malformed);
215 return;
216 }
217
218 // Read the '"..."'.
219 Toks.lex();
220 if (!tok::isStringLiteral(Tok.getKind())) {
221 Diag(PragmaLoc, diag::err__Pragma_malformed);
222 // Skip bad tokens, and the ')', if present.
223 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof) && Tok.isNot(tok::eod))
224 Lex(Tok);
225 while (Tok.isNot(tok::r_paren) &&
226 !Tok.isAtStartOfLine() &&
227 Tok.isNot(tok::eof) && Tok.isNot(tok::eod))
228 Lex(Tok);
229 if (Tok.is(tok::r_paren))
230 Lex(Tok);
231 return;
232 }
233
234 if (Tok.hasUDSuffix()) {
235 Diag(Tok, diag::err_invalid_string_udl);
236 // Skip this token, and the ')', if present.
237 Lex(Tok);
238 if (Tok.is(tok::r_paren))
239 Lex(Tok);
240 return;
241 }
242
243 // Remember the string.
244 Token StrTok = Tok;
245
246 // Read the ')'.
247 Toks.lex();
248 if (Tok.isNot(tok::r_paren)) {
249 Diag(PragmaLoc, diag::err__Pragma_malformed);
250 return;
251 }
252
253 // If we're expanding a macro argument, put the tokens back.
254 if (InMacroArgPreExpansion) {
255 Toks.revert();
256 return;
257 }
258
259 SourceLocation RParenLoc = Tok.getLocation();
260 bool Invalid = false;
261 SmallString<64> StrVal;
262 StrVal.resize(StrTok.getLength());
263 StringRef StrValRef = getSpelling(StrTok, StrVal, &Invalid);
264 if (Invalid) {
265 Diag(PragmaLoc, diag::err__Pragma_malformed);
266 return;
267 }
268
269 assert(StrValRef.size() <= StrVal.size());
270
271 // If the token was spelled somewhere else, copy it.
272 if (StrValRef.begin() != StrVal.begin())
273 StrVal.assign(StrValRef);
274 // Truncate if necessary.
275 else if (StrValRef.size() != StrVal.size())
276 StrVal.resize(StrValRef.size());
277
278 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1.
279 prepare_PragmaString(StrVal);
280
281 // Plop the string (including the newline and trailing null) into a buffer
282 // where we can lex it.
283 Token TmpTok;
284 TmpTok.startToken();
285 CreateString(StrVal, TmpTok);
286 SourceLocation TokLoc = TmpTok.getLocation();
287
288 // Make and enter a lexer object so that we lex and expand the tokens just
289 // like any others.
290 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
291 StrVal.size(), *this);
292
293 EnterSourceFileWithLexer(TL, nullptr);
294
295 // With everything set up, lex this as a #pragma directive.
296 HandlePragmaDirective({PIK__Pragma, PragmaLoc});
297
298 // Finally, return whatever came after the pragma directive.
299 return Lex(Tok);
300 }
301
prepare_PragmaString(SmallVectorImpl<char> & StrVal)302 void clang::prepare_PragmaString(SmallVectorImpl<char> &StrVal) {
303 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
304 (StrVal[0] == 'u' && StrVal[1] != '8'))
305 StrVal.erase(StrVal.begin());
306 else if (StrVal[0] == 'u')
307 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
308
309 if (StrVal[0] == 'R') {
310 // FIXME: C++11 does not specify how to handle raw-string-literals here.
311 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
312 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
313 "Invalid raw string token!");
314
315 // Measure the length of the d-char-sequence.
316 unsigned NumDChars = 0;
317 while (StrVal[2 + NumDChars] != '(') {
318 assert(NumDChars < (StrVal.size() - 5) / 2 &&
319 "Invalid raw string token!");
320 ++NumDChars;
321 }
322 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
323
324 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
325 // parens below.
326 StrVal.erase(StrVal.begin(), StrVal.begin() + 2 + NumDChars);
327 StrVal.erase(StrVal.end() - 1 - NumDChars, StrVal.end());
328 } else {
329 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
330 "Invalid string token!");
331
332 // Remove escaped quotes and escapes.
333 unsigned ResultPos = 1;
334 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
335 // Skip escapes. \\ -> '\' and \" -> '"'.
336 if (StrVal[i] == '\\' && i + 1 < e &&
337 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
338 ++i;
339 StrVal[ResultPos++] = StrVal[i];
340 }
341 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
342 }
343
344 // Remove the front quote, replacing it with a space, so that the pragma
345 // contents appear to have a space before them.
346 StrVal[0] = ' ';
347
348 // Replace the terminating quote with a \n.
349 StrVal[StrVal.size() - 1] = '\n';
350 }
351
352 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
353 /// is not enclosed within a string literal.
HandleMicrosoft__pragma(Token & Tok)354 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
355 // During macro pre-expansion, check the syntax now but put the tokens back
356 // into the token stream for later consumption. Same as Handle_Pragma.
357 TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
358
359 // Remember the pragma token location.
360 SourceLocation PragmaLoc = Tok.getLocation();
361
362 // Read the '('.
363 Toks.lex();
364 if (Tok.isNot(tok::l_paren)) {
365 Diag(PragmaLoc, diag::err__Pragma_malformed);
366 return;
367 }
368
369 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
370 SmallVector<Token, 32> PragmaToks;
371 int NumParens = 0;
372 Toks.lex();
373 while (Tok.isNot(tok::eof)) {
374 PragmaToks.push_back(Tok);
375 if (Tok.is(tok::l_paren))
376 NumParens++;
377 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
378 break;
379 Toks.lex();
380 }
381
382 if (Tok.is(tok::eof)) {
383 Diag(PragmaLoc, diag::err_unterminated___pragma);
384 return;
385 }
386
387 // If we're expanding a macro argument, put the tokens back.
388 if (InMacroArgPreExpansion) {
389 Toks.revert();
390 return;
391 }
392
393 PragmaToks.front().setFlag(Token::LeadingSpace);
394
395 // Replace the ')' with an EOD to mark the end of the pragma.
396 PragmaToks.back().setKind(tok::eod);
397
398 Token *TokArray = new Token[PragmaToks.size()];
399 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
400
401 // Push the tokens onto the stack.
402 EnterTokenStream(TokArray, PragmaToks.size(), true, true,
403 /*IsReinject*/ false);
404
405 // With everything set up, lex this as a #pragma directive.
406 HandlePragmaDirective({PIK___pragma, PragmaLoc});
407
408 // Finally, return whatever came after the pragma directive.
409 return Lex(Tok);
410 }
411
412 /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
HandlePragmaOnce(Token & OnceTok)413 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
414 // Don't honor the 'once' when handling the primary source file, unless
415 // this is a prefix to a TU, which indicates we're generating a PCH file, or
416 // when the main file is a header (e.g. when -xc-header is provided on the
417 // commandline).
418 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
419 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
420 return;
421 }
422
423 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
424 // Mark the file as a once-only file now.
425 HeaderInfo.MarkFileIncludeOnce(*getCurrentFileLexer()->getFileEntry());
426 }
427
HandlePragmaMark(Token & MarkTok)428 void Preprocessor::HandlePragmaMark(Token &MarkTok) {
429 assert(CurPPLexer && "No current lexer?");
430
431 SmallString<64> Buffer;
432 CurLexer->ReadToEndOfLine(&Buffer);
433 if (Callbacks)
434 Callbacks->PragmaMark(MarkTok.getLocation(), Buffer);
435 }
436
437 /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
HandlePragmaPoison()438 void Preprocessor::HandlePragmaPoison() {
439 Token Tok;
440
441 while (true) {
442 // Read the next token to poison. While doing this, pretend that we are
443 // skipping while reading the identifier to poison.
444 // This avoids errors on code like:
445 // #pragma GCC poison X
446 // #pragma GCC poison X
447 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
448 LexUnexpandedToken(Tok);
449 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
450
451 // If we reached the end of line, we're done.
452 if (Tok.is(tok::eod)) return;
453
454 // Can only poison identifiers.
455 if (Tok.isNot(tok::raw_identifier)) {
456 Diag(Tok, diag::err_pp_invalid_poison);
457 return;
458 }
459
460 // Look up the identifier info for the token. We disabled identifier lookup
461 // by saying we're skipping contents, so we need to do this manually.
462 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
463
464 // Already poisoned.
465 if (II->isPoisoned()) continue;
466
467 // If this is a macro identifier, emit a warning.
468 if (isMacroDefined(II))
469 Diag(Tok, diag::pp_poisoning_existing_macro);
470
471 // Finally, poison it!
472 II->setIsPoisoned();
473 if (II->isFromAST())
474 II->setChangedSinceDeserialization();
475 }
476 }
477
478 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
479 /// that the whole directive has been parsed.
HandlePragmaSystemHeader(Token & SysHeaderTok)480 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
481 if (isInPrimaryFile()) {
482 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
483 return;
484 }
485
486 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
487 PreprocessorLexer *TheLexer = getCurrentFileLexer();
488
489 // Mark the file as a system header.
490 HeaderInfo.MarkFileSystemHeader(*TheLexer->getFileEntry());
491
492 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
493 if (PLoc.isInvalid())
494 return;
495
496 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
497
498 // Notify the client, if desired, that we are in a new source file.
499 if (Callbacks)
500 Callbacks->FileChanged(SysHeaderTok.getLocation(),
501 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
502
503 // Emit a line marker. This will change any source locations from this point
504 // forward to realize they are in a system header.
505 // Create a line note with this information.
506 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
507 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
508 SrcMgr::C_System);
509 }
510
511 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
HandlePragmaDependency(Token & DependencyTok)512 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
513 Token FilenameTok;
514 if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
515 return;
516
517 // If the next token wasn't a header-name, diagnose the error.
518 if (FilenameTok.isNot(tok::header_name)) {
519 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
520 return;
521 }
522
523 // Reserve a buffer to get the spelling.
524 SmallString<128> FilenameBuffer;
525 bool Invalid = false;
526 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
527 if (Invalid)
528 return;
529
530 bool isAngled =
531 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
532 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
533 // error.
534 if (Filename.empty())
535 return;
536
537 // Search include directories for this file.
538 OptionalFileEntryRef File =
539 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
540 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
541 if (!File) {
542 if (!SuppressIncludeNotFoundError)
543 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
544 return;
545 }
546
547 OptionalFileEntryRef CurFile = getCurrentFileLexer()->getFileEntry();
548
549 // If this file is older than the file it depends on, emit a diagnostic.
550 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
551 // Lex tokens at the end of the message and include them in the message.
552 std::string Message;
553 Lex(DependencyTok);
554 while (DependencyTok.isNot(tok::eod)) {
555 Message += getSpelling(DependencyTok) + " ";
556 Lex(DependencyTok);
557 }
558
559 // Remove the trailing ' ' if present.
560 if (!Message.empty())
561 Message.erase(Message.end()-1);
562 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
563 }
564 }
565
566 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
567 /// Return the IdentifierInfo* associated with the macro to push or pop.
ParsePragmaPushOrPopMacro(Token & Tok)568 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
569 // Remember the pragma token location.
570 Token PragmaTok = Tok;
571
572 // Read the '('.
573 Lex(Tok);
574 if (Tok.isNot(tok::l_paren)) {
575 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
576 << getSpelling(PragmaTok);
577 return nullptr;
578 }
579
580 // Read the macro name string.
581 Lex(Tok);
582 if (Tok.isNot(tok::string_literal)) {
583 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
584 << getSpelling(PragmaTok);
585 return nullptr;
586 }
587
588 if (Tok.hasUDSuffix()) {
589 Diag(Tok, diag::err_invalid_string_udl);
590 return nullptr;
591 }
592
593 // Remember the macro string.
594 std::string StrVal = getSpelling(Tok);
595
596 // Read the ')'.
597 Lex(Tok);
598 if (Tok.isNot(tok::r_paren)) {
599 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
600 << getSpelling(PragmaTok);
601 return nullptr;
602 }
603
604 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
605 "Invalid string token!");
606
607 // Create a Token from the string.
608 Token MacroTok;
609 MacroTok.startToken();
610 MacroTok.setKind(tok::raw_identifier);
611 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
612
613 // Get the IdentifierInfo of MacroToPushTok.
614 return LookUpIdentifierInfo(MacroTok);
615 }
616
617 /// Handle \#pragma push_macro.
618 ///
619 /// The syntax is:
620 /// \code
621 /// #pragma push_macro("macro")
622 /// \endcode
HandlePragmaPushMacro(Token & PushMacroTok)623 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
624 // Parse the pragma directive and get the macro IdentifierInfo*.
625 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
626 if (!IdentInfo) return;
627
628 // Get the MacroInfo associated with IdentInfo.
629 MacroInfo *MI = getMacroInfo(IdentInfo);
630
631 if (MI) {
632 // Allow the original MacroInfo to be redefined later.
633 MI->setIsAllowRedefinitionsWithoutWarning(true);
634 }
635
636 // Push the cloned MacroInfo so we can retrieve it later.
637 PragmaPushMacroInfo[IdentInfo].push_back(MI);
638 }
639
640 /// Handle \#pragma pop_macro.
641 ///
642 /// The syntax is:
643 /// \code
644 /// #pragma pop_macro("macro")
645 /// \endcode
HandlePragmaPopMacro(Token & PopMacroTok)646 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
647 SourceLocation MessageLoc = PopMacroTok.getLocation();
648
649 // Parse the pragma directive and get the macro IdentifierInfo*.
650 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
651 if (!IdentInfo) return;
652
653 // Find the vector<MacroInfo*> associated with the macro.
654 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
655 PragmaPushMacroInfo.find(IdentInfo);
656 if (iter != PragmaPushMacroInfo.end()) {
657 // Forget the MacroInfo currently associated with IdentInfo.
658 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
659 if (MI->isWarnIfUnused())
660 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
661 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
662 }
663
664 // Get the MacroInfo we want to reinstall.
665 MacroInfo *MacroToReInstall = iter->second.back();
666
667 if (MacroToReInstall)
668 // Reinstall the previously pushed macro.
669 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
670
671 // Pop PragmaPushMacroInfo stack.
672 iter->second.pop_back();
673 if (iter->second.empty())
674 PragmaPushMacroInfo.erase(iter);
675 } else {
676 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
677 << IdentInfo->getName();
678 }
679 }
680
HandlePragmaIncludeAlias(Token & Tok)681 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
682 // We will either get a quoted filename or a bracketed filename, and we
683 // have to track which we got. The first filename is the source name,
684 // and the second name is the mapped filename. If the first is quoted,
685 // the second must be as well (cannot mix and match quotes and brackets).
686
687 // Get the open paren
688 Lex(Tok);
689 if (Tok.isNot(tok::l_paren)) {
690 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
691 return;
692 }
693
694 // We expect either a quoted string literal, or a bracketed name
695 Token SourceFilenameTok;
696 if (LexHeaderName(SourceFilenameTok))
697 return;
698
699 StringRef SourceFileName;
700 SmallString<128> FileNameBuffer;
701 if (SourceFilenameTok.is(tok::header_name)) {
702 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
703 } else {
704 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
705 return;
706 }
707 FileNameBuffer.clear();
708
709 // Now we expect a comma, followed by another include name
710 Lex(Tok);
711 if (Tok.isNot(tok::comma)) {
712 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
713 return;
714 }
715
716 Token ReplaceFilenameTok;
717 if (LexHeaderName(ReplaceFilenameTok))
718 return;
719
720 StringRef ReplaceFileName;
721 if (ReplaceFilenameTok.is(tok::header_name)) {
722 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
723 } else {
724 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
725 return;
726 }
727
728 // Finally, we expect the closing paren
729 Lex(Tok);
730 if (Tok.isNot(tok::r_paren)) {
731 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
732 return;
733 }
734
735 // Now that we have the source and target filenames, we need to make sure
736 // they're both of the same type (angled vs non-angled)
737 StringRef OriginalSource = SourceFileName;
738
739 bool SourceIsAngled =
740 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
741 SourceFileName);
742 bool ReplaceIsAngled =
743 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
744 ReplaceFileName);
745 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
746 (SourceIsAngled != ReplaceIsAngled)) {
747 unsigned int DiagID;
748 if (SourceIsAngled)
749 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
750 else
751 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
752
753 Diag(SourceFilenameTok.getLocation(), DiagID)
754 << SourceFileName
755 << ReplaceFileName;
756
757 return;
758 }
759
760 // Now we can let the include handler know about this mapping
761 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
762 }
763
764 // Lex a component of a module name: either an identifier or a string literal;
765 // for components that can be expressed both ways, the two forms are equivalent.
LexModuleNameComponent(Preprocessor & PP,Token & Tok,IdentifierLoc & ModuleNameComponent,bool First)766 static bool LexModuleNameComponent(Preprocessor &PP, Token &Tok,
767 IdentifierLoc &ModuleNameComponent,
768 bool First) {
769 PP.LexUnexpandedToken(Tok);
770 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
771 StringLiteralParser Literal(Tok, PP);
772 if (Literal.hadError)
773 return true;
774 ModuleNameComponent = IdentifierLoc(
775 Tok.getLocation(), PP.getIdentifierInfo(Literal.GetString()));
776 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
777 ModuleNameComponent =
778 IdentifierLoc(Tok.getLocation(), Tok.getIdentifierInfo());
779 } else {
780 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
781 return true;
782 }
783 return false;
784 }
785
LexModuleName(Preprocessor & PP,Token & Tok,llvm::SmallVectorImpl<IdentifierLoc> & ModuleName)786 static bool LexModuleName(Preprocessor &PP, Token &Tok,
787 llvm::SmallVectorImpl<IdentifierLoc> &ModuleName) {
788 while (true) {
789 IdentifierLoc NameComponent;
790 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
791 return true;
792 ModuleName.push_back(NameComponent);
793
794 PP.LexUnexpandedToken(Tok);
795 if (Tok.isNot(tok::period))
796 return false;
797 }
798 }
799
HandlePragmaModuleBuild(Token & Tok)800 void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
801 SourceLocation Loc = Tok.getLocation();
802
803 IdentifierLoc ModuleNameLoc;
804 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
805 return;
806 IdentifierInfo *ModuleName = ModuleNameLoc.getIdentifierInfo();
807
808 LexUnexpandedToken(Tok);
809 if (Tok.isNot(tok::eod)) {
810 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
811 DiscardUntilEndOfDirective();
812 }
813
814 CurLexer->LexingRawMode = true;
815
816 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
817 if (Tok.getKind() != tok::raw_identifier ||
818 Tok.getRawIdentifier() != Ident)
819 return false;
820 CurLexer->Lex(Tok);
821 return true;
822 };
823
824 // Scan forward looking for the end of the module.
825 const char *Start = CurLexer->getBufferLocation();
826 const char *End = nullptr;
827 unsigned NestingLevel = 1;
828 while (true) {
829 End = CurLexer->getBufferLocation();
830 CurLexer->Lex(Tok);
831
832 if (Tok.is(tok::eof)) {
833 Diag(Loc, diag::err_pp_module_build_missing_end);
834 break;
835 }
836
837 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
838 // Token was part of module; keep going.
839 continue;
840 }
841
842 // We hit something directive-shaped; check to see if this is the end
843 // of the module build.
844 CurLexer->ParsingPreprocessorDirective = true;
845 CurLexer->Lex(Tok);
846 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
847 TryConsumeIdentifier("module")) {
848 if (TryConsumeIdentifier("build"))
849 // #pragma clang module build -> entering a nested module build.
850 ++NestingLevel;
851 else if (TryConsumeIdentifier("endbuild")) {
852 // #pragma clang module endbuild -> leaving a module build.
853 if (--NestingLevel == 0)
854 break;
855 }
856 // We should either be looking at the EOD or more of the current directive
857 // preceding the EOD. Either way we can ignore this token and keep going.
858 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
859 }
860 }
861
862 CurLexer->LexingRawMode = false;
863
864 // Load the extracted text as a preprocessed module.
865 assert(CurLexer->getBuffer().begin() <= Start &&
866 Start <= CurLexer->getBuffer().end() &&
867 CurLexer->getBuffer().begin() <= End &&
868 End <= CurLexer->getBuffer().end() &&
869 "module source range not contained within same file buffer");
870 TheModuleLoader.createModuleFromSource(Loc, ModuleName->getName(),
871 StringRef(Start, End - Start));
872 }
873
HandlePragmaHdrstop(Token & Tok)874 void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
875 Lex(Tok);
876 if (Tok.is(tok::l_paren)) {
877 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
878
879 std::string FileName;
880 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
881 return;
882
883 if (Tok.isNot(tok::r_paren)) {
884 Diag(Tok, diag::err_expected) << tok::r_paren;
885 return;
886 }
887 Lex(Tok);
888 }
889 if (Tok.isNot(tok::eod))
890 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
891 << "pragma hdrstop";
892
893 if (creatingPCHWithPragmaHdrStop() &&
894 SourceMgr.isInMainFile(Tok.getLocation())) {
895 assert(CurLexer && "no lexer for #pragma hdrstop processing");
896 Token &Result = Tok;
897 Result.startToken();
898 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
899 CurLexer->cutOffLexing();
900 }
901 if (usingPCHWithPragmaHdrStop())
902 SkippingUntilPragmaHdrStop = false;
903 }
904
905 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
906 /// If 'Namespace' is non-null, then it is a token required to exist on the
907 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
AddPragmaHandler(StringRef Namespace,PragmaHandler * Handler)908 void Preprocessor::AddPragmaHandler(StringRef Namespace,
909 PragmaHandler *Handler) {
910 PragmaNamespace *InsertNS = PragmaHandlers.get();
911
912 // If this is specified to be in a namespace, step down into it.
913 if (!Namespace.empty()) {
914 // If there is already a pragma handler with the name of this namespace,
915 // we either have an error (directive with the same name as a namespace) or
916 // we already have the namespace to insert into.
917 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
918 InsertNS = Existing->getIfNamespace();
919 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
920 " handler with the same name!");
921 } else {
922 // Otherwise, this namespace doesn't exist yet, create and insert the
923 // handler for it.
924 InsertNS = new PragmaNamespace(Namespace);
925 PragmaHandlers->AddPragma(InsertNS);
926 }
927 }
928
929 // Check to make sure we don't already have a pragma for this identifier.
930 assert(!InsertNS->FindHandler(Handler->getName()) &&
931 "Pragma handler already exists for this identifier!");
932 InsertNS->AddPragma(Handler);
933 }
934
935 /// RemovePragmaHandler - Remove the specific pragma handler from the
936 /// preprocessor. If \arg Namespace is non-null, then it should be the
937 /// namespace that \arg Handler was added to. It is an error to remove
938 /// a handler that has not been registered.
RemovePragmaHandler(StringRef Namespace,PragmaHandler * Handler)939 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
940 PragmaHandler *Handler) {
941 PragmaNamespace *NS = PragmaHandlers.get();
942
943 // If this is specified to be in a namespace, step down into it.
944 if (!Namespace.empty()) {
945 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
946 assert(Existing && "Namespace containing handler does not exist!");
947
948 NS = Existing->getIfNamespace();
949 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
950 }
951
952 NS->RemovePragmaHandler(Handler);
953
954 // If this is a non-default namespace and it is now empty, remove it.
955 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
956 PragmaHandlers->RemovePragmaHandler(NS);
957 delete NS;
958 }
959 }
960
LexOnOffSwitch(tok::OnOffSwitch & Result)961 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
962 Token Tok;
963 LexUnexpandedToken(Tok);
964
965 if (Tok.isNot(tok::identifier)) {
966 Diag(Tok, diag::ext_on_off_switch_syntax);
967 return true;
968 }
969 IdentifierInfo *II = Tok.getIdentifierInfo();
970 if (II->isStr("ON"))
971 Result = tok::OOS_ON;
972 else if (II->isStr("OFF"))
973 Result = tok::OOS_OFF;
974 else if (II->isStr("DEFAULT"))
975 Result = tok::OOS_DEFAULT;
976 else {
977 Diag(Tok, diag::ext_on_off_switch_syntax);
978 return true;
979 }
980
981 // Verify that this is followed by EOD.
982 LexUnexpandedToken(Tok);
983 if (Tok.isNot(tok::eod))
984 Diag(Tok, diag::ext_pragma_syntax_eod);
985 return false;
986 }
987
988 namespace {
989
990 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
991 struct PragmaOnceHandler : public PragmaHandler {
PragmaOnceHandler__anon851a8f8a0311::PragmaOnceHandler992 PragmaOnceHandler() : PragmaHandler("once") {}
993
HandlePragma__anon851a8f8a0311::PragmaOnceHandler994 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
995 Token &OnceTok) override {
996 PP.CheckEndOfDirective("pragma once");
997 PP.HandlePragmaOnce(OnceTok);
998 }
999 };
1000
1001 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
1002 /// rest of the line is not lexed.
1003 struct PragmaMarkHandler : public PragmaHandler {
PragmaMarkHandler__anon851a8f8a0311::PragmaMarkHandler1004 PragmaMarkHandler() : PragmaHandler("mark") {}
1005
HandlePragma__anon851a8f8a0311::PragmaMarkHandler1006 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1007 Token &MarkTok) override {
1008 PP.HandlePragmaMark(MarkTok);
1009 }
1010 };
1011
1012 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
1013 struct PragmaPoisonHandler : public PragmaHandler {
PragmaPoisonHandler__anon851a8f8a0311::PragmaPoisonHandler1014 PragmaPoisonHandler() : PragmaHandler("poison") {}
1015
HandlePragma__anon851a8f8a0311::PragmaPoisonHandler1016 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1017 Token &PoisonTok) override {
1018 PP.HandlePragmaPoison();
1019 }
1020 };
1021
1022 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
1023 /// as a system header, which silences warnings in it.
1024 struct PragmaSystemHeaderHandler : public PragmaHandler {
PragmaSystemHeaderHandler__anon851a8f8a0311::PragmaSystemHeaderHandler1025 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
1026
HandlePragma__anon851a8f8a0311::PragmaSystemHeaderHandler1027 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1028 Token &SHToken) override {
1029 PP.HandlePragmaSystemHeader(SHToken);
1030 PP.CheckEndOfDirective("pragma");
1031 }
1032 };
1033
1034 struct PragmaDependencyHandler : public PragmaHandler {
PragmaDependencyHandler__anon851a8f8a0311::PragmaDependencyHandler1035 PragmaDependencyHandler() : PragmaHandler("dependency") {}
1036
HandlePragma__anon851a8f8a0311::PragmaDependencyHandler1037 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1038 Token &DepToken) override {
1039 PP.HandlePragmaDependency(DepToken);
1040 }
1041 };
1042
1043 struct PragmaDebugHandler : public PragmaHandler {
PragmaDebugHandler__anon851a8f8a0311::PragmaDebugHandler1044 PragmaDebugHandler() : PragmaHandler("__debug") {}
1045
HandlePragma__anon851a8f8a0311::PragmaDebugHandler1046 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1047 Token &DebugToken) override {
1048 Token Tok;
1049 PP.LexUnexpandedToken(Tok);
1050 if (Tok.isNot(tok::identifier)) {
1051 PP.Diag(Tok, diag::warn_pragma_debug_missing_command);
1052 return;
1053 }
1054 IdentifierInfo *II = Tok.getIdentifierInfo();
1055
1056 if (II->isStr("assert")) {
1057 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1058 llvm_unreachable("This is an assertion!");
1059 } else if (II->isStr("crash")) {
1060 llvm::Timer T("crash", "pragma crash");
1061 llvm::TimeRegion R(&T);
1062 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1063 LLVM_BUILTIN_TRAP;
1064 } else if (II->isStr("parser_crash")) {
1065 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash) {
1066 Token Crasher;
1067 Crasher.startToken();
1068 Crasher.setKind(tok::annot_pragma_parser_crash);
1069 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
1070 PP.EnterToken(Crasher, /*IsReinject*/ false);
1071 }
1072 } else if (II->isStr("dump")) {
1073 Token DumpAnnot;
1074 DumpAnnot.startToken();
1075 DumpAnnot.setKind(tok::annot_pragma_dump);
1076 DumpAnnot.setAnnotationRange(SourceRange(Tok.getLocation()));
1077 PP.EnterToken(DumpAnnot, /*IsReinject*/false);
1078 } else if (II->isStr("diag_mapping")) {
1079 Token DiagName;
1080 PP.LexUnexpandedToken(DiagName);
1081 if (DiagName.is(tok::eod))
1082 PP.getDiagnostics().dump();
1083 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1084 StringLiteralParser Literal(DiagName, PP,
1085 StringLiteralEvalMethod::Unevaluated);
1086 if (Literal.hadError)
1087 return;
1088 PP.getDiagnostics().dump(Literal.GetString());
1089 } else {
1090 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1091 << II->getName();
1092 }
1093 } else if (II->isStr("llvm_fatal_error")) {
1094 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1095 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1096 } else if (II->isStr("llvm_unreachable")) {
1097 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1098 llvm_unreachable("#pragma clang __debug llvm_unreachable");
1099 } else if (II->isStr("macro")) {
1100 Token MacroName;
1101 PP.LexUnexpandedToken(MacroName);
1102 auto *MacroII = MacroName.getIdentifierInfo();
1103 if (MacroII)
1104 PP.dumpMacroInfo(MacroII);
1105 else
1106 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1107 << II->getName();
1108 } else if (II->isStr("module_map")) {
1109 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1110 if (LexModuleName(PP, Tok, ModuleName))
1111 return;
1112 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1113 Module *M = nullptr;
1114 for (auto IIAndLoc : ModuleName) {
1115 M = MM.lookupModuleQualified(IIAndLoc.getIdentifierInfo()->getName(),
1116 M);
1117 if (!M) {
1118 PP.Diag(IIAndLoc.getLoc(), diag::warn_pragma_debug_unknown_module)
1119 << IIAndLoc.getIdentifierInfo()->getName();
1120 return;
1121 }
1122 }
1123 M->dump();
1124 } else if (II->isStr("module_lookup")) {
1125 Token MName;
1126 PP.LexUnexpandedToken(MName);
1127 auto *MNameII = MName.getIdentifierInfo();
1128 if (!MNameII) {
1129 PP.Diag(MName, diag::warn_pragma_debug_missing_argument)
1130 << II->getName();
1131 return;
1132 }
1133 Module *M = PP.getHeaderSearchInfo().lookupModule(MNameII->getName());
1134 if (!M) {
1135 PP.Diag(MName, diag::warn_pragma_debug_unable_to_find_module)
1136 << MNameII->getName();
1137 return;
1138 }
1139 M->dump();
1140 } else if (II->isStr("overflow_stack")) {
1141 if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
1142 DebugOverflowStack();
1143 } else if (II->isStr("captured")) {
1144 HandleCaptured(PP);
1145 } else if (II->isStr("modules")) {
1146 struct ModuleVisitor {
1147 Preprocessor &PP;
1148 void visit(Module *M, bool VisibleOnly) {
1149 SourceLocation ImportLoc = PP.getModuleImportLoc(M);
1150 if (!VisibleOnly || ImportLoc.isValid()) {
1151 llvm::errs() << M->getFullModuleName() << " ";
1152 if (ImportLoc.isValid()) {
1153 llvm::errs() << M << " visible ";
1154 ImportLoc.print(llvm::errs(), PP.getSourceManager());
1155 }
1156 llvm::errs() << "\n";
1157 }
1158 for (Module *Sub : M->submodules()) {
1159 if (!VisibleOnly || ImportLoc.isInvalid() || Sub->IsExplicit)
1160 visit(Sub, VisibleOnly);
1161 }
1162 }
1163 void visitAll(bool VisibleOnly) {
1164 for (auto &NameAndMod :
1165 PP.getHeaderSearchInfo().getModuleMap().modules())
1166 visit(NameAndMod.second, VisibleOnly);
1167 }
1168 } Visitor{PP};
1169
1170 Token Kind;
1171 PP.LexUnexpandedToken(Kind);
1172 auto *DumpII = Kind.getIdentifierInfo();
1173 if (!DumpII) {
1174 PP.Diag(Kind, diag::warn_pragma_debug_missing_argument)
1175 << II->getName();
1176 } else if (DumpII->isStr("all")) {
1177 Visitor.visitAll(false);
1178 } else if (DumpII->isStr("visible")) {
1179 Visitor.visitAll(true);
1180 } else if (DumpII->isStr("building")) {
1181 for (auto &Building : PP.getBuildingSubmodules()) {
1182 llvm::errs() << "in " << Building.M->getFullModuleName();
1183 if (Building.ImportLoc.isValid()) {
1184 llvm::errs() << " imported ";
1185 if (Building.IsPragma)
1186 llvm::errs() << "via pragma ";
1187 llvm::errs() << "at ";
1188 Building.ImportLoc.print(llvm::errs(), PP.getSourceManager());
1189 llvm::errs() << "\n";
1190 }
1191 }
1192 } else {
1193 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1194 << DumpII->getName();
1195 }
1196 } else if (II->isStr("sloc_usage")) {
1197 // An optional integer literal argument specifies the number of files to
1198 // specifically report information about.
1199 std::optional<unsigned> MaxNotes;
1200 Token ArgToken;
1201 PP.Lex(ArgToken);
1202 uint64_t Value;
1203 if (ArgToken.is(tok::numeric_constant) &&
1204 PP.parseSimpleIntegerLiteral(ArgToken, Value)) {
1205 MaxNotes = Value;
1206 } else if (ArgToken.isNot(tok::eod)) {
1207 PP.Diag(ArgToken, diag::warn_pragma_debug_unexpected_argument);
1208 }
1209
1210 PP.Diag(Tok, diag::remark_sloc_usage);
1211 PP.getSourceManager().noteSLocAddressSpaceUsage(PP.getDiagnostics(),
1212 MaxNotes);
1213 } else {
1214 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1215 << II->getName();
1216 }
1217
1218 PPCallbacks *Callbacks = PP.getPPCallbacks();
1219 if (Callbacks)
1220 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1221 }
1222
HandleCaptured__anon851a8f8a0311::PragmaDebugHandler1223 void HandleCaptured(Preprocessor &PP) {
1224 Token Tok;
1225 PP.LexUnexpandedToken(Tok);
1226
1227 if (Tok.isNot(tok::eod)) {
1228 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1229 << "pragma clang __debug captured";
1230 return;
1231 }
1232
1233 SourceLocation NameLoc = Tok.getLocation();
1234 MutableArrayRef<Token> Toks(
1235 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1236 Toks[0].startToken();
1237 Toks[0].setKind(tok::annot_pragma_captured);
1238 Toks[0].setLocation(NameLoc);
1239
1240 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1241 /*IsReinject=*/false);
1242 }
1243
1244 // Disable MSVC warning about runtime stack overflow.
1245 #ifdef _MSC_VER
1246 #pragma warning(disable : 4717)
1247 #endif
DebugOverflowStack__anon851a8f8a0311::PragmaDebugHandler1248 static void DebugOverflowStack(void (*P)() = nullptr) {
1249 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1250 Self(reinterpret_cast<void(*)()>(Self));
1251 }
1252 #ifdef _MSC_VER
1253 #pragma warning(default : 4717)
1254 #endif
1255 };
1256
1257 struct PragmaUnsafeBufferUsageHandler : public PragmaHandler {
PragmaUnsafeBufferUsageHandler__anon851a8f8a0311::PragmaUnsafeBufferUsageHandler1258 PragmaUnsafeBufferUsageHandler() : PragmaHandler("unsafe_buffer_usage") {}
HandlePragma__anon851a8f8a0311::PragmaUnsafeBufferUsageHandler1259 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1260 Token &FirstToken) override {
1261 Token Tok;
1262
1263 PP.LexUnexpandedToken(Tok);
1264 if (Tok.isNot(tok::identifier)) {
1265 PP.Diag(Tok, diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1266 return;
1267 }
1268
1269 IdentifierInfo *II = Tok.getIdentifierInfo();
1270 SourceLocation Loc = Tok.getLocation();
1271
1272 if (II->isStr("begin")) {
1273 if (PP.enterOrExitSafeBufferOptOutRegion(true, Loc))
1274 PP.Diag(Loc, diag::err_pp_double_begin_pragma_unsafe_buffer_usage);
1275 } else if (II->isStr("end")) {
1276 if (PP.enterOrExitSafeBufferOptOutRegion(false, Loc))
1277 PP.Diag(Loc, diag::err_pp_unmatched_end_begin_pragma_unsafe_buffer_usage);
1278 } else
1279 PP.Diag(Tok, diag::err_pp_pragma_unsafe_buffer_usage_syntax);
1280 }
1281 };
1282
1283 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1284 struct PragmaDiagnosticHandler : public PragmaHandler {
1285 private:
1286 const char *Namespace;
1287
1288 public:
PragmaDiagnosticHandler__anon851a8f8a0311::PragmaDiagnosticHandler1289 explicit PragmaDiagnosticHandler(const char *NS)
1290 : PragmaHandler("diagnostic"), Namespace(NS) {}
1291
HandlePragma__anon851a8f8a0311::PragmaDiagnosticHandler1292 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1293 Token &DiagToken) override {
1294 SourceLocation DiagLoc = DiagToken.getLocation();
1295 Token Tok;
1296 PP.LexUnexpandedToken(Tok);
1297 if (Tok.isNot(tok::identifier)) {
1298 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1299 return;
1300 }
1301 IdentifierInfo *II = Tok.getIdentifierInfo();
1302 PPCallbacks *Callbacks = PP.getPPCallbacks();
1303
1304 // Get the next token, which is either an EOD or a string literal. We lex
1305 // it now so that we can early return if the previous token was push or pop.
1306 PP.LexUnexpandedToken(Tok);
1307
1308 if (II->isStr("pop")) {
1309 if (!PP.getDiagnostics().popMappings(DiagLoc))
1310 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1311 else if (Callbacks)
1312 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1313
1314 if (Tok.isNot(tok::eod))
1315 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1316 return;
1317 } else if (II->isStr("push")) {
1318 PP.getDiagnostics().pushMappings(DiagLoc);
1319 if (Callbacks)
1320 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1321
1322 if (Tok.isNot(tok::eod))
1323 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1324 return;
1325 }
1326
1327 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1328 .Case("ignored", diag::Severity::Ignored)
1329 .Case("warning", diag::Severity::Warning)
1330 .Case("error", diag::Severity::Error)
1331 .Case("fatal", diag::Severity::Fatal)
1332 .Default(diag::Severity());
1333
1334 if (SV == diag::Severity()) {
1335 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1336 return;
1337 }
1338
1339 // At this point, we expect a string literal.
1340 SourceLocation StringLoc = Tok.getLocation();
1341 std::string WarningName;
1342 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1343 /*AllowMacroExpansion=*/false))
1344 return;
1345
1346 if (Tok.isNot(tok::eod)) {
1347 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1348 return;
1349 }
1350
1351 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1352 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1353 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1354 return;
1355 }
1356
1357 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1358 : diag::Flavor::Remark;
1359 StringRef Group = StringRef(WarningName).substr(2);
1360 bool unknownDiag = false;
1361 if (Group == "everything") {
1362 // Special handling for pragma clang diagnostic ... "-Weverything".
1363 // There is no formal group named "everything", so there has to be a
1364 // special case for it.
1365 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1366 } else
1367 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1368 DiagLoc);
1369 if (unknownDiag)
1370 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1371 << WarningName;
1372 else if (Callbacks)
1373 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1374 }
1375 };
1376
1377 /// "\#pragma hdrstop [<header-name-string>]"
1378 struct PragmaHdrstopHandler : public PragmaHandler {
PragmaHdrstopHandler__anon851a8f8a0311::PragmaHdrstopHandler1379 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
HandlePragma__anon851a8f8a0311::PragmaHdrstopHandler1380 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1381 Token &DepToken) override {
1382 PP.HandlePragmaHdrstop(DepToken);
1383 }
1384 };
1385
1386 /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1387 /// diagnostics, so we don't really implement this pragma. We parse it and
1388 /// ignore it to avoid -Wunknown-pragma warnings.
1389 struct PragmaWarningHandler : public PragmaHandler {
PragmaWarningHandler__anon851a8f8a0311::PragmaWarningHandler1390 PragmaWarningHandler() : PragmaHandler("warning") {}
1391
HandlePragma__anon851a8f8a0311::PragmaWarningHandler1392 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1393 Token &Tok) override {
1394 // Parse things like:
1395 // warning(push, 1)
1396 // warning(pop)
1397 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1398 SourceLocation DiagLoc = Tok.getLocation();
1399 PPCallbacks *Callbacks = PP.getPPCallbacks();
1400
1401 PP.Lex(Tok);
1402 if (Tok.isNot(tok::l_paren)) {
1403 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1404 return;
1405 }
1406
1407 PP.Lex(Tok);
1408 IdentifierInfo *II = Tok.getIdentifierInfo();
1409
1410 if (II && II->isStr("push")) {
1411 // #pragma warning( push[ ,n ] )
1412 int Level = -1;
1413 PP.Lex(Tok);
1414 if (Tok.is(tok::comma)) {
1415 PP.Lex(Tok);
1416 uint64_t Value;
1417 if (Tok.is(tok::numeric_constant) &&
1418 PP.parseSimpleIntegerLiteral(Tok, Value))
1419 Level = int(Value);
1420 if (Level < 0 || Level > 4) {
1421 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1422 return;
1423 }
1424 }
1425 PP.getDiagnostics().pushMappings(DiagLoc);
1426 if (Callbacks)
1427 Callbacks->PragmaWarningPush(DiagLoc, Level);
1428 } else if (II && II->isStr("pop")) {
1429 // #pragma warning( pop )
1430 PP.Lex(Tok);
1431 if (!PP.getDiagnostics().popMappings(DiagLoc))
1432 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1433 else if (Callbacks)
1434 Callbacks->PragmaWarningPop(DiagLoc);
1435 } else {
1436 // #pragma warning( warning-specifier : warning-number-list
1437 // [; warning-specifier : warning-number-list...] )
1438 while (true) {
1439 II = Tok.getIdentifierInfo();
1440 if (!II && !Tok.is(tok::numeric_constant)) {
1441 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1442 return;
1443 }
1444
1445 // Figure out which warning specifier this is.
1446 bool SpecifierValid;
1447 PPCallbacks::PragmaWarningSpecifier Specifier;
1448 if (II) {
1449 int SpecifierInt = llvm::StringSwitch<int>(II->getName())
1450 .Case("default", PPCallbacks::PWS_Default)
1451 .Case("disable", PPCallbacks::PWS_Disable)
1452 .Case("error", PPCallbacks::PWS_Error)
1453 .Case("once", PPCallbacks::PWS_Once)
1454 .Case("suppress", PPCallbacks::PWS_Suppress)
1455 .Default(-1);
1456 SpecifierValid = SpecifierInt != -1;
1457 if (SpecifierValid)
1458 Specifier =
1459 static_cast<PPCallbacks::PragmaWarningSpecifier>(SpecifierInt);
1460
1461 // If we read a correct specifier, snatch next token (that should be
1462 // ":", checked later).
1463 if (SpecifierValid)
1464 PP.Lex(Tok);
1465 } else {
1466 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1467 uint64_t Value;
1468 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1469 if ((SpecifierValid = (Value >= 1) && (Value <= 4)))
1470 Specifier = static_cast<PPCallbacks::PragmaWarningSpecifier>(
1471 PPCallbacks::PWS_Level1 + Value - 1);
1472 } else
1473 SpecifierValid = false;
1474 // Next token already snatched by parseSimpleIntegerLiteral.
1475 }
1476
1477 if (!SpecifierValid) {
1478 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1479 return;
1480 }
1481 if (Tok.isNot(tok::colon)) {
1482 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1483 return;
1484 }
1485
1486 // Collect the warning ids.
1487 SmallVector<int, 4> Ids;
1488 PP.Lex(Tok);
1489 while (Tok.is(tok::numeric_constant)) {
1490 uint64_t Value;
1491 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1492 Value > INT_MAX) {
1493 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1494 return;
1495 }
1496 Ids.push_back(int(Value));
1497 }
1498
1499 // Only act on disable for now.
1500 diag::Severity SV = diag::Severity();
1501 if (Specifier == PPCallbacks::PWS_Disable)
1502 SV = diag::Severity::Ignored;
1503 if (SV != diag::Severity())
1504 for (int Id : Ids) {
1505 if (auto Group = diagGroupFromCLWarningID(Id)) {
1506 bool unknownDiag = PP.getDiagnostics().setSeverityForGroup(
1507 diag::Flavor::WarningOrError, *Group, SV, DiagLoc);
1508 assert(!unknownDiag &&
1509 "wd table should only contain known diags");
1510 (void)unknownDiag;
1511 }
1512 }
1513
1514 if (Callbacks)
1515 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1516
1517 // Parse the next specifier if there is a semicolon.
1518 if (Tok.isNot(tok::semi))
1519 break;
1520 PP.Lex(Tok);
1521 }
1522 }
1523
1524 if (Tok.isNot(tok::r_paren)) {
1525 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1526 return;
1527 }
1528
1529 PP.Lex(Tok);
1530 if (Tok.isNot(tok::eod))
1531 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1532 }
1533 };
1534
1535 /// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1536 /// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1537 /// otherwise to avoid -Wunknown-pragma warnings.
1538 struct PragmaExecCharsetHandler : public PragmaHandler {
PragmaExecCharsetHandler__anon851a8f8a0311::PragmaExecCharsetHandler1539 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1540
HandlePragma__anon851a8f8a0311::PragmaExecCharsetHandler1541 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1542 Token &Tok) override {
1543 // Parse things like:
1544 // execution_character_set(push, "UTF-8")
1545 // execution_character_set(pop)
1546 SourceLocation DiagLoc = Tok.getLocation();
1547 PPCallbacks *Callbacks = PP.getPPCallbacks();
1548
1549 PP.Lex(Tok);
1550 if (Tok.isNot(tok::l_paren)) {
1551 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1552 return;
1553 }
1554
1555 PP.Lex(Tok);
1556 IdentifierInfo *II = Tok.getIdentifierInfo();
1557
1558 if (II && II->isStr("push")) {
1559 // #pragma execution_character_set( push[ , string ] )
1560 PP.Lex(Tok);
1561 if (Tok.is(tok::comma)) {
1562 PP.Lex(Tok);
1563
1564 std::string ExecCharset;
1565 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1566 "pragma execution_character_set",
1567 /*AllowMacroExpansion=*/false))
1568 return;
1569
1570 // MSVC supports either of these, but nothing else.
1571 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1572 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1573 return;
1574 }
1575 }
1576 if (Callbacks)
1577 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1578 } else if (II && II->isStr("pop")) {
1579 // #pragma execution_character_set( pop )
1580 PP.Lex(Tok);
1581 if (Callbacks)
1582 Callbacks->PragmaExecCharsetPop(DiagLoc);
1583 } else {
1584 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1585 return;
1586 }
1587
1588 if (Tok.isNot(tok::r_paren)) {
1589 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1590 return;
1591 }
1592
1593 PP.Lex(Tok);
1594 if (Tok.isNot(tok::eod))
1595 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1596 }
1597 };
1598
1599 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1600 struct PragmaIncludeAliasHandler : public PragmaHandler {
PragmaIncludeAliasHandler__anon851a8f8a0311::PragmaIncludeAliasHandler1601 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1602
HandlePragma__anon851a8f8a0311::PragmaIncludeAliasHandler1603 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1604 Token &IncludeAliasTok) override {
1605 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1606 }
1607 };
1608
1609 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1610 /// extension. The syntax is:
1611 /// \code
1612 /// #pragma message(string)
1613 /// \endcode
1614 /// OR, in GCC mode:
1615 /// \code
1616 /// #pragma message string
1617 /// \endcode
1618 /// string is a string, which is fully macro expanded, and permits string
1619 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1620 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1621 /// form as \#pragma message.
1622 struct PragmaMessageHandler : public PragmaHandler {
1623 private:
1624 const PPCallbacks::PragmaMessageKind Kind;
1625 const StringRef Namespace;
1626
PragmaKind__anon851a8f8a0311::PragmaMessageHandler1627 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1628 bool PragmaNameOnly = false) {
1629 switch (Kind) {
1630 case PPCallbacks::PMK_Message:
1631 return PragmaNameOnly ? "message" : "pragma message";
1632 case PPCallbacks::PMK_Warning:
1633 return PragmaNameOnly ? "warning" : "pragma warning";
1634 case PPCallbacks::PMK_Error:
1635 return PragmaNameOnly ? "error" : "pragma error";
1636 }
1637 llvm_unreachable("Unknown PragmaMessageKind!");
1638 }
1639
1640 public:
PragmaMessageHandler__anon851a8f8a0311::PragmaMessageHandler1641 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1642 StringRef Namespace = StringRef())
1643 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1644 Namespace(Namespace) {}
1645
HandlePragma__anon851a8f8a0311::PragmaMessageHandler1646 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1647 Token &Tok) override {
1648 SourceLocation MessageLoc = Tok.getLocation();
1649 PP.Lex(Tok);
1650 bool ExpectClosingParen = false;
1651 switch (Tok.getKind()) {
1652 case tok::l_paren:
1653 // We have a MSVC style pragma message.
1654 ExpectClosingParen = true;
1655 // Read the string.
1656 PP.Lex(Tok);
1657 break;
1658 case tok::string_literal:
1659 // We have a GCC style pragma message, and we just read the string.
1660 break;
1661 default:
1662 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1663 return;
1664 }
1665
1666 std::string MessageString;
1667 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1668 /*AllowMacroExpansion=*/true))
1669 return;
1670
1671 if (ExpectClosingParen) {
1672 if (Tok.isNot(tok::r_paren)) {
1673 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1674 return;
1675 }
1676 PP.Lex(Tok); // eat the r_paren.
1677 }
1678
1679 if (Tok.isNot(tok::eod)) {
1680 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1681 return;
1682 }
1683
1684 // Output the message.
1685 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1686 ? diag::err_pragma_message
1687 : diag::warn_pragma_message) << MessageString;
1688
1689 // If the pragma is lexically sound, notify any interested PPCallbacks.
1690 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1691 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1692 }
1693 };
1694
1695 /// Handle the clang \#pragma module import extension. The syntax is:
1696 /// \code
1697 /// #pragma clang module import some.module.name
1698 /// \endcode
1699 struct PragmaModuleImportHandler : public PragmaHandler {
PragmaModuleImportHandler__anon851a8f8a0311::PragmaModuleImportHandler1700 PragmaModuleImportHandler() : PragmaHandler("import") {}
1701
HandlePragma__anon851a8f8a0311::PragmaModuleImportHandler1702 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1703 Token &Tok) override {
1704 SourceLocation ImportLoc = Tok.getLocation();
1705
1706 // Read the module name.
1707 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1708 if (LexModuleName(PP, Tok, ModuleName))
1709 return;
1710
1711 if (Tok.isNot(tok::eod))
1712 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1713
1714 // If we have a non-empty module path, load the named module.
1715 Module *Imported =
1716 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1717 /*IsInclusionDirective=*/false);
1718 if (!Imported)
1719 return;
1720
1721 PP.makeModuleVisible(Imported, ImportLoc);
1722 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().getLoc()),
1723 tok::annot_module_include, Imported);
1724 if (auto *CB = PP.getPPCallbacks())
1725 CB->moduleImport(ImportLoc, ModuleName, Imported);
1726 }
1727 };
1728
1729 /// Handle the clang \#pragma module begin extension. The syntax is:
1730 /// \code
1731 /// #pragma clang module begin some.module.name
1732 /// ...
1733 /// #pragma clang module end
1734 /// \endcode
1735 struct PragmaModuleBeginHandler : public PragmaHandler {
PragmaModuleBeginHandler__anon851a8f8a0311::PragmaModuleBeginHandler1736 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1737
HandlePragma__anon851a8f8a0311::PragmaModuleBeginHandler1738 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1739 Token &Tok) override {
1740 SourceLocation BeginLoc = Tok.getLocation();
1741
1742 // Read the module name.
1743 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1744 if (LexModuleName(PP, Tok, ModuleName))
1745 return;
1746
1747 if (Tok.isNot(tok::eod))
1748 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1749
1750 // We can only enter submodules of the current module.
1751 StringRef Current = PP.getLangOpts().CurrentModule;
1752 if (ModuleName.front().getIdentifierInfo()->getName() != Current) {
1753 PP.Diag(ModuleName.front().getLoc(),
1754 diag::err_pp_module_begin_wrong_module)
1755 << ModuleName.front().getIdentifierInfo() << (ModuleName.size() > 1)
1756 << Current.empty() << Current;
1757 return;
1758 }
1759
1760 // Find the module we're entering. We require that a module map for it
1761 // be loaded or implicitly loadable.
1762 auto &HSI = PP.getHeaderSearchInfo();
1763 auto &MM = HSI.getModuleMap();
1764 Module *M = HSI.lookupModule(Current, ModuleName.front().getLoc());
1765 if (!M) {
1766 PP.Diag(ModuleName.front().getLoc(),
1767 diag::err_pp_module_begin_no_module_map)
1768 << Current;
1769 return;
1770 }
1771 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1772 auto *NewM = MM.findOrInferSubmodule(
1773 M, ModuleName[I].getIdentifierInfo()->getName());
1774 if (!NewM) {
1775 PP.Diag(ModuleName[I].getLoc(), diag::err_pp_module_begin_no_submodule)
1776 << M->getFullModuleName() << ModuleName[I].getIdentifierInfo();
1777 return;
1778 }
1779 M = NewM;
1780 }
1781
1782 // If the module isn't available, it doesn't make sense to enter it.
1783 if (Preprocessor::checkModuleIsAvailable(
1784 PP.getLangOpts(), PP.getTargetInfo(), *M, PP.getDiagnostics())) {
1785 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1786 << M->getTopLevelModuleName();
1787 return;
1788 }
1789
1790 // Enter the scope of the submodule.
1791 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1792 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().getLoc()),
1793 tok::annot_module_begin, M);
1794 }
1795 };
1796
1797 /// Handle the clang \#pragma module end extension.
1798 struct PragmaModuleEndHandler : public PragmaHandler {
PragmaModuleEndHandler__anon851a8f8a0311::PragmaModuleEndHandler1799 PragmaModuleEndHandler() : PragmaHandler("end") {}
1800
HandlePragma__anon851a8f8a0311::PragmaModuleEndHandler1801 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1802 Token &Tok) override {
1803 SourceLocation Loc = Tok.getLocation();
1804
1805 PP.LexUnexpandedToken(Tok);
1806 if (Tok.isNot(tok::eod))
1807 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1808
1809 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1810 if (M)
1811 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1812 else
1813 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1814 }
1815 };
1816
1817 /// Handle the clang \#pragma module build extension.
1818 struct PragmaModuleBuildHandler : public PragmaHandler {
PragmaModuleBuildHandler__anon851a8f8a0311::PragmaModuleBuildHandler1819 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1820
HandlePragma__anon851a8f8a0311::PragmaModuleBuildHandler1821 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1822 Token &Tok) override {
1823 PP.HandlePragmaModuleBuild(Tok);
1824 }
1825 };
1826
1827 /// Handle the clang \#pragma module load extension.
1828 struct PragmaModuleLoadHandler : public PragmaHandler {
PragmaModuleLoadHandler__anon851a8f8a0311::PragmaModuleLoadHandler1829 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1830
HandlePragma__anon851a8f8a0311::PragmaModuleLoadHandler1831 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1832 Token &Tok) override {
1833 SourceLocation Loc = Tok.getLocation();
1834
1835 // Read the module name.
1836 llvm::SmallVector<IdentifierLoc, 8> ModuleName;
1837 if (LexModuleName(PP, Tok, ModuleName))
1838 return;
1839
1840 if (Tok.isNot(tok::eod))
1841 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1842
1843 // Load the module, don't make it visible.
1844 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1845 /*IsInclusionDirective=*/false);
1846 }
1847 };
1848
1849 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1850 /// macro on the top of the stack.
1851 struct PragmaPushMacroHandler : public PragmaHandler {
PragmaPushMacroHandler__anon851a8f8a0311::PragmaPushMacroHandler1852 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1853
HandlePragma__anon851a8f8a0311::PragmaPushMacroHandler1854 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1855 Token &PushMacroTok) override {
1856 PP.HandlePragmaPushMacro(PushMacroTok);
1857 }
1858 };
1859
1860 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1861 /// macro to the value on the top of the stack.
1862 struct PragmaPopMacroHandler : public PragmaHandler {
PragmaPopMacroHandler__anon851a8f8a0311::PragmaPopMacroHandler1863 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1864
HandlePragma__anon851a8f8a0311::PragmaPopMacroHandler1865 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1866 Token &PopMacroTok) override {
1867 PP.HandlePragmaPopMacro(PopMacroTok);
1868 }
1869 };
1870
1871 /// PragmaARCCFCodeAuditedHandler -
1872 /// \#pragma clang arc_cf_code_audited begin/end
1873 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
PragmaARCCFCodeAuditedHandler__anon851a8f8a0311::PragmaARCCFCodeAuditedHandler1874 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1875
HandlePragma__anon851a8f8a0311::PragmaARCCFCodeAuditedHandler1876 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1877 Token &NameTok) override {
1878 SourceLocation Loc = NameTok.getLocation();
1879 bool IsBegin;
1880
1881 Token Tok;
1882
1883 // Lex the 'begin' or 'end'.
1884 PP.LexUnexpandedToken(Tok);
1885 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1886 if (BeginEnd && BeginEnd->isStr("begin")) {
1887 IsBegin = true;
1888 } else if (BeginEnd && BeginEnd->isStr("end")) {
1889 IsBegin = false;
1890 } else {
1891 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1892 return;
1893 }
1894
1895 // Verify that this is followed by EOD.
1896 PP.LexUnexpandedToken(Tok);
1897 if (Tok.isNot(tok::eod))
1898 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1899
1900 // The start location of the active audit.
1901 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().getLoc();
1902
1903 // The start location we want after processing this.
1904 SourceLocation NewLoc;
1905
1906 if (IsBegin) {
1907 // Complain about attempts to re-enter an audit.
1908 if (BeginLoc.isValid()) {
1909 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1910 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1911 }
1912 NewLoc = Loc;
1913 } else {
1914 // Complain about attempts to leave an audit that doesn't exist.
1915 if (!BeginLoc.isValid()) {
1916 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1917 return;
1918 }
1919 NewLoc = SourceLocation();
1920 }
1921
1922 PP.setPragmaARCCFCodeAuditedInfo(NameTok.getIdentifierInfo(), NewLoc);
1923 }
1924 };
1925
1926 /// PragmaAssumeNonNullHandler -
1927 /// \#pragma clang assume_nonnull begin/end
1928 struct PragmaAssumeNonNullHandler : public PragmaHandler {
PragmaAssumeNonNullHandler__anon851a8f8a0311::PragmaAssumeNonNullHandler1929 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1930
HandlePragma__anon851a8f8a0311::PragmaAssumeNonNullHandler1931 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1932 Token &NameTok) override {
1933 SourceLocation Loc = NameTok.getLocation();
1934 bool IsBegin;
1935
1936 Token Tok;
1937
1938 // Lex the 'begin' or 'end'.
1939 PP.LexUnexpandedToken(Tok);
1940 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1941 if (BeginEnd && BeginEnd->isStr("begin")) {
1942 IsBegin = true;
1943 } else if (BeginEnd && BeginEnd->isStr("end")) {
1944 IsBegin = false;
1945 } else {
1946 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1947 return;
1948 }
1949
1950 // Verify that this is followed by EOD.
1951 PP.LexUnexpandedToken(Tok);
1952 if (Tok.isNot(tok::eod))
1953 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1954
1955 // The start location of the active audit.
1956 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1957
1958 // The start location we want after processing this.
1959 SourceLocation NewLoc;
1960 PPCallbacks *Callbacks = PP.getPPCallbacks();
1961
1962 if (IsBegin) {
1963 // Complain about attempts to re-enter an audit.
1964 if (BeginLoc.isValid()) {
1965 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1966 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1967 }
1968 NewLoc = Loc;
1969 if (Callbacks)
1970 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
1971 } else {
1972 // Complain about attempts to leave an audit that doesn't exist.
1973 if (!BeginLoc.isValid()) {
1974 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1975 return;
1976 }
1977 NewLoc = SourceLocation();
1978 if (Callbacks)
1979 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
1980 }
1981
1982 PP.setPragmaAssumeNonNullLoc(NewLoc);
1983 }
1984 };
1985
1986 /// Handle "\#pragma region [...]"
1987 ///
1988 /// The syntax is
1989 /// \code
1990 /// #pragma region [optional name]
1991 /// #pragma endregion [optional comment]
1992 /// \endcode
1993 ///
1994 /// \note This is
1995 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1996 /// pragma, just skipped by compiler.
1997 struct PragmaRegionHandler : public PragmaHandler {
PragmaRegionHandler__anon851a8f8a0311::PragmaRegionHandler1998 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
1999
HandlePragma__anon851a8f8a0311::PragmaRegionHandler2000 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2001 Token &NameTok) override {
2002 // #pragma region: endregion matches can be verified
2003 // __pragma(region): no sense, but ignored by msvc
2004 // _Pragma is not valid for MSVC, but there isn't any point
2005 // to handle a _Pragma differently.
2006 }
2007 };
2008
2009 /// "\#pragma managed"
2010 /// "\#pragma managed(...)"
2011 /// "\#pragma unmanaged"
2012 /// MSVC ignores this pragma when not compiling using /clr, which clang doesn't
2013 /// support. We parse it and ignore it to avoid -Wunknown-pragma warnings.
2014 struct PragmaManagedHandler : public EmptyPragmaHandler {
PragmaManagedHandler__anon851a8f8a0311::PragmaManagedHandler2015 PragmaManagedHandler(const char *pragma) : EmptyPragmaHandler(pragma) {}
2016 };
2017
2018 /// This handles parsing pragmas that take a macro name and optional message
HandleMacroAnnotationPragma(Preprocessor & PP,Token & Tok,const char * Pragma,std::string & MessageString)2019 static IdentifierInfo *HandleMacroAnnotationPragma(Preprocessor &PP, Token &Tok,
2020 const char *Pragma,
2021 std::string &MessageString) {
2022 PP.Lex(Tok);
2023 if (Tok.isNot(tok::l_paren)) {
2024 PP.Diag(Tok, diag::err_expected) << "(";
2025 return nullptr;
2026 }
2027
2028 PP.LexUnexpandedToken(Tok);
2029 if (!Tok.is(tok::identifier)) {
2030 PP.Diag(Tok, diag::err_expected) << tok::identifier;
2031 return nullptr;
2032 }
2033 IdentifierInfo *II = Tok.getIdentifierInfo();
2034
2035 if (!II->hasMacroDefinition()) {
2036 PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2037 return nullptr;
2038 }
2039
2040 PP.Lex(Tok);
2041 if (Tok.is(tok::comma)) {
2042 PP.Lex(Tok);
2043 if (!PP.FinishLexStringLiteral(Tok, MessageString, Pragma,
2044 /*AllowMacroExpansion=*/true))
2045 return nullptr;
2046 }
2047
2048 if (Tok.isNot(tok::r_paren)) {
2049 PP.Diag(Tok, diag::err_expected) << ")";
2050 return nullptr;
2051 }
2052 return II;
2053 }
2054
2055 /// "\#pragma clang deprecated(...)"
2056 ///
2057 /// The syntax is
2058 /// \code
2059 /// #pragma clang deprecate(MACRO_NAME [, Message])
2060 /// \endcode
2061 struct PragmaDeprecatedHandler : public PragmaHandler {
PragmaDeprecatedHandler__anon851a8f8a0311::PragmaDeprecatedHandler2062 PragmaDeprecatedHandler() : PragmaHandler("deprecated") {}
2063
HandlePragma__anon851a8f8a0311::PragmaDeprecatedHandler2064 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2065 Token &Tok) override {
2066 std::string MessageString;
2067
2068 if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2069 PP, Tok, "#pragma clang deprecated", MessageString)) {
2070 II->setIsDeprecatedMacro(true);
2071 PP.addMacroDeprecationMsg(II, std::move(MessageString),
2072 Tok.getLocation());
2073 }
2074 }
2075 };
2076
2077 /// "\#pragma clang restrict_expansion(...)"
2078 ///
2079 /// The syntax is
2080 /// \code
2081 /// #pragma clang restrict_expansion(MACRO_NAME [, Message])
2082 /// \endcode
2083 struct PragmaRestrictExpansionHandler : public PragmaHandler {
PragmaRestrictExpansionHandler__anon851a8f8a0311::PragmaRestrictExpansionHandler2084 PragmaRestrictExpansionHandler() : PragmaHandler("restrict_expansion") {}
2085
HandlePragma__anon851a8f8a0311::PragmaRestrictExpansionHandler2086 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2087 Token &Tok) override {
2088 std::string MessageString;
2089
2090 if (IdentifierInfo *II = HandleMacroAnnotationPragma(
2091 PP, Tok, "#pragma clang restrict_expansion", MessageString)) {
2092 II->setIsRestrictExpansion(true);
2093 PP.addRestrictExpansionMsg(II, std::move(MessageString),
2094 Tok.getLocation());
2095 }
2096 }
2097 };
2098
2099 /// "\#pragma clang final(...)"
2100 ///
2101 /// The syntax is
2102 /// \code
2103 /// #pragma clang final(MACRO_NAME)
2104 /// \endcode
2105 struct PragmaFinalHandler : public PragmaHandler {
PragmaFinalHandler__anon851a8f8a0311::PragmaFinalHandler2106 PragmaFinalHandler() : PragmaHandler("final") {}
2107
HandlePragma__anon851a8f8a0311::PragmaFinalHandler2108 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
2109 Token &Tok) override {
2110 PP.Lex(Tok);
2111 if (Tok.isNot(tok::l_paren)) {
2112 PP.Diag(Tok, diag::err_expected) << "(";
2113 return;
2114 }
2115
2116 PP.LexUnexpandedToken(Tok);
2117 if (!Tok.is(tok::identifier)) {
2118 PP.Diag(Tok, diag::err_expected) << tok::identifier;
2119 return;
2120 }
2121 IdentifierInfo *II = Tok.getIdentifierInfo();
2122
2123 if (!II->hasMacroDefinition()) {
2124 PP.Diag(Tok, diag::err_pp_visibility_non_macro) << II;
2125 return;
2126 }
2127
2128 PP.Lex(Tok);
2129 if (Tok.isNot(tok::r_paren)) {
2130 PP.Diag(Tok, diag::err_expected) << ")";
2131 return;
2132 }
2133 II->setIsFinal(true);
2134 PP.addFinalLoc(II, Tok.getLocation());
2135 }
2136 };
2137
2138 } // namespace
2139
2140 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
2141 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
RegisterBuiltinPragmas()2142 void Preprocessor::RegisterBuiltinPragmas() {
2143 AddPragmaHandler(new PragmaOnceHandler());
2144 AddPragmaHandler(new PragmaMarkHandler());
2145 AddPragmaHandler(new PragmaPushMacroHandler());
2146 AddPragmaHandler(new PragmaPopMacroHandler());
2147 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
2148
2149 // #pragma GCC ...
2150 AddPragmaHandler("GCC", new PragmaPoisonHandler());
2151 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
2152 AddPragmaHandler("GCC", new PragmaDependencyHandler());
2153 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
2154 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
2155 "GCC"));
2156 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
2157 "GCC"));
2158 // #pragma clang ...
2159 AddPragmaHandler("clang", new PragmaPoisonHandler());
2160 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
2161 AddPragmaHandler("clang", new PragmaDebugHandler());
2162 AddPragmaHandler("clang", new PragmaDependencyHandler());
2163 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
2164 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
2165 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
2166 AddPragmaHandler("clang", new PragmaDeprecatedHandler());
2167 AddPragmaHandler("clang", new PragmaRestrictExpansionHandler());
2168 AddPragmaHandler("clang", new PragmaFinalHandler());
2169
2170 // #pragma clang module ...
2171 auto *ModuleHandler = new PragmaNamespace("module");
2172 AddPragmaHandler("clang", ModuleHandler);
2173 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
2174 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
2175 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
2176 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
2177 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
2178
2179 // Safe Buffers pragmas
2180 AddPragmaHandler("clang", new PragmaUnsafeBufferUsageHandler);
2181
2182 // Add region pragmas.
2183 AddPragmaHandler(new PragmaRegionHandler("region"));
2184 AddPragmaHandler(new PragmaRegionHandler("endregion"));
2185
2186 // MS extensions.
2187 if (LangOpts.MicrosoftExt) {
2188 AddPragmaHandler(new PragmaWarningHandler());
2189 AddPragmaHandler(new PragmaExecCharsetHandler());
2190 AddPragmaHandler(new PragmaIncludeAliasHandler());
2191 AddPragmaHandler(new PragmaHdrstopHandler());
2192 AddPragmaHandler(new PragmaSystemHeaderHandler());
2193 AddPragmaHandler(new PragmaManagedHandler("managed"));
2194 AddPragmaHandler(new PragmaManagedHandler("unmanaged"));
2195 }
2196
2197 // Pragmas added by plugins
2198 for (const PragmaHandlerRegistry::entry &handler :
2199 PragmaHandlerRegistry::entries()) {
2200 AddPragmaHandler(handler.instantiate().release());
2201 }
2202 }
2203
2204 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
2205 /// warn about those pragmas being unknown.
IgnorePragmas()2206 void Preprocessor::IgnorePragmas() {
2207 AddPragmaHandler(new EmptyPragmaHandler());
2208 // Also ignore all pragmas in all namespaces created
2209 // in Preprocessor::RegisterBuiltinPragmas().
2210 AddPragmaHandler("GCC", new EmptyPragmaHandler());
2211 AddPragmaHandler("clang", new EmptyPragmaHandler());
2212 }
2213