https://github.com/ChenMiaoi created
https://github.com/llvm/llvm-project/pull/246726
Executing a nested pragma while reading the enclosing pragma's arguments can
inject annotation tokens where ordinary tokens are expected.
Track when a pragma is active so the preprocessor can diagnose and skip nested
pragmas. Expand deferred pragma arguments while the pragma is active and
disable macro expansion when replaying those tokens.
For example:
``` cc
#pragma clang attribute (_Pragma("clang attribute push"))
```
Clang emits:
```text
attribute.cc:1:26: error: nested pragma is not allowed
1 | #pragma clang attribute (_Pragma("clang attribute push"))
| ^
```
Fixes #225035
>From 8b1b4cae8c45ccb3265475cea773f642470fb53b Mon Sep 17 00:00:00 2001
From: Chen Miao <[email protected]>
Date: Sat, 28 Nov 2026 02:57:21 +0800
Subject: [PATCH] [clang][lex] Reject nested pragmas during preprocessing
Executing a nested pragma while reading the enclosing pragma's arguments
can inject annotation tokens where ordinary tokens are expected.
Track when a pragma is active so the preprocessor can diagnose and skip
nested pragmas. Expand deferred pragma arguments while the pragma is
active and disable macro expansion when replaying those tokens.
For example:
``` cc
#pragma clang attribute (_Pragma("clang attribute push"))
```
Clang emits:
```text
attribute.cc:1:26: error: nested pragma is not allowed
1 | #pragma clang attribute (_Pragma("clang attribute push"))
| ^
```
Fixes #225035
---
clang/docs/ReleaseNotes.md | 4 +
.../include/clang/Basic/DiagnosticLexKinds.td | 1 +
clang/include/clang/Lex/Preprocessor.h | 30 +++-
clang/lib/Lex/PPDirectives.cpp | 4 +
clang/lib/Lex/PPMacroExpansion.cpp | 10 +-
clang/lib/Lex/Pragma.cpp | 154 +++++++++++++-----
clang/lib/Parse/ParsePragma.cpp | 8 +-
clang/test/OpenMP/assumes_messages.c | 10 +-
clang/test/OpenMP/openmp_check.cpp | 6 +-
clang/test/Preprocessor/pragma-nested.c | 78 +++++++++
10 files changed, 241 insertions(+), 64 deletions(-)
create mode 100644 clang/test/Preprocessor/pragma-nested.c
diff --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index f8115a8aff6afa..7f6a00cbebaa03 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -48,6 +48,10 @@ The previous behavior can be restored with
`-Wno-error=unicode-whitespace`.
Clang will stop accepting non-ascii whitespaces as token separators
in a future version of Clang.
+- Clang now rejects nested pragmas during preprocessing instead of attempting
+ to execute them, which previously could cause crashes or unexpected behavior.
+ (#GH225035)
+
### C++ Specific Potentially Breaking Changes
- The `[[carries_dependency]]` attribute is no longer recognized, in any
language
diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td
b/clang/include/clang/Basic/DiagnosticLexKinds.td
index a75c7ddd66cb87..092f42f33be213 100644
--- a/clang/include/clang/Basic/DiagnosticLexKinds.td
+++ b/clang/include/clang/Basic/DiagnosticLexKinds.td
@@ -713,6 +713,7 @@ def warn_pragma_exec_charset_push_invalid :
def err__Pragma_malformed : Error<
"_Pragma takes a parenthesized string literal">;
+def err_nested_pragma : Error<"nested pragma is not allowed">;
def err_pragma_message_malformed : Error<
"pragma %select{message|warning|error}0 requires parenthesized string">;
def err_pragma_push_pop_macro_malformed : Error<
diff --git a/clang/include/clang/Lex/Preprocessor.h
b/clang/include/clang/Lex/Preprocessor.h
index 8d15ed7e8afd85..a3ae068f5851f1 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -305,6 +305,21 @@ class Preprocessor {
/// True if we are pre-expanding macro arguments.
bool InMacroArgPreExpansion;
+ /// Tracks pragma lexing state to reject nested pragmas.
+ enum class PragmaLexingState {
+ /// Not lexing a pragma.
+ None,
+ /// Lexing a pragma directive or operator; nested pragmas are rejected.
+ Active,
+ /// Skipping a rejected nested pragma's operand without executing or
+ /// re-diagnosing inner pragmas.
+ SkippingNested,
+ /// Recovering from a malformed _Pragma; same-line operators are rejected,
+ /// while a line-start directive or pragma operator ends recovery.
+ Recovering,
+ };
+ PragmaLexingState PragmaState = PragmaLexingState::None;
+
/// Mapping/lookup information for all identifiers in
/// the program, including program keywords.
mutable IdentifierTable Identifiers;
@@ -2821,14 +2836,21 @@ class Preprocessor {
/// as a builtin macro, handle it and return the next token as 'Tok'.
void ExpandBuiltinMacro(Token &Tok);
- /// Read a \c _Pragma directive, slice it up, process it, then
- /// return the first token after the directive.
+ /// Process a \c _Pragma or Microsoft \c __pragma operator.
+ /// This assumes that the pragma operator token has just been read into
+ /// \p Tok. Returns true if \p Tok holds a token to deliver, or false if
+ /// lexing should continue.
+ bool HandlePragmaOperator(Token &Tok, bool IsMicrosoft);
+
+ /// Read a \c _Pragma directive, slice it up, and process it.
/// This assumes that the \c _Pragma token has just been read into \p Tok.
- void Handle_Pragma(Token &Tok);
+ /// Returns true if \p Tok holds a token to deliver, or false if lexing
+ /// should continue.
+ bool Handle_Pragma(Token &Tok);
/// Like Handle_Pragma except the pragma text is not enclosed within
/// a string literal.
- void HandleMicrosoft__pragma(Token &Tok);
+ bool HandleMicrosoft__pragma(Token &Tok);
/// Add a lexer to the top of the include stack and
/// start lexing tokens from it instead of the current buffer.
diff --git a/clang/lib/Lex/PPDirectives.cpp b/clang/lib/Lex/PPDirectives.cpp
index ecb9e42c88bc0d..e89372313472c4 100644
--- a/clang/lib/Lex/PPDirectives.cpp
+++ b/clang/lib/Lex/PPDirectives.cpp
@@ -1316,6 +1316,10 @@ void
Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
/// lexer/preprocessor state, and advances the lexer(s) so that the next token
/// read is the correct one.
void Preprocessor::HandleDirective(Token &Result) {
+ // Reaching a new line-start directive ends malformed _Pragma recovery.
+ if (PragmaState == PragmaLexingState::Recovering)
+ PragmaState = PragmaLexingState::None;
+
// FIXME: Traditional: # with whitespace before it not recognized by K&R?
// We just parsed a # or @ character at the start of a line, so we're in
diff --git a/clang/lib/Lex/PPMacroExpansion.cpp
b/clang/lib/Lex/PPMacroExpansion.cpp
index bce83b27298f88..839ad72a5829fa 100644
--- a/clang/lib/Lex/PPMacroExpansion.cpp
+++ b/clang/lib/Lex/PPMacroExpansion.cpp
@@ -440,6 +440,9 @@ bool Preprocessor::HandleMacroExpandedIdentifier(Token
&Identifier,
if (Callbacks)
Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
/*Args=*/nullptr);
+ IdentifierInfo *II = Identifier.getIdentifierInfo();
+ if (II == Ident_Pragma || II == Ident__pragma)
+ return HandlePragmaOperator(Identifier, II == Ident__pragma);
ExpandBuiltinMacro(Identifier);
return true;
}
@@ -1601,13 +1604,6 @@ void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
assert(II && "Can't be a macro without id info!");
SourceLocation MacroNameLoc = Tok.getLocation();
- // If this is an _Pragma or Microsoft __pragma directive, expand it,
- // invoke the pragma handler, then lex the token after it.
- if (II == Ident_Pragma)
- return Handle_Pragma(Tok);
- else if (II == Ident__pragma) // in non-MS mode this is null
- return HandleMicrosoft__pragma(Tok);
-
++NumBuiltinMacroExpanded;
SmallString<128> TmpBuffer;
diff --git a/clang/lib/Lex/Pragma.cpp b/clang/lib/Lex/Pragma.cpp
index 078842ab08c5ef..4cce3c23b37b84 100644
--- a/clang/lib/Lex/Pragma.cpp
+++ b/clang/lib/Lex/Pragma.cpp
@@ -39,6 +39,7 @@
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/Timer.h"
#include <algorithm>
#include <cassert>
@@ -162,6 +163,17 @@ struct TokenCollector {
/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
/// rest of the pragma, passing it to the registered pragma handlers.
void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
+ // _Pragma/__pragma are checked in HandlePragmaOperator before reaching here.
+ if (Introducer.Kind == PIK_HashPragma &&
+ PragmaState != PragmaLexingState::None) {
+ if (PragmaState == PragmaLexingState::Active)
+ Diag(Introducer.Loc, diag::err_nested_pragma);
+ DiscardUntilEndOfDirective();
+ return;
+ }
+
+ llvm::SaveAndRestore RestorePragmaState(PragmaState,
+ PragmaLexingState::Active);
if (Callbacks)
Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
@@ -175,15 +187,61 @@ void Preprocessor::HandlePragmaDirective(PragmaIntroducer
Introducer) {
PragmaHandlers->HandlePragma(*this, Introducer, Tok);
// If the pragma handler didn't read the rest of the line, consume it now.
- if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
- || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
+ // Preserve deferred #pragma clang __debug dump/parser_crash token streams.
+ auto IsDeferredDebugAnnotation = [&]() {
+ std::optional<Token> Next = CurTokenLexer->peekNextPPToken();
+ return Next && Next->isOneOf(tok::annot_pragma_dump,
+ tok::annot_pragma_parser_crash);
+ };
+ if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective() &&
+ !IsDeferredDebugAnnotation()) ||
+ (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
DiscardUntilEndOfDirective();
}
-/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
-/// return the first token after the directive. The _Pragma token has just
-/// been read into 'Tok'.
-void Preprocessor::Handle_Pragma(Token &Tok) {
+bool Preprocessor::HandlePragmaOperator(Token &Tok, bool IsMicrosoft) {
+ if (PragmaState == PragmaLexingState::SkippingNested)
+ return true;
+
+ if (PragmaState == PragmaLexingState::Recovering && Tok.isAtStartOfLine())
+ PragmaState = PragmaLexingState::None;
+
+ // During argument pre-expansion the operator is only checked and put
+ // back. Diagnose it later if it survives macro replacement.
+ if ((PragmaState == PragmaLexingState::Active ||
+ PragmaState == PragmaLexingState::Recovering) &&
+ !InMacroArgPreExpansion) {
+ Diag(Tok, diag::err_nested_pragma);
+ // Recover through the operand without executing another pragma. Keep
+ // expanding other macros, which can supply the operand's parentheses.
+ llvm::SaveAndRestore SkipNested(PragmaState,
+ PragmaLexingState::SkippingNested);
+ Lex(Tok);
+ if (Tok.isNot(tok::l_paren))
+ return true;
+
+ // Skip through the operand's matching ')', leaving later tokens unread.
+ unsigned Depth = 1;
+ do {
+ Lex(Tok);
+ if (Tok.isOneOf(tok::eod, tok::eof))
+ return true;
+ if (Tok.is(tok::l_paren))
+ ++Depth;
+ else if (Tok.is(tok::r_paren))
+ --Depth;
+ } while (Depth);
+ return false;
+ }
+
+ // Restore the state before lexing past the operator, where another pragma
+ // may immediately follow it.
+ llvm::SaveAndRestore RestorePragmaState(PragmaState,
+ PragmaLexingState::Active);
+ return IsMicrosoft ? HandleMicrosoft__pragma(Tok) : Handle_Pragma(Tok);
+}
+
+bool Preprocessor::Handle_Pragma(Token &Tok) {
// C11 6.10.3.4/3:
// all pragma unary operator expressions within [a completely
// macro-replaced preprocessing token sequence] are [...] processed [after
@@ -213,32 +271,39 @@ void Preprocessor::Handle_Pragma(Token &Tok) {
Toks.lex();
if (Tok.isNot(tok::l_paren)) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
- return;
+ return true;
}
// Read the '"..."'.
Toks.lex();
+ bool IsRecovering = !InMacroArgPreExpansion;
+ PragmaLexingState RecoveryState =
+ IsRecovering ? PragmaLexingState::Recovering : PragmaState;
if (!tok::isStringLiteral(Tok.getKind())) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
// Skip bad tokens, and the ')', if present.
- if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof) && Tok.isNot(tok::eod))
+ llvm::SaveAndRestore Recover(PragmaState, RecoveryState);
+ if (!Tok.isOneOf(tok::r_paren, tok::eof, tok::eod))
Lex(Tok);
- while (Tok.isNot(tok::r_paren) &&
- !Tok.isAtStartOfLine() &&
- Tok.isNot(tok::eof) && Tok.isNot(tok::eod))
+ while ((!IsRecovering || PragmaState == PragmaLexingState::Recovering) &&
+ !Tok.isOneOf(tok::r_paren, tok::eof, tok::eod) &&
+ !Tok.isAtStartOfLine())
Lex(Tok);
- if (Tok.is(tok::r_paren))
- Lex(Tok);
- return;
+ // Recovery ended at a new line-start directive or pragma; deliver Tok
+ // instead of consuming a ')' that belongs to that line.
+ if (IsRecovering && PragmaState != PragmaLexingState::Recovering)
+ return true;
+ return Tok.isNot(tok::r_paren);
}
if (Tok.hasUDSuffix()) {
Diag(Tok, diag::err_invalid_string_udl);
// Skip this token, and the ')', if present.
+ llvm::SaveAndRestore Recover(PragmaState, RecoveryState);
Lex(Tok);
- if (Tok.is(tok::r_paren))
- Lex(Tok);
- return;
+ if (IsRecovering && PragmaState != PragmaLexingState::Recovering)
+ return true;
+ return Tok.isNot(tok::r_paren);
}
// Remember the string.
@@ -248,13 +313,13 @@ void Preprocessor::Handle_Pragma(Token &Tok) {
Toks.lex();
if (Tok.isNot(tok::r_paren)) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
- return;
+ return true;
}
// If we're expanding a macro argument, put the tokens back.
if (InMacroArgPreExpansion) {
Toks.revert();
- return;
+ return true;
}
SourceLocation RParenLoc = Tok.getLocation();
@@ -264,7 +329,7 @@ void Preprocessor::Handle_Pragma(Token &Tok) {
StringRef StrValRef = getSpelling(StrTok, StrVal, &Invalid);
if (Invalid) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
- return;
+ return true;
}
assert(StrValRef.size() <= StrVal.size());
@@ -296,8 +361,7 @@ void Preprocessor::Handle_Pragma(Token &Tok) {
// With everything set up, lex this as a #pragma directive.
HandlePragmaDirective({PIK__Pragma, PragmaLoc});
- // Finally, return whatever came after the pragma directive.
- return Lex(Tok);
+ return false;
}
void clang::prepare_PragmaString(SmallVectorImpl<char> &StrVal) {
@@ -352,7 +416,7 @@ void clang::prepare_PragmaString(SmallVectorImpl<char>
&StrVal) {
/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
/// is not enclosed within a string literal.
-void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
+bool Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
// During macro pre-expansion, check the syntax now but put the tokens back
// into the token stream for later consumption. Same as Handle_Pragma.
TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
@@ -364,14 +428,14 @@ void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
Toks.lex();
if (Tok.isNot(tok::l_paren)) {
Diag(PragmaLoc, diag::err__Pragma_malformed);
- return;
+ return true;
}
// Get the tokens enclosed within the __pragma(), as well as the final ')'.
SmallVector<Token, 32> PragmaToks;
int NumParens = 0;
Toks.lex();
- while (Tok.isNot(tok::eof)) {
+ while (!Tok.isOneOf(tok::eod, tok::eof)) {
PragmaToks.push_back(Tok);
if (Tok.is(tok::l_paren))
NumParens++;
@@ -380,15 +444,15 @@ void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
Toks.lex();
}
- if (Tok.is(tok::eof)) {
+ if (Tok.isOneOf(tok::eod, tok::eof)) {
Diag(PragmaLoc, diag::err_unterminated___pragma);
- return;
+ return true;
}
// If we're expanding a macro argument, put the tokens back.
if (InMacroArgPreExpansion) {
Toks.revert();
- return;
+ return true;
}
PragmaToks.front().setFlag(Token::LeadingSpace);
@@ -406,8 +470,7 @@ void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
// With everything set up, lex this as a #pragma directive.
HandlePragmaDirective({PIK___pragma, PragmaLoc});
- // Finally, return whatever came after the pragma directive.
- return Lex(Tok);
+ return false;
}
/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
@@ -1113,18 +1176,14 @@ struct PragmaDebugHandler : public PragmaHandler {
llvm::TimeRegion R(&T);
if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash)
LLVM_BUILTIN_TRAP;
- } else if (II->isStr("parser_crash")) {
- if (!PP.getPreprocessorOpts().DisablePragmaDebugCrash) {
- Token Crasher = Token::createAnnotation(tok::annot_pragma_parser_crash,
- Tok.getLocation());
- PP.EnterToken(Crasher, /*IsReinject*/ false);
- }
+ } else if (II->isStr("parser_crash") || II->isStr("dump")) {
+ bool IsDump = II->isStr("dump");
+ if (IsDump || !PP.getPreprocessorOpts().DisablePragmaDebugCrash)
+ HandleParserAnnotation(PP, Tok,
+ IsDump ? tok::annot_pragma_dump
+ : tok::annot_pragma_parser_crash);
} else if (II->isStr("sleep")) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
- } else if (II->isStr("dump")) {
- Token DumpAnnot =
- Token::createAnnotation(tok::annot_pragma_dump, Tok.getLocation());
- PP.EnterToken(DumpAnnot, /*IsReinject*/false);
} else if (II->isStr("diag_mapping")) {
Token DiagName;
PP.LexUnexpandedToken(DiagName);
@@ -1270,6 +1329,21 @@ struct PragmaDebugHandler : public PragmaHandler {
Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
}
+ static void HandleParserAnnotation(Preprocessor &PP, const Token &Command,
+ tok::TokenKind Kind) {
+ // Expand the arguments while the pragma is active. The parser consumes
+ // them after the handler returns.
+ SmallVector<Token, 8> Args;
+ Args.push_back(Token::createAnnotation(Kind, Command.getLocation()));
+ do {
+ PP.Lex(Args.emplace_back());
+ } while (!Args.back().isOneOf(tok::eod, tok::eof));
+ auto Tokens = std::make_unique<Token[]>(Args.size());
+ std::copy(Args.begin(), Args.end(), Tokens.get());
+ PP.EnterTokenStream(std::move(Tokens), Args.size(),
+ /*DisableMacroExpansion=*/true, /*IsReinject=*/false);
+ }
+
void HandleCaptured(Preprocessor &PP) {
Token Tok;
PP.LexUnexpandedToken(Tok);
diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp
index 0b13731e3d8bbc..6e5b5e807e583e 100644
--- a/clang/lib/Parse/ParsePragma.cpp
+++ b/clang/lib/Parse/ParsePragma.cpp
@@ -1591,7 +1591,7 @@ bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
<< PragmaLoopHintString(Info->PragmaName, Info->Option);
Hint.StateLoc = new (Actions.Context) IdentifierLoc(StateLoc, StateInfo);
} else if (OptionInfo && OptionInfo->getName() == "vectorize_width") {
- PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
+ PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
ConsumeAnnotationToken();
@@ -1660,7 +1660,7 @@ bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
}
} else {
// Enter constant expression including eof terminator into token stream.
- PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
+ PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
ConsumeAnnotationToken();
ExprResult R = ParseConstantExpression();
@@ -1977,7 +1977,7 @@ void Parser::HandlePragmaAttribute() {
return;
}
- PP.EnterTokenStream(Info->Tokens, /*DisableMacroExpansion=*/false,
+ PP.EnterTokenStream(Info->Tokens, /*DisableMacroExpansion=*/true,
/*IsReinject=*/false);
ConsumeAnnotationToken();
@@ -2833,7 +2833,7 @@ void PragmaSupportHandler<StartTok, EndTok,
UnexpectedDiag>::HandlePragma(
auto Toks = std::make_unique<Token[]>(Pragma.size());
std::copy(Pragma.begin(), Pragma.end(), Toks.get());
PP.EnterTokenStream(std::move(Toks), Pragma.size(),
- /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
+ /*DisableMacroExpansion=*/true, /*IsReinject=*/false);
}
/// Handle '#pragma pointers_to_members'
diff --git a/clang/test/OpenMP/assumes_messages.c
b/clang/test/OpenMP/assumes_messages.c
index 4d63cc2e8aca5e..9bbedf59b77fc6 100644
--- a/clang/test/OpenMP/assumes_messages.c
+++ b/clang/test/OpenMP/assumes_messages.c
@@ -59,14 +59,8 @@
#pragma omp begin assumes ext // expected-warning {{valid begin assumes
clauses start with 'ext_', 'absent', 'contains', 'holds', 'no_openmp',
'no_openmp_routines', 'no_openmp_constructs', 'no_parallelism'; token will be
ignored}}
#pragma omp end assumes
-// FIXME: We should be getting an expected note about where the span of ignored
-// tokens ends. However, error recovery ends up lexing the 'not' token,
-// emitting a (silenced) diagnostic about use of a C++ keyword in C, and the
-// note gets associated with *that* (silenced) diagnostic. This is an existing
-// issue that also happens with error recovery of reserved identifiers or
-// extension tokens, but is unfortunate nonetheless.
-#pragma omp assumes ext_123(not allowed) // expected-warning {{'ext_123'
clause should not be followed by arguments; tokens will be ignored}}
-#pragma omp begin assumes ext_123(not allowed) // expected-warning {{'ext_123'
clause should not be followed by arguments; tokens will be ignored}}
+#pragma omp assumes ext_123(not allowed) // expected-warning {{'ext_123'
clause should not be followed by arguments; tokens will be ignored}}
expected-note {{the ignored tokens spans until here}}
+#pragma omp begin assumes ext_123(not allowed) // expected-warning {{'ext_123'
clause should not be followed by arguments; tokens will be ignored}}
expected-note {{the ignored tokens spans until here}}
#pragma omp end assumes
#pragma omp end assumes // expected-error {{'#pragma omp end assumes' with no
matching '#pragma omp begin assumes'}}
diff --git a/clang/test/OpenMP/openmp_check.cpp
b/clang/test/OpenMP/openmp_check.cpp
index b52ce0c066922a..e85876d4b28b7f 100644
--- a/clang/test/OpenMP/openmp_check.cpp
+++ b/clang/test/OpenMP/openmp_check.cpp
@@ -8,9 +8,13 @@
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
#define p _Pragma("omp parallel")
+#define L (
+#define NESTED_PRAGMA() _Pragma("message(\"escaped\")")
int nested(int a) {
-#pragma omp parallel p // expected-error {{unexpected OpenMP directive}}
+#pragma omp parallel p // expected-error {{nested pragma is not allowed}}
+ ++a;
+#pragma omp parallel NESTED_PRAGMA L ) // expected-warning {{extra tokens at
the end of '#pragma omp parallel' are ignored}}
++a;
#pragma omp parallel
++a;
diff --git a/clang/test/Preprocessor/pragma-nested.c
b/clang/test/Preprocessor/pragma-nested.c
new file mode 100644
index 00000000000000..38b06d787e89d7
--- /dev/null
+++ b/clang/test/Preprocessor/pragma-nested.c
@@ -0,0 +1,78 @@
+// RUN: %clang_cc1 -fsyntax-only -fms-extensions -verify
-verify-ignore-unexpected=note %s
+// RUN: %clang_cc1 -x c++ -fsyntax-only -fms-extensions -verify
-verify-ignore-unexpected=note %s
+
+#pragma clang attribute (_Pragma("clang attribute push")) // expected-error
{{nested pragma is not allowed}} expected-error {{expected an attribute}}
+#pragma clang __debug dump _Pragma("message(\"inner\")") // expected-error
{{nested pragma is not allowed}} expected-warning {{missing argument to debug
command 'dump'}}
+
+#define OPEN (
+#define INNER _Pragma OPEN "message(\"inner\")")
+_Pragma(INNER "message(\"outer\")") // expected-error {{nested pragma is not
allowed}} expected-warning {{outer}}
+_Pragma(bad _Pragma("message(\"inner\")")) // expected-error {{_Pragma takes a
parenthesized string literal}} expected-error {{nested pragma is not allowed}}
+_Pragma(bad // expected-error {{_Pragma takes a parenthesized string literal}}
+_Pragma("message(\"next\")") int after_next; // expected-warning {{next}}
+int *use_after_next = &after_next;
+
+#define EMPTY
+_Pragma(bad EMPTY // expected-error {{_Pragma takes a parenthesized string
literal}}
+int keep_decl;
+int *use_keep_decl = &keep_decl;
+
+_Pragma(bad // expected-error {{_Pragma takes a parenthesized string literal}}
+#pragma message("after") // expected-warning {{after}}
+int keep_after_hash;
+int *use_keep_after_hash = &keep_after_hash;
+
+#define FLAG 1
+#pragma push_macro("FLAG")
+#undef FLAG
+_Pragma(bad // expected-error {{_Pragma takes a parenthesized string literal}}
+#if _Pragma("pop_macro(\"FLAG\")") FLAG
+int keep_selected;
+#else
+int wrong_branch;
+#endif
+int *use_keep_selected = &keep_selected;
+
+#ifdef __cplusplus
+_Pragma("bad"_x _Pragma("message(\"inner\")")) // expected-error {{string
literal with user-defined suffix cannot be used here}} expected-error {{nested
pragma is not allowed}}
+#define R )
+_Pragma("bad"_x R // expected-error {{string literal with user-defined suffix
cannot be used here}}
+_Pragma("bad"_x // expected-error {{string literal with user-defined suffix
cannot be used here}}
+_Pragma("message(\"after_udl\")") int keep_after_udl; // expected-warning
{{after_udl}}
+int *use_keep_after_udl = &keep_after_udl;
+#endif
+
+#define L (
+#define F() _Pragma("message(\"escaped\")")
+#pragma clang attribute push(F L )) // expected-error {{expected an attribute}}
+void loop_replay(void) {
+#ifdef __cplusplus
+#pragma clang loop unroll_count(F L )) // expected-error {{'F' is defined as a
function-like macro; did you mean 'F(...)'?}}
+#else
+#pragma clang loop unroll_count(F L )) // expected-error {{call to undeclared
function 'F'}} expected-error {{expression is not an integer constant
expression}}
+#endif
+ for (int i = 0; i < 4; ++i)
+ ;
+}
+
+#define PASS(x) x
+#define DROP(x)
+#define FORWARD_TO_DROP(x) DROP(x)
+#pragma message("outer" PASS(_Pragma("message(\"inner\")"))) // expected-error
{{nested pragma is not allowed}} expected-warning {{outer}}
+#pragma message("outer" FORWARD_TO_DROP(_Pragma("message(\"inner\")"))) //
expected-warning {{outer}}
+
+_Pragma("message(_Pragma(\"message(\\\"inner\\\")\") \"outer\")") //
expected-error {{nested pragma is not allowed}} expected-warning {{outer}}
+__pragma(message("outer" __pragma(message("inner")))) // expected-error
{{nested pragma is not allowed}} expected-warning {{outer}}
+
+_Pragma(
+#pragma message("inner") // expected-error {{nested pragma is not allowed}}
+ "message(\"outer\")") // expected-warning@-2 {{outer}}
+
+#pragma message("outer" _Pragma("message(\"inner\")" // expected-error
{{nested pragma is not allowed}} expected-error {{pragma message requires
parenthesized string}}
+
+#if __pragma(message("outer" _Pragma("message(\"inner\")") // expected-error
{{nested pragma is not allowed}} expected-error {{missing terminating ')'
character}} expected-error {{expected value in expression}}
+#endif
+
+_Pragma("message(\"first\")") __pragma(message("second")) // expected-warning
{{first}} expected-warning {{second}}
+int after;
+int *use = &after;
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits