Bug Summary

File:tools/clang/lib/Lex/Pragma.cpp
Warning:line 1090, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Pragma.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/Lex -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/Lex -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp -faddrsig
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/Diagnostic.h"
16#include "clang/Basic/FileManager.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/Token.h"
34#include "clang/Lex/TokenLexer.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringSwitch.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/Support/CrashRecoveryContext.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/ErrorHandling.h"
45#include <algorithm>
46#include <cassert>
47#include <cstddef>
48#include <cstdint>
49#include <limits>
50#include <string>
51#include <utility>
52#include <vector>
53
54using namespace clang;
55
56// Out-of-line destructor to provide a home for the class.
57PragmaHandler::~PragmaHandler() = default;
58
59//===----------------------------------------------------------------------===//
60// EmptyPragmaHandler Implementation.
61//===----------------------------------------------------------------------===//
62
63EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
64
65void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
66 PragmaIntroducer Introducer,
67 Token &FirstToken) {}
68
69//===----------------------------------------------------------------------===//
70// PragmaNamespace Implementation.
71//===----------------------------------------------------------------------===//
72
73PragmaNamespace::~PragmaNamespace() {
74 llvm::DeleteContainerSeconds(Handlers);
75}
76
77/// FindHandler - Check to see if there is already a handler for the
78/// specified name. If not, return the handler for the null identifier if it
79/// exists, otherwise return null. If IgnoreNull is true (the default) then
80/// the null handler isn't returned on failure to match.
81PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
82 bool IgnoreNull) const {
83 if (PragmaHandler *Handler = Handlers.lookup(Name))
84 return Handler;
85 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
86}
87
88void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
89 assert(!Handlers.lookup(Handler->getName()) &&((!Handlers.lookup(Handler->getName()) && "A handler with this name is already registered in this namespace"
) ? static_cast<void> (0) : __assert_fail ("!Handlers.lookup(Handler->getName()) && \"A handler with this name is already registered in this namespace\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 90, __PRETTY_FUNCTION__))
90 "A handler with this name is already registered in this namespace")((!Handlers.lookup(Handler->getName()) && "A handler with this name is already registered in this namespace"
) ? static_cast<void> (0) : __assert_fail ("!Handlers.lookup(Handler->getName()) && \"A handler with this name is already registered in this namespace\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 90, __PRETTY_FUNCTION__))
;
91 Handlers[Handler->getName()] = Handler;
92}
93
94void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
95 assert(Handlers.lookup(Handler->getName()) &&((Handlers.lookup(Handler->getName()) && "Handler not registered in this namespace"
) ? static_cast<void> (0) : __assert_fail ("Handlers.lookup(Handler->getName()) && \"Handler not registered in this namespace\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 96, __PRETTY_FUNCTION__))
96 "Handler not registered in this namespace")((Handlers.lookup(Handler->getName()) && "Handler not registered in this namespace"
) ? static_cast<void> (0) : __assert_fail ("Handlers.lookup(Handler->getName()) && \"Handler not registered in this namespace\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 96, __PRETTY_FUNCTION__))
;
97 Handlers.erase(Handler->getName());
98}
99
100void PragmaNamespace::HandlePragma(Preprocessor &PP,
101 PragmaIntroducer Introducer, Token &Tok) {
102 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
103 // expand it, the user can have a STDC #define, that should not affect this.
104 PP.LexUnexpandedToken(Tok);
105
106 // Get the handler for this token. If there is no handler, ignore the pragma.
107 PragmaHandler *Handler
108 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
109 : StringRef(),
110 /*IgnoreNull=*/false);
111 if (!Handler) {
112 PP.Diag(Tok, diag::warn_pragma_ignored);
113 return;
114 }
115
116 // Otherwise, pass it down.
117 Handler->HandlePragma(PP, Introducer, Tok);
118}
119
120//===----------------------------------------------------------------------===//
121// Preprocessor Pragma Directive Handling.
122//===----------------------------------------------------------------------===//
123
124/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
125/// rest of the pragma, passing it to the registered pragma handlers.
126void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
127 if (Callbacks)
128 Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
129
130 if (!PragmasEnabled)
131 return;
132
133 ++NumPragma;
134
135 // Invoke the first level of pragma handlers which reads the namespace id.
136 Token Tok;
137 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
138
139 // If the pragma handler didn't read the rest of the line, consume it now.
140 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
141 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
142 DiscardUntilEndOfDirective();
143}
144
145/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
146/// return the first token after the directive. The _Pragma token has just
147/// been read into 'Tok'.
148void Preprocessor::Handle_Pragma(Token &Tok) {
149 // C11 6.10.3.4/3:
150 // all pragma unary operator expressions within [a completely
151 // macro-replaced preprocessing token sequence] are [...] processed [after
152 // rescanning is complete]
153 //
154 // This means that we execute _Pragma operators in two cases:
155 //
156 // 1) on token sequences that would otherwise be produced as the output of
157 // phase 4 of preprocessing, and
158 // 2) on token sequences formed as the macro-replaced token sequence of a
159 // macro argument
160 //
161 // Case #2 appears to be a wording bug: only _Pragmas that would survive to
162 // the end of phase 4 should actually be executed. Discussion on the WG14
163 // mailing list suggests that a _Pragma operator is notionally checked early,
164 // but only pragmas that survive to the end of phase 4 should be executed.
165 //
166 // In Case #2, we check the syntax now, but then put the tokens back into the
167 // token stream for later consumption.
168
169 struct TokenCollector {
170 Preprocessor &Self;
171 bool Collect;
172 SmallVector<Token, 3> Tokens;
173 Token &Tok;
174
175 void lex() {
176 if (Collect)
177 Tokens.push_back(Tok);
178 Self.Lex(Tok);
179 }
180
181 void revert() {
182 assert(Collect && "did not collect tokens")((Collect && "did not collect tokens") ? static_cast<
void> (0) : __assert_fail ("Collect && \"did not collect tokens\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 182, __PRETTY_FUNCTION__))
;
183 assert(!Tokens.empty() && "collected unexpected number of tokens")((!Tokens.empty() && "collected unexpected number of tokens"
) ? static_cast<void> (0) : __assert_fail ("!Tokens.empty() && \"collected unexpected number of tokens\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 183, __PRETTY_FUNCTION__))
;
184
185 // Push the ( "string" ) tokens into the token stream.
186 auto Toks = llvm::make_unique<Token[]>(Tokens.size());
187 std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
188 Toks[Tokens.size() - 1] = Tok;
189 Self.EnterTokenStream(std::move(Toks), Tokens.size(),
190 /*DisableMacroExpansion*/ true,
191 /*IsReinject*/ true);
192
193 // ... and return the _Pragma token unchanged.
194 Tok = *Tokens.begin();
195 }
196 };
197
198 TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
199
200 // Remember the pragma token location.
201 SourceLocation PragmaLoc = Tok.getLocation();
202
203 // Read the '('.
204 Toks.lex();
205 if (Tok.isNot(tok::l_paren)) {
206 Diag(PragmaLoc, diag::err__Pragma_malformed);
207 return;
208 }
209
210 // Read the '"..."'.
211 Toks.lex();
212 if (!tok::isStringLiteral(Tok.getKind())) {
213 Diag(PragmaLoc, diag::err__Pragma_malformed);
214 // Skip bad tokens, and the ')', if present.
215 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
216 Lex(Tok);
217 while (Tok.isNot(tok::r_paren) &&
218 !Tok.isAtStartOfLine() &&
219 Tok.isNot(tok::eof))
220 Lex(Tok);
221 if (Tok.is(tok::r_paren))
222 Lex(Tok);
223 return;
224 }
225
226 if (Tok.hasUDSuffix()) {
227 Diag(Tok, diag::err_invalid_string_udl);
228 // Skip this token, and the ')', if present.
229 Lex(Tok);
230 if (Tok.is(tok::r_paren))
231 Lex(Tok);
232 return;
233 }
234
235 // Remember the string.
236 Token StrTok = Tok;
237
238 // Read the ')'.
239 Toks.lex();
240 if (Tok.isNot(tok::r_paren)) {
241 Diag(PragmaLoc, diag::err__Pragma_malformed);
242 return;
243 }
244
245 // If we're expanding a macro argument, put the tokens back.
246 if (InMacroArgPreExpansion) {
247 Toks.revert();
248 return;
249 }
250
251 SourceLocation RParenLoc = Tok.getLocation();
252 std::string StrVal = getSpelling(StrTok);
253
254 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
255 // "The string literal is destringized by deleting any encoding prefix,
256 // deleting the leading and trailing double-quotes, replacing each escape
257 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
258 // single backslash."
259 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
260 (StrVal[0] == 'u' && StrVal[1] != '8'))
261 StrVal.erase(StrVal.begin());
262 else if (StrVal[0] == 'u')
263 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
264
265 if (StrVal[0] == 'R') {
266 // FIXME: C++11 does not specify how to handle raw-string-literals here.
267 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
268 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&((StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"'
&& "Invalid raw string token!") ? static_cast<void
> (0) : __assert_fail ("StrVal[1] == '\"' && StrVal[StrVal.size() - 1] == '\"' && \"Invalid raw string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 269, __PRETTY_FUNCTION__))
269 "Invalid raw string token!")((StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"'
&& "Invalid raw string token!") ? static_cast<void
> (0) : __assert_fail ("StrVal[1] == '\"' && StrVal[StrVal.size() - 1] == '\"' && \"Invalid raw string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 269, __PRETTY_FUNCTION__))
;
270
271 // Measure the length of the d-char-sequence.
272 unsigned NumDChars = 0;
273 while (StrVal[2 + NumDChars] != '(') {
274 assert(NumDChars < (StrVal.size() - 5) / 2 &&((NumDChars < (StrVal.size() - 5) / 2 && "Invalid raw string token!"
) ? static_cast<void> (0) : __assert_fail ("NumDChars < (StrVal.size() - 5) / 2 && \"Invalid raw string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 275, __PRETTY_FUNCTION__))
275 "Invalid raw string token!")((NumDChars < (StrVal.size() - 5) / 2 && "Invalid raw string token!"
) ? static_cast<void> (0) : __assert_fail ("NumDChars < (StrVal.size() - 5) / 2 && \"Invalid raw string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 275, __PRETTY_FUNCTION__))
;
276 ++NumDChars;
277 }
278 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')')((StrVal[StrVal.size() - 2 - NumDChars] == ')') ? static_cast
<void> (0) : __assert_fail ("StrVal[StrVal.size() - 2 - NumDChars] == ')'"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 278, __PRETTY_FUNCTION__))
;
279
280 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
281 // parens below.
282 StrVal.erase(0, 2 + NumDChars);
283 StrVal.erase(StrVal.size() - 1 - NumDChars);
284 } else {
285 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&((StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
"Invalid string token!") ? static_cast<void> (0) : __assert_fail
("StrVal[0] == '\"' && StrVal[StrVal.size()-1] == '\"' && \"Invalid string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 286, __PRETTY_FUNCTION__))
286 "Invalid string token!")((StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
"Invalid string token!") ? static_cast<void> (0) : __assert_fail
("StrVal[0] == '\"' && StrVal[StrVal.size()-1] == '\"' && \"Invalid string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 286, __PRETTY_FUNCTION__))
;
287
288 // Remove escaped quotes and escapes.
289 unsigned ResultPos = 1;
290 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
291 // Skip escapes. \\ -> '\' and \" -> '"'.
292 if (StrVal[i] == '\\' && i + 1 < e &&
293 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
294 ++i;
295 StrVal[ResultPos++] = StrVal[i];
296 }
297 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
298 }
299
300 // Remove the front quote, replacing it with a space, so that the pragma
301 // contents appear to have a space before them.
302 StrVal[0] = ' ';
303
304 // Replace the terminating quote with a \n.
305 StrVal[StrVal.size()-1] = '\n';
306
307 // Plop the string (including the newline and trailing null) into a buffer
308 // where we can lex it.
309 Token TmpTok;
310 TmpTok.startToken();
311 CreateString(StrVal, TmpTok);
312 SourceLocation TokLoc = TmpTok.getLocation();
313
314 // Make and enter a lexer object so that we lex and expand the tokens just
315 // like any others.
316 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
317 StrVal.size(), *this);
318
319 EnterSourceFileWithLexer(TL, nullptr);
320
321 // With everything set up, lex this as a #pragma directive.
322 HandlePragmaDirective({PIK__Pragma, PragmaLoc});
323
324 // Finally, return whatever came after the pragma directive.
325 return Lex(Tok);
326}
327
328/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
329/// is not enclosed within a string literal.
330void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
331 // Remember the pragma token location.
332 SourceLocation PragmaLoc = Tok.getLocation();
333
334 // Read the '('.
335 Lex(Tok);
336 if (Tok.isNot(tok::l_paren)) {
337 Diag(PragmaLoc, diag::err__Pragma_malformed);
338 return;
339 }
340
341 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
342 SmallVector<Token, 32> PragmaToks;
343 int NumParens = 0;
344 Lex(Tok);
345 while (Tok.isNot(tok::eof)) {
346 PragmaToks.push_back(Tok);
347 if (Tok.is(tok::l_paren))
348 NumParens++;
349 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
350 break;
351 Lex(Tok);
352 }
353
354 if (Tok.is(tok::eof)) {
355 Diag(PragmaLoc, diag::err_unterminated___pragma);
356 return;
357 }
358
359 PragmaToks.front().setFlag(Token::LeadingSpace);
360
361 // Replace the ')' with an EOD to mark the end of the pragma.
362 PragmaToks.back().setKind(tok::eod);
363
364 Token *TokArray = new Token[PragmaToks.size()];
365 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
366
367 // Push the tokens onto the stack.
368 EnterTokenStream(TokArray, PragmaToks.size(), true, true,
369 /*IsReinject*/ false);
370
371 // With everything set up, lex this as a #pragma directive.
372 HandlePragmaDirective({PIK___pragma, PragmaLoc});
373
374 // Finally, return whatever came after the pragma directive.
375 return Lex(Tok);
376}
377
378/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
379void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
380 // Don't honor the 'once' when handling the primary source file, unless
381 // this is a prefix to a TU, which indicates we're generating a PCH file, or
382 // when the main file is a header (e.g. when -xc-header is provided on the
383 // commandline).
384 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
385 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
386 return;
387 }
388
389 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
390 // Mark the file as a once-only file now.
391 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
392}
393
394void Preprocessor::HandlePragmaMark() {
395 assert(CurPPLexer && "No current lexer?")((CurPPLexer && "No current lexer?") ? static_cast<
void> (0) : __assert_fail ("CurPPLexer && \"No current lexer?\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 395, __PRETTY_FUNCTION__))
;
396 CurLexer->ReadToEndOfLine();
397}
398
399/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
400void Preprocessor::HandlePragmaPoison() {
401 Token Tok;
402
403 while (true) {
404 // Read the next token to poison. While doing this, pretend that we are
405 // skipping while reading the identifier to poison.
406 // This avoids errors on code like:
407 // #pragma GCC poison X
408 // #pragma GCC poison X
409 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
410 LexUnexpandedToken(Tok);
411 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
412
413 // If we reached the end of line, we're done.
414 if (Tok.is(tok::eod)) return;
415
416 // Can only poison identifiers.
417 if (Tok.isNot(tok::raw_identifier)) {
418 Diag(Tok, diag::err_pp_invalid_poison);
419 return;
420 }
421
422 // Look up the identifier info for the token. We disabled identifier lookup
423 // by saying we're skipping contents, so we need to do this manually.
424 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
425
426 // Already poisoned.
427 if (II->isPoisoned()) continue;
428
429 // If this is a macro identifier, emit a warning.
430 if (isMacroDefined(II))
431 Diag(Tok, diag::pp_poisoning_existing_macro);
432
433 // Finally, poison it!
434 II->setIsPoisoned();
435 if (II->isFromAST())
436 II->setChangedSinceDeserialization();
437 }
438}
439
440/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
441/// that the whole directive has been parsed.
442void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
443 if (isInPrimaryFile()) {
444 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
445 return;
446 }
447
448 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
449 PreprocessorLexer *TheLexer = getCurrentFileLexer();
450
451 // Mark the file as a system header.
452 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
453
454 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
455 if (PLoc.isInvalid())
456 return;
457
458 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
459
460 // Notify the client, if desired, that we are in a new source file.
461 if (Callbacks)
462 Callbacks->FileChanged(SysHeaderTok.getLocation(),
463 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
464
465 // Emit a line marker. This will change any source locations from this point
466 // forward to realize they are in a system header.
467 // Create a line note with this information.
468 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
469 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
470 SrcMgr::C_System);
471}
472
473/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
474void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
475 Token FilenameTok;
476 if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
477 return;
478
479 // If the next token wasn't a header-name, diagnose the error.
480 if (FilenameTok.isNot(tok::header_name)) {
481 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
482 return;
483 }
484
485 // Reserve a buffer to get the spelling.
486 SmallString<128> FilenameBuffer;
487 bool Invalid = false;
488 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
489 if (Invalid)
490 return;
491
492 bool isAngled =
493 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
494 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
495 // error.
496 if (Filename.empty())
497 return;
498
499 // Search include directories for this file.
500 const DirectoryLookup *CurDir;
501 const FileEntry *File =
502 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
503 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
504 if (!File) {
505 if (!SuppressIncludeNotFoundError)
506 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
507 return;
508 }
509
510 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
511
512 // If this file is older than the file it depends on, emit a diagnostic.
513 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
514 // Lex tokens at the end of the message and include them in the message.
515 std::string Message;
516 Lex(DependencyTok);
517 while (DependencyTok.isNot(tok::eod)) {
518 Message += getSpelling(DependencyTok) + " ";
519 Lex(DependencyTok);
520 }
521
522 // Remove the trailing ' ' if present.
523 if (!Message.empty())
524 Message.erase(Message.end()-1);
525 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
526 }
527}
528
529/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
530/// Return the IdentifierInfo* associated with the macro to push or pop.
531IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
532 // Remember the pragma token location.
533 Token PragmaTok = Tok;
534
535 // Read the '('.
536 Lex(Tok);
537 if (Tok.isNot(tok::l_paren)) {
538 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
539 << getSpelling(PragmaTok);
540 return nullptr;
541 }
542
543 // Read the macro name string.
544 Lex(Tok);
545 if (Tok.isNot(tok::string_literal)) {
546 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
547 << getSpelling(PragmaTok);
548 return nullptr;
549 }
550
551 if (Tok.hasUDSuffix()) {
552 Diag(Tok, diag::err_invalid_string_udl);
553 return nullptr;
554 }
555
556 // Remember the macro string.
557 std::string StrVal = getSpelling(Tok);
558
559 // Read the ')'.
560 Lex(Tok);
561 if (Tok.isNot(tok::r_paren)) {
562 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
563 << getSpelling(PragmaTok);
564 return nullptr;
565 }
566
567 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&((StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
"Invalid string token!") ? static_cast<void> (0) : __assert_fail
("StrVal[0] == '\"' && StrVal[StrVal.size()-1] == '\"' && \"Invalid string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 568, __PRETTY_FUNCTION__))
568 "Invalid string token!")((StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
"Invalid string token!") ? static_cast<void> (0) : __assert_fail
("StrVal[0] == '\"' && StrVal[StrVal.size()-1] == '\"' && \"Invalid string token!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 568, __PRETTY_FUNCTION__))
;
569
570 // Create a Token from the string.
571 Token MacroTok;
572 MacroTok.startToken();
573 MacroTok.setKind(tok::raw_identifier);
574 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
575
576 // Get the IdentifierInfo of MacroToPushTok.
577 return LookUpIdentifierInfo(MacroTok);
578}
579
580/// Handle \#pragma push_macro.
581///
582/// The syntax is:
583/// \code
584/// #pragma push_macro("macro")
585/// \endcode
586void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
587 // Parse the pragma directive and get the macro IdentifierInfo*.
588 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
589 if (!IdentInfo) return;
590
591 // Get the MacroInfo associated with IdentInfo.
592 MacroInfo *MI = getMacroInfo(IdentInfo);
593
594 if (MI) {
595 // Allow the original MacroInfo to be redefined later.
596 MI->setIsAllowRedefinitionsWithoutWarning(true);
597 }
598
599 // Push the cloned MacroInfo so we can retrieve it later.
600 PragmaPushMacroInfo[IdentInfo].push_back(MI);
601}
602
603/// Handle \#pragma pop_macro.
604///
605/// The syntax is:
606/// \code
607/// #pragma pop_macro("macro")
608/// \endcode
609void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
610 SourceLocation MessageLoc = PopMacroTok.getLocation();
611
612 // Parse the pragma directive and get the macro IdentifierInfo*.
613 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
614 if (!IdentInfo) return;
615
616 // Find the vector<MacroInfo*> associated with the macro.
617 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
618 PragmaPushMacroInfo.find(IdentInfo);
619 if (iter != PragmaPushMacroInfo.end()) {
620 // Forget the MacroInfo currently associated with IdentInfo.
621 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
622 if (MI->isWarnIfUnused())
623 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
624 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
625 }
626
627 // Get the MacroInfo we want to reinstall.
628 MacroInfo *MacroToReInstall = iter->second.back();
629
630 if (MacroToReInstall)
631 // Reinstall the previously pushed macro.
632 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
633
634 // Pop PragmaPushMacroInfo stack.
635 iter->second.pop_back();
636 if (iter->second.empty())
637 PragmaPushMacroInfo.erase(iter);
638 } else {
639 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
640 << IdentInfo->getName();
641 }
642}
643
644void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
645 // We will either get a quoted filename or a bracketed filename, and we
646 // have to track which we got. The first filename is the source name,
647 // and the second name is the mapped filename. If the first is quoted,
648 // the second must be as well (cannot mix and match quotes and brackets).
649
650 // Get the open paren
651 Lex(Tok);
652 if (Tok.isNot(tok::l_paren)) {
653 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
654 return;
655 }
656
657 // We expect either a quoted string literal, or a bracketed name
658 Token SourceFilenameTok;
659 if (LexHeaderName(SourceFilenameTok))
660 return;
661
662 StringRef SourceFileName;
663 SmallString<128> FileNameBuffer;
664 if (SourceFilenameTok.is(tok::header_name)) {
665 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
666 } else {
667 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
668 return;
669 }
670 FileNameBuffer.clear();
671
672 // Now we expect a comma, followed by another include name
673 Lex(Tok);
674 if (Tok.isNot(tok::comma)) {
675 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
676 return;
677 }
678
679 Token ReplaceFilenameTok;
680 if (LexHeaderName(ReplaceFilenameTok))
681 return;
682
683 StringRef ReplaceFileName;
684 if (ReplaceFilenameTok.is(tok::header_name)) {
685 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
686 } else {
687 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
688 return;
689 }
690
691 // Finally, we expect the closing paren
692 Lex(Tok);
693 if (Tok.isNot(tok::r_paren)) {
694 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
695 return;
696 }
697
698 // Now that we have the source and target filenames, we need to make sure
699 // they're both of the same type (angled vs non-angled)
700 StringRef OriginalSource = SourceFileName;
701
702 bool SourceIsAngled =
703 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
704 SourceFileName);
705 bool ReplaceIsAngled =
706 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
707 ReplaceFileName);
708 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
709 (SourceIsAngled != ReplaceIsAngled)) {
710 unsigned int DiagID;
711 if (SourceIsAngled)
712 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
713 else
714 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
715
716 Diag(SourceFilenameTok.getLocation(), DiagID)
717 << SourceFileName
718 << ReplaceFileName;
719
720 return;
721 }
722
723 // Now we can let the include handler know about this mapping
724 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
725}
726
727// Lex a component of a module name: either an identifier or a string literal;
728// for components that can be expressed both ways, the two forms are equivalent.
729static bool LexModuleNameComponent(
730 Preprocessor &PP, Token &Tok,
731 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
732 bool First) {
733 PP.LexUnexpandedToken(Tok);
734 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
735 StringLiteralParser Literal(Tok, PP);
736 if (Literal.hadError)
737 return true;
738 ModuleNameComponent = std::make_pair(
739 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
740 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
741 ModuleNameComponent =
742 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
743 } else {
744 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
745 return true;
746 }
747 return false;
748}
749
750static bool LexModuleName(
751 Preprocessor &PP, Token &Tok,
752 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
753 &ModuleName) {
754 while (true) {
755 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
756 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
757 return true;
758 ModuleName.push_back(NameComponent);
759
760 PP.LexUnexpandedToken(Tok);
761 if (Tok.isNot(tok::period))
762 return false;
763 }
764}
765
766void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
767 SourceLocation Loc = Tok.getLocation();
768
769 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
770 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
771 return;
772 IdentifierInfo *ModuleName = ModuleNameLoc.first;
773
774 LexUnexpandedToken(Tok);
775 if (Tok.isNot(tok::eod)) {
776 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
777 DiscardUntilEndOfDirective();
778 }
779
780 CurLexer->LexingRawMode = true;
781
782 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
783 if (Tok.getKind() != tok::raw_identifier ||
784 Tok.getRawIdentifier() != Ident)
785 return false;
786 CurLexer->Lex(Tok);
787 return true;
788 };
789
790 // Scan forward looking for the end of the module.
791 const char *Start = CurLexer->getBufferLocation();
792 const char *End = nullptr;
793 unsigned NestingLevel = 1;
794 while (true) {
795 End = CurLexer->getBufferLocation();
796 CurLexer->Lex(Tok);
797
798 if (Tok.is(tok::eof)) {
799 Diag(Loc, diag::err_pp_module_build_missing_end);
800 break;
801 }
802
803 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
804 // Token was part of module; keep going.
805 continue;
806 }
807
808 // We hit something directive-shaped; check to see if this is the end
809 // of the module build.
810 CurLexer->ParsingPreprocessorDirective = true;
811 CurLexer->Lex(Tok);
812 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
813 TryConsumeIdentifier("module")) {
814 if (TryConsumeIdentifier("build"))
815 // #pragma clang module build -> entering a nested module build.
816 ++NestingLevel;
817 else if (TryConsumeIdentifier("endbuild")) {
818 // #pragma clang module endbuild -> leaving a module build.
819 if (--NestingLevel == 0)
820 break;
821 }
822 // We should either be looking at the EOD or more of the current directive
823 // preceding the EOD. Either way we can ignore this token and keep going.
824 assert(Tok.getKind() != tok::eof && "missing EOD before EOF")((Tok.getKind() != tok::eof && "missing EOD before EOF"
) ? static_cast<void> (0) : __assert_fail ("Tok.getKind() != tok::eof && \"missing EOD before EOF\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 824, __PRETTY_FUNCTION__))
;
825 }
826 }
827
828 CurLexer->LexingRawMode = false;
829
830 // Load the extracted text as a preprocessed module.
831 assert(CurLexer->getBuffer().begin() <= Start &&((CurLexer->getBuffer().begin() <= Start && Start
<= CurLexer->getBuffer().end() && CurLexer->
getBuffer().begin() <= End && End <= CurLexer->
getBuffer().end() && "module source range not contained within same file buffer"
) ? static_cast<void> (0) : __assert_fail ("CurLexer->getBuffer().begin() <= Start && Start <= CurLexer->getBuffer().end() && CurLexer->getBuffer().begin() <= End && End <= CurLexer->getBuffer().end() && \"module source range not contained within same file buffer\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 835, __PRETTY_FUNCTION__))
832 Start <= CurLexer->getBuffer().end() &&((CurLexer->getBuffer().begin() <= Start && Start
<= CurLexer->getBuffer().end() && CurLexer->
getBuffer().begin() <= End && End <= CurLexer->
getBuffer().end() && "module source range not contained within same file buffer"
) ? static_cast<void> (0) : __assert_fail ("CurLexer->getBuffer().begin() <= Start && Start <= CurLexer->getBuffer().end() && CurLexer->getBuffer().begin() <= End && End <= CurLexer->getBuffer().end() && \"module source range not contained within same file buffer\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 835, __PRETTY_FUNCTION__))
833 CurLexer->getBuffer().begin() <= End &&((CurLexer->getBuffer().begin() <= Start && Start
<= CurLexer->getBuffer().end() && CurLexer->
getBuffer().begin() <= End && End <= CurLexer->
getBuffer().end() && "module source range not contained within same file buffer"
) ? static_cast<void> (0) : __assert_fail ("CurLexer->getBuffer().begin() <= Start && Start <= CurLexer->getBuffer().end() && CurLexer->getBuffer().begin() <= End && End <= CurLexer->getBuffer().end() && \"module source range not contained within same file buffer\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 835, __PRETTY_FUNCTION__))
834 End <= CurLexer->getBuffer().end() &&((CurLexer->getBuffer().begin() <= Start && Start
<= CurLexer->getBuffer().end() && CurLexer->
getBuffer().begin() <= End && End <= CurLexer->
getBuffer().end() && "module source range not contained within same file buffer"
) ? static_cast<void> (0) : __assert_fail ("CurLexer->getBuffer().begin() <= Start && Start <= CurLexer->getBuffer().end() && CurLexer->getBuffer().begin() <= End && End <= CurLexer->getBuffer().end() && \"module source range not contained within same file buffer\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 835, __PRETTY_FUNCTION__))
835 "module source range not contained within same file buffer")((CurLexer->getBuffer().begin() <= Start && Start
<= CurLexer->getBuffer().end() && CurLexer->
getBuffer().begin() <= End && End <= CurLexer->
getBuffer().end() && "module source range not contained within same file buffer"
) ? static_cast<void> (0) : __assert_fail ("CurLexer->getBuffer().begin() <= Start && Start <= CurLexer->getBuffer().end() && CurLexer->getBuffer().begin() <= End && End <= CurLexer->getBuffer().end() && \"module source range not contained within same file buffer\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 835, __PRETTY_FUNCTION__))
;
836 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
837 StringRef(Start, End - Start));
838}
839
840void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
841 Lex(Tok);
842 if (Tok.is(tok::l_paren)) {
843 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
844
845 std::string FileName;
846 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
847 return;
848
849 if (Tok.isNot(tok::r_paren)) {
850 Diag(Tok, diag::err_expected) << tok::r_paren;
851 return;
852 }
853 Lex(Tok);
854 }
855 if (Tok.isNot(tok::eod))
856 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
857 << "pragma hdrstop";
858
859 if (creatingPCHWithPragmaHdrStop() &&
860 SourceMgr.isInMainFile(Tok.getLocation())) {
861 assert(CurLexer && "no lexer for #pragma hdrstop processing")((CurLexer && "no lexer for #pragma hdrstop processing"
) ? static_cast<void> (0) : __assert_fail ("CurLexer && \"no lexer for #pragma hdrstop processing\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 861, __PRETTY_FUNCTION__))
;
862 Token &Result = Tok;
863 Result.startToken();
864 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
865 CurLexer->cutOffLexing();
866 }
867 if (usingPCHWithPragmaHdrStop())
868 SkippingUntilPragmaHdrStop = false;
869}
870
871/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
872/// If 'Namespace' is non-null, then it is a token required to exist on the
873/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
874void Preprocessor::AddPragmaHandler(StringRef Namespace,
875 PragmaHandler *Handler) {
876 PragmaNamespace *InsertNS = PragmaHandlers.get();
877
878 // If this is specified to be in a namespace, step down into it.
879 if (!Namespace.empty()) {
880 // If there is already a pragma handler with the name of this namespace,
881 // we either have an error (directive with the same name as a namespace) or
882 // we already have the namespace to insert into.
883 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
884 InsertNS = Existing->getIfNamespace();
885 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"((InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
" handler with the same name!") ? static_cast<void> (0
) : __assert_fail ("InsertNS != nullptr && \"Cannot have a pragma namespace and pragma\" \" handler with the same name!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 886, __PRETTY_FUNCTION__))
886 " handler with the same name!")((InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
" handler with the same name!") ? static_cast<void> (0
) : __assert_fail ("InsertNS != nullptr && \"Cannot have a pragma namespace and pragma\" \" handler with the same name!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 886, __PRETTY_FUNCTION__))
;
887 } else {
888 // Otherwise, this namespace doesn't exist yet, create and insert the
889 // handler for it.
890 InsertNS = new PragmaNamespace(Namespace);
891 PragmaHandlers->AddPragma(InsertNS);
892 }
893 }
894
895 // Check to make sure we don't already have a pragma for this identifier.
896 assert(!InsertNS->FindHandler(Handler->getName()) &&((!InsertNS->FindHandler(Handler->getName()) &&
"Pragma handler already exists for this identifier!") ? static_cast
<void> (0) : __assert_fail ("!InsertNS->FindHandler(Handler->getName()) && \"Pragma handler already exists for this identifier!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 897, __PRETTY_FUNCTION__))
897 "Pragma handler already exists for this identifier!")((!InsertNS->FindHandler(Handler->getName()) &&
"Pragma handler already exists for this identifier!") ? static_cast
<void> (0) : __assert_fail ("!InsertNS->FindHandler(Handler->getName()) && \"Pragma handler already exists for this identifier!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 897, __PRETTY_FUNCTION__))
;
898 InsertNS->AddPragma(Handler);
899}
900
901/// RemovePragmaHandler - Remove the specific pragma handler from the
902/// preprocessor. If \arg Namespace is non-null, then it should be the
903/// namespace that \arg Handler was added to. It is an error to remove
904/// a handler that has not been registered.
905void Preprocessor::RemovePragmaHandler(StringRef Namespace,
906 PragmaHandler *Handler) {
907 PragmaNamespace *NS = PragmaHandlers.get();
908
909 // If this is specified to be in a namespace, step down into it.
910 if (!Namespace.empty()) {
911 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
912 assert(Existing && "Namespace containing handler does not exist!")((Existing && "Namespace containing handler does not exist!"
) ? static_cast<void> (0) : __assert_fail ("Existing && \"Namespace containing handler does not exist!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 912, __PRETTY_FUNCTION__))
;
913
914 NS = Existing->getIfNamespace();
915 assert(NS && "Invalid namespace, registered as a regular pragma handler!")((NS && "Invalid namespace, registered as a regular pragma handler!"
) ? static_cast<void> (0) : __assert_fail ("NS && \"Invalid namespace, registered as a regular pragma handler!\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 915, __PRETTY_FUNCTION__))
;
916 }
917
918 NS->RemovePragmaHandler(Handler);
919
920 // If this is a non-default namespace and it is now empty, remove it.
921 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
922 PragmaHandlers->RemovePragmaHandler(NS);
923 delete NS;
924 }
925}
926
927bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
928 Token Tok;
929 LexUnexpandedToken(Tok);
930
931 if (Tok.isNot(tok::identifier)) {
932 Diag(Tok, diag::ext_on_off_switch_syntax);
933 return true;
934 }
935 IdentifierInfo *II = Tok.getIdentifierInfo();
936 if (II->isStr("ON"))
937 Result = tok::OOS_ON;
938 else if (II->isStr("OFF"))
939 Result = tok::OOS_OFF;
940 else if (II->isStr("DEFAULT"))
941 Result = tok::OOS_DEFAULT;
942 else {
943 Diag(Tok, diag::ext_on_off_switch_syntax);
944 return true;
945 }
946
947 // Verify that this is followed by EOD.
948 LexUnexpandedToken(Tok);
949 if (Tok.isNot(tok::eod))
950 Diag(Tok, diag::ext_pragma_syntax_eod);
951 return false;
952}
953
954namespace {
955
956/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
957struct PragmaOnceHandler : public PragmaHandler {
958 PragmaOnceHandler() : PragmaHandler("once") {}
959
960 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
961 Token &OnceTok) override {
962 PP.CheckEndOfDirective("pragma once");
963 PP.HandlePragmaOnce(OnceTok);
964 }
965};
966
967/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
968/// rest of the line is not lexed.
969struct PragmaMarkHandler : public PragmaHandler {
970 PragmaMarkHandler() : PragmaHandler("mark") {}
971
972 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
973 Token &MarkTok) override {
974 PP.HandlePragmaMark();
975 }
976};
977
978/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
979struct PragmaPoisonHandler : public PragmaHandler {
980 PragmaPoisonHandler() : PragmaHandler("poison") {}
981
982 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
983 Token &PoisonTok) override {
984 PP.HandlePragmaPoison();
985 }
986};
987
988/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
989/// as a system header, which silences warnings in it.
990struct PragmaSystemHeaderHandler : public PragmaHandler {
991 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
992
993 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
994 Token &SHToken) override {
995 PP.HandlePragmaSystemHeader(SHToken);
996 PP.CheckEndOfDirective("pragma");
997 }
998};
999
1000struct PragmaDependencyHandler : public PragmaHandler {
1001 PragmaDependencyHandler() : PragmaHandler("dependency") {}
1002
1003 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1004 Token &DepToken) override {
1005 PP.HandlePragmaDependency(DepToken);
1006 }
1007};
1008
1009struct PragmaDebugHandler : public PragmaHandler {
1010 PragmaDebugHandler() : PragmaHandler("__debug") {}
1011
1012 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1013 Token &DebugToken) override {
1014 Token Tok;
1015 PP.LexUnexpandedToken(Tok);
1016 if (Tok.isNot(tok::identifier)) {
1
Taking false branch
1017 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1018 return;
1019 }
1020 IdentifierInfo *II = Tok.getIdentifierInfo();
1021
1022 if (II->isStr("assert")) {
2
Taking false branch
1023 llvm_unreachable("This is an assertion!")::llvm::llvm_unreachable_internal("This is an assertion!", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 1023)
;
1024 } else if (II->isStr("crash")) {
3
Taking false branch
1025 LLVM_BUILTIN_TRAP__builtin_trap();
1026 } else if (II->isStr("parser_crash")) {
4
Taking false branch
1027 Token Crasher;
1028 Crasher.startToken();
1029 Crasher.setKind(tok::annot_pragma_parser_crash);
1030 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
1031 PP.EnterToken(Crasher, /*IsReinject*/false);
1032 } else if (II->isStr("dump")) {
5
Taking false branch
1033 Token Identifier;
1034 PP.LexUnexpandedToken(Identifier);
1035 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1036 Token DumpAnnot;
1037 DumpAnnot.startToken();
1038 DumpAnnot.setKind(tok::annot_pragma_dump);
1039 DumpAnnot.setAnnotationRange(
1040 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1041 DumpAnnot.setAnnotationValue(DumpII);
1042 PP.DiscardUntilEndOfDirective();
1043 PP.EnterToken(DumpAnnot, /*IsReinject*/false);
1044 } else {
1045 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1046 << II->getName();
1047 }
1048 } else if (II->isStr("diag_mapping")) {
6
Taking false branch
1049 Token DiagName;
1050 PP.LexUnexpandedToken(DiagName);
1051 if (DiagName.is(tok::eod))
1052 PP.getDiagnostics().dump();
1053 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1054 StringLiteralParser Literal(DiagName, PP);
1055 if (Literal.hadError)
1056 return;
1057 PP.getDiagnostics().dump(Literal.GetString());
1058 } else {
1059 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1060 << II->getName();
1061 }
1062 } else if (II->isStr("llvm_fatal_error")) {
7
Taking false branch
1063 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1064 } else if (II->isStr("llvm_unreachable")) {
8
Taking false branch
1065 llvm_unreachable("#pragma clang __debug llvm_unreachable")::llvm::llvm_unreachable_internal("#pragma clang __debug llvm_unreachable"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 1065)
;
1066 } else if (II->isStr("macro")) {
9
Taking false branch
1067 Token MacroName;
1068 PP.LexUnexpandedToken(MacroName);
1069 auto *MacroII = MacroName.getIdentifierInfo();
1070 if (MacroII)
1071 PP.dumpMacroInfo(MacroII);
1072 else
1073 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1074 << II->getName();
1075 } else if (II->isStr("module_map")) {
10
Taking true branch
1076 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1077 ModuleName;
1078 if (LexModuleName(PP, Tok, ModuleName))
11
Assuming the condition is false
12
Taking false branch
1079 return;
1080 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1081 Module *M = nullptr;
13
'M' initialized to a null pointer value
1082 for (auto IIAndLoc : ModuleName) {
14
Assuming '__begin11' is equal to '__end11'
1083 M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
1084 if (!M) {
1085 PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
1086 << IIAndLoc.first;
1087 return;
1088 }
1089 }
1090 M->dump();
15
Called C++ object pointer is null
1091 } else if (II->isStr("overflow_stack")) {
1092 DebugOverflowStack();
1093 } else if (II->isStr("handle_crash")) {
1094 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1095 if (CRC)
1096 CRC->HandleCrash();
1097 } else if (II->isStr("captured")) {
1098 HandleCaptured(PP);
1099 } else {
1100 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1101 << II->getName();
1102 }
1103
1104 PPCallbacks *Callbacks = PP.getPPCallbacks();
1105 if (Callbacks)
1106 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1107 }
1108
1109 void HandleCaptured(Preprocessor &PP) {
1110 Token Tok;
1111 PP.LexUnexpandedToken(Tok);
1112
1113 if (Tok.isNot(tok::eod)) {
1114 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1115 << "pragma clang __debug captured";
1116 return;
1117 }
1118
1119 SourceLocation NameLoc = Tok.getLocation();
1120 MutableArrayRef<Token> Toks(
1121 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1122 Toks[0].startToken();
1123 Toks[0].setKind(tok::annot_pragma_captured);
1124 Toks[0].setLocation(NameLoc);
1125
1126 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1127 /*IsReinject=*/false);
1128 }
1129
1130// Disable MSVC warning about runtime stack overflow.
1131#ifdef _MSC_VER
1132 #pragma warning(disable : 4717)
1133#endif
1134 static void DebugOverflowStack(void (*P)() = nullptr) {
1135 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1136 Self(reinterpret_cast<void(*)()>(Self));
1137 }
1138#ifdef _MSC_VER
1139 #pragma warning(default : 4717)
1140#endif
1141};
1142
1143/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
1144struct PragmaDiagnosticHandler : public PragmaHandler {
1145private:
1146 const char *Namespace;
1147
1148public:
1149 explicit PragmaDiagnosticHandler(const char *NS)
1150 : PragmaHandler("diagnostic"), Namespace(NS) {}
1151
1152 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1153 Token &DiagToken) override {
1154 SourceLocation DiagLoc = DiagToken.getLocation();
1155 Token Tok;
1156 PP.LexUnexpandedToken(Tok);
1157 if (Tok.isNot(tok::identifier)) {
1158 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1159 return;
1160 }
1161 IdentifierInfo *II = Tok.getIdentifierInfo();
1162 PPCallbacks *Callbacks = PP.getPPCallbacks();
1163
1164 if (II->isStr("pop")) {
1165 if (!PP.getDiagnostics().popMappings(DiagLoc))
1166 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
1167 else if (Callbacks)
1168 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
1169 return;
1170 } else if (II->isStr("push")) {
1171 PP.getDiagnostics().pushMappings(DiagLoc);
1172 if (Callbacks)
1173 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
1174 return;
1175 }
1176
1177 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1178 .Case("ignored", diag::Severity::Ignored)
1179 .Case("warning", diag::Severity::Warning)
1180 .Case("error", diag::Severity::Error)
1181 .Case("fatal", diag::Severity::Fatal)
1182 .Default(diag::Severity());
1183
1184 if (SV == diag::Severity()) {
1185 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
1186 return;
1187 }
1188
1189 PP.LexUnexpandedToken(Tok);
1190 SourceLocation StringLoc = Tok.getLocation();
1191
1192 std::string WarningName;
1193 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1194 /*MacroExpansion=*/false))
1195 return;
1196
1197 if (Tok.isNot(tok::eod)) {
1198 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1199 return;
1200 }
1201
1202 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1203 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
1204 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
1205 return;
1206 }
1207
1208 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1209 : diag::Flavor::Remark;
1210 StringRef Group = StringRef(WarningName).substr(2);
1211 bool unknownDiag = false;
1212 if (Group == "everything") {
1213 // Special handling for pragma clang diagnostic ... "-Weverything".
1214 // There is no formal group named "everything", so there has to be a
1215 // special case for it.
1216 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1217 } else
1218 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1219 DiagLoc);
1220 if (unknownDiag)
1221 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1222 << WarningName;
1223 else if (Callbacks)
1224 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1225 }
1226};
1227
1228/// "\#pragma hdrstop [<header-name-string>]"
1229struct PragmaHdrstopHandler : public PragmaHandler {
1230 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1231 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1232 Token &DepToken) override {
1233 PP.HandlePragmaHdrstop(DepToken);
1234 }
1235};
1236
1237/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1238/// diagnostics, so we don't really implement this pragma. We parse it and
1239/// ignore it to avoid -Wunknown-pragma warnings.
1240struct PragmaWarningHandler : public PragmaHandler {
1241 PragmaWarningHandler() : PragmaHandler("warning") {}
1242
1243 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1244 Token &Tok) override {
1245 // Parse things like:
1246 // warning(push, 1)
1247 // warning(pop)
1248 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1249 SourceLocation DiagLoc = Tok.getLocation();
1250 PPCallbacks *Callbacks = PP.getPPCallbacks();
1251
1252 PP.Lex(Tok);
1253 if (Tok.isNot(tok::l_paren)) {
1254 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1255 return;
1256 }
1257
1258 PP.Lex(Tok);
1259 IdentifierInfo *II = Tok.getIdentifierInfo();
1260
1261 if (II && II->isStr("push")) {
1262 // #pragma warning( push[ ,n ] )
1263 int Level = -1;
1264 PP.Lex(Tok);
1265 if (Tok.is(tok::comma)) {
1266 PP.Lex(Tok);
1267 uint64_t Value;
1268 if (Tok.is(tok::numeric_constant) &&
1269 PP.parseSimpleIntegerLiteral(Tok, Value))
1270 Level = int(Value);
1271 if (Level < 0 || Level > 4) {
1272 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1273 return;
1274 }
1275 }
1276 if (Callbacks)
1277 Callbacks->PragmaWarningPush(DiagLoc, Level);
1278 } else if (II && II->isStr("pop")) {
1279 // #pragma warning( pop )
1280 PP.Lex(Tok);
1281 if (Callbacks)
1282 Callbacks->PragmaWarningPop(DiagLoc);
1283 } else {
1284 // #pragma warning( warning-specifier : warning-number-list
1285 // [; warning-specifier : warning-number-list...] )
1286 while (true) {
1287 II = Tok.getIdentifierInfo();
1288 if (!II && !Tok.is(tok::numeric_constant)) {
1289 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1290 return;
1291 }
1292
1293 // Figure out which warning specifier this is.
1294 bool SpecifierValid;
1295 StringRef Specifier;
1296 llvm::SmallString<1> SpecifierBuf;
1297 if (II) {
1298 Specifier = II->getName();
1299 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1300 .Cases("default", "disable", "error", "once",
1301 "suppress", true)
1302 .Default(false);
1303 // If we read a correct specifier, snatch next token (that should be
1304 // ":", checked later).
1305 if (SpecifierValid)
1306 PP.Lex(Tok);
1307 } else {
1308 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1309 uint64_t Value;
1310 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1311 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1312 SpecifierValid = (Value >= 1) && (Value <= 4);
1313 } else
1314 SpecifierValid = false;
1315 // Next token already snatched by parseSimpleIntegerLiteral.
1316 }
1317
1318 if (!SpecifierValid) {
1319 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1320 return;
1321 }
1322 if (Tok.isNot(tok::colon)) {
1323 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1324 return;
1325 }
1326
1327 // Collect the warning ids.
1328 SmallVector<int, 4> Ids;
1329 PP.Lex(Tok);
1330 while (Tok.is(tok::numeric_constant)) {
1331 uint64_t Value;
1332 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1333 Value > std::numeric_limits<int>::max()) {
1334 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1335 return;
1336 }
1337 Ids.push_back(int(Value));
1338 }
1339 if (Callbacks)
1340 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1341
1342 // Parse the next specifier if there is a semicolon.
1343 if (Tok.isNot(tok::semi))
1344 break;
1345 PP.Lex(Tok);
1346 }
1347 }
1348
1349 if (Tok.isNot(tok::r_paren)) {
1350 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1351 return;
1352 }
1353
1354 PP.Lex(Tok);
1355 if (Tok.isNot(tok::eod))
1356 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1357 }
1358};
1359
1360/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1361/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1362/// otherwise to avoid -Wunknown-pragma warnings.
1363struct PragmaExecCharsetHandler : public PragmaHandler {
1364 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1365
1366 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1367 Token &Tok) override {
1368 // Parse things like:
1369 // execution_character_set(push, "UTF-8")
1370 // execution_character_set(pop)
1371 SourceLocation DiagLoc = Tok.getLocation();
1372 PPCallbacks *Callbacks = PP.getPPCallbacks();
1373
1374 PP.Lex(Tok);
1375 if (Tok.isNot(tok::l_paren)) {
1376 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1377 return;
1378 }
1379
1380 PP.Lex(Tok);
1381 IdentifierInfo *II = Tok.getIdentifierInfo();
1382
1383 if (II && II->isStr("push")) {
1384 // #pragma execution_character_set( push[ , string ] )
1385 PP.Lex(Tok);
1386 if (Tok.is(tok::comma)) {
1387 PP.Lex(Tok);
1388
1389 std::string ExecCharset;
1390 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1391 "pragma execution_character_set",
1392 /*MacroExpansion=*/false))
1393 return;
1394
1395 // MSVC supports either of these, but nothing else.
1396 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1397 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1398 return;
1399 }
1400 }
1401 if (Callbacks)
1402 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1403 } else if (II && II->isStr("pop")) {
1404 // #pragma execution_character_set( pop )
1405 PP.Lex(Tok);
1406 if (Callbacks)
1407 Callbacks->PragmaExecCharsetPop(DiagLoc);
1408 } else {
1409 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1410 return;
1411 }
1412
1413 if (Tok.isNot(tok::r_paren)) {
1414 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1415 return;
1416 }
1417
1418 PP.Lex(Tok);
1419 if (Tok.isNot(tok::eod))
1420 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1421 }
1422};
1423
1424/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1425struct PragmaIncludeAliasHandler : public PragmaHandler {
1426 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1427
1428 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1429 Token &IncludeAliasTok) override {
1430 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1431 }
1432};
1433
1434/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1435/// extension. The syntax is:
1436/// \code
1437/// #pragma message(string)
1438/// \endcode
1439/// OR, in GCC mode:
1440/// \code
1441/// #pragma message string
1442/// \endcode
1443/// string is a string, which is fully macro expanded, and permits string
1444/// concatenation, embedded escape characters, etc... See MSDN for more details.
1445/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1446/// form as \#pragma message.
1447struct PragmaMessageHandler : public PragmaHandler {
1448private:
1449 const PPCallbacks::PragmaMessageKind Kind;
1450 const StringRef Namespace;
1451
1452 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1453 bool PragmaNameOnly = false) {
1454 switch (Kind) {
1455 case PPCallbacks::PMK_Message:
1456 return PragmaNameOnly ? "message" : "pragma message";
1457 case PPCallbacks::PMK_Warning:
1458 return PragmaNameOnly ? "warning" : "pragma warning";
1459 case PPCallbacks::PMK_Error:
1460 return PragmaNameOnly ? "error" : "pragma error";
1461 }
1462 llvm_unreachable("Unknown PragmaMessageKind!")::llvm::llvm_unreachable_internal("Unknown PragmaMessageKind!"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/Lex/Pragma.cpp"
, 1462)
;
1463 }
1464
1465public:
1466 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1467 StringRef Namespace = StringRef())
1468 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1469 Namespace(Namespace) {}
1470
1471 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1472 Token &Tok) override {
1473 SourceLocation MessageLoc = Tok.getLocation();
1474 PP.Lex(Tok);
1475 bool ExpectClosingParen = false;
1476 switch (Tok.getKind()) {
1477 case tok::l_paren:
1478 // We have a MSVC style pragma message.
1479 ExpectClosingParen = true;
1480 // Read the string.
1481 PP.Lex(Tok);
1482 break;
1483 case tok::string_literal:
1484 // We have a GCC style pragma message, and we just read the string.
1485 break;
1486 default:
1487 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1488 return;
1489 }
1490
1491 std::string MessageString;
1492 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1493 /*MacroExpansion=*/true))
1494 return;
1495
1496 if (ExpectClosingParen) {
1497 if (Tok.isNot(tok::r_paren)) {
1498 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1499 return;
1500 }
1501 PP.Lex(Tok); // eat the r_paren.
1502 }
1503
1504 if (Tok.isNot(tok::eod)) {
1505 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1506 return;
1507 }
1508
1509 // Output the message.
1510 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1511 ? diag::err_pragma_message
1512 : diag::warn_pragma_message) << MessageString;
1513
1514 // If the pragma is lexically sound, notify any interested PPCallbacks.
1515 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1516 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1517 }
1518};
1519
1520/// Handle the clang \#pragma module import extension. The syntax is:
1521/// \code
1522/// #pragma clang module import some.module.name
1523/// \endcode
1524struct PragmaModuleImportHandler : public PragmaHandler {
1525 PragmaModuleImportHandler() : PragmaHandler("import") {}
1526
1527 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1528 Token &Tok) override {
1529 SourceLocation ImportLoc = Tok.getLocation();
1530
1531 // Read the module name.
1532 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1533 ModuleName;
1534 if (LexModuleName(PP, Tok, ModuleName))
1535 return;
1536
1537 if (Tok.isNot(tok::eod))
1538 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1539
1540 // If we have a non-empty module path, load the named module.
1541 Module *Imported =
1542 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1543 /*IsIncludeDirective=*/false);
1544 if (!Imported)
1545 return;
1546
1547 PP.makeModuleVisible(Imported, ImportLoc);
1548 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1549 tok::annot_module_include, Imported);
1550 if (auto *CB = PP.getPPCallbacks())
1551 CB->moduleImport(ImportLoc, ModuleName, Imported);
1552 }
1553};
1554
1555/// Handle the clang \#pragma module begin extension. The syntax is:
1556/// \code
1557/// #pragma clang module begin some.module.name
1558/// ...
1559/// #pragma clang module end
1560/// \endcode
1561struct PragmaModuleBeginHandler : public PragmaHandler {
1562 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1563
1564 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1565 Token &Tok) override {
1566 SourceLocation BeginLoc = Tok.getLocation();
1567
1568 // Read the module name.
1569 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1570 ModuleName;
1571 if (LexModuleName(PP, Tok, ModuleName))
1572 return;
1573
1574 if (Tok.isNot(tok::eod))
1575 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1576
1577 // We can only enter submodules of the current module.
1578 StringRef Current = PP.getLangOpts().CurrentModule;
1579 if (ModuleName.front().first->getName() != Current) {
1580 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1581 << ModuleName.front().first << (ModuleName.size() > 1)
1582 << Current.empty() << Current;
1583 return;
1584 }
1585
1586 // Find the module we're entering. We require that a module map for it
1587 // be loaded or implicitly loadable.
1588 auto &HSI = PP.getHeaderSearchInfo();
1589 Module *M = HSI.lookupModule(Current);
1590 if (!M) {
1591 PP.Diag(ModuleName.front().second,
1592 diag::err_pp_module_begin_no_module_map) << Current;
1593 return;
1594 }
1595 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1596 auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
1597 if (!NewM) {
1598 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1599 << M->getFullModuleName() << ModuleName[I].first;
1600 return;
1601 }
1602 M = NewM;
1603 }
1604
1605 // If the module isn't available, it doesn't make sense to enter it.
1606 if (Preprocessor::checkModuleIsAvailable(
1607 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
1608 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1609 << M->getTopLevelModuleName();
1610 return;
1611 }
1612
1613 // Enter the scope of the submodule.
1614 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1615 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1616 tok::annot_module_begin, M);
1617 }
1618};
1619
1620/// Handle the clang \#pragma module end extension.
1621struct PragmaModuleEndHandler : public PragmaHandler {
1622 PragmaModuleEndHandler() : PragmaHandler("end") {}
1623
1624 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1625 Token &Tok) override {
1626 SourceLocation Loc = Tok.getLocation();
1627
1628 PP.LexUnexpandedToken(Tok);
1629 if (Tok.isNot(tok::eod))
1630 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1631
1632 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1633 if (M)
1634 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1635 else
1636 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
1637 }
1638};
1639
1640/// Handle the clang \#pragma module build extension.
1641struct PragmaModuleBuildHandler : public PragmaHandler {
1642 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1643
1644 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1645 Token &Tok) override {
1646 PP.HandlePragmaModuleBuild(Tok);
1647 }
1648};
1649
1650/// Handle the clang \#pragma module load extension.
1651struct PragmaModuleLoadHandler : public PragmaHandler {
1652 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1653
1654 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1655 Token &Tok) override {
1656 SourceLocation Loc = Tok.getLocation();
1657
1658 // Read the module name.
1659 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1660 ModuleName;
1661 if (LexModuleName(PP, Tok, ModuleName))
1662 return;
1663
1664 if (Tok.isNot(tok::eod))
1665 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1666
1667 // Load the module, don't make it visible.
1668 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1669 /*IsIncludeDirective=*/false);
1670 }
1671};
1672
1673/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1674/// macro on the top of the stack.
1675struct PragmaPushMacroHandler : public PragmaHandler {
1676 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1677
1678 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1679 Token &PushMacroTok) override {
1680 PP.HandlePragmaPushMacro(PushMacroTok);
1681 }
1682};
1683
1684/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1685/// macro to the value on the top of the stack.
1686struct PragmaPopMacroHandler : public PragmaHandler {
1687 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1688
1689 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1690 Token &PopMacroTok) override {
1691 PP.HandlePragmaPopMacro(PopMacroTok);
1692 }
1693};
1694
1695/// PragmaARCCFCodeAuditedHandler -
1696/// \#pragma clang arc_cf_code_audited begin/end
1697struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1698 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1699
1700 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1701 Token &NameTok) override {
1702 SourceLocation Loc = NameTok.getLocation();
1703 bool IsBegin;
1704
1705 Token Tok;
1706
1707 // Lex the 'begin' or 'end'.
1708 PP.LexUnexpandedToken(Tok);
1709 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1710 if (BeginEnd && BeginEnd->isStr("begin")) {
1711 IsBegin = true;
1712 } else if (BeginEnd && BeginEnd->isStr("end")) {
1713 IsBegin = false;
1714 } else {
1715 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1716 return;
1717 }
1718
1719 // Verify that this is followed by EOD.
1720 PP.LexUnexpandedToken(Tok);
1721 if (Tok.isNot(tok::eod))
1722 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1723
1724 // The start location of the active audit.
1725 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1726
1727 // The start location we want after processing this.
1728 SourceLocation NewLoc;
1729
1730 if (IsBegin) {
1731 // Complain about attempts to re-enter an audit.
1732 if (BeginLoc.isValid()) {
1733 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1734 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1735 }
1736 NewLoc = Loc;
1737 } else {
1738 // Complain about attempts to leave an audit that doesn't exist.
1739 if (!BeginLoc.isValid()) {
1740 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1741 return;
1742 }
1743 NewLoc = SourceLocation();
1744 }
1745
1746 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1747 }
1748};
1749
1750/// PragmaAssumeNonNullHandler -
1751/// \#pragma clang assume_nonnull begin/end
1752struct PragmaAssumeNonNullHandler : public PragmaHandler {
1753 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
1754
1755 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1756 Token &NameTok) override {
1757 SourceLocation Loc = NameTok.getLocation();
1758 bool IsBegin;
1759
1760 Token Tok;
1761
1762 // Lex the 'begin' or 'end'.
1763 PP.LexUnexpandedToken(Tok);
1764 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1765 if (BeginEnd && BeginEnd->isStr("begin")) {
1766 IsBegin = true;
1767 } else if (BeginEnd && BeginEnd->isStr("end")) {
1768 IsBegin = false;
1769 } else {
1770 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1771 return;
1772 }
1773
1774 // Verify that this is followed by EOD.
1775 PP.LexUnexpandedToken(Tok);
1776 if (Tok.isNot(tok::eod))
1777 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1778
1779 // The start location of the active audit.
1780 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1781
1782 // The start location we want after processing this.
1783 SourceLocation NewLoc;
1784 PPCallbacks *Callbacks = PP.getPPCallbacks();
1785
1786 if (IsBegin) {
1787 // Complain about attempts to re-enter an audit.
1788 if (BeginLoc.isValid()) {
1789 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1790 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1791 }
1792 NewLoc = Loc;
1793 if (Callbacks)
1794 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
1795 } else {
1796 // Complain about attempts to leave an audit that doesn't exist.
1797 if (!BeginLoc.isValid()) {
1798 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1799 return;
1800 }
1801 NewLoc = SourceLocation();
1802 if (Callbacks)
1803 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
1804 }
1805
1806 PP.setPragmaAssumeNonNullLoc(NewLoc);
1807 }
1808};
1809
1810/// Handle "\#pragma region [...]"
1811///
1812/// The syntax is
1813/// \code
1814/// #pragma region [optional name]
1815/// #pragma endregion [optional comment]
1816/// \endcode
1817///
1818/// \note This is
1819/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1820/// pragma, just skipped by compiler.
1821struct PragmaRegionHandler : public PragmaHandler {
1822 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
1823
1824 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
1825 Token &NameTok) override {
1826 // #pragma region: endregion matches can be verified
1827 // __pragma(region): no sense, but ignored by msvc
1828 // _Pragma is not valid for MSVC, but there isn't any point
1829 // to handle a _Pragma differently.
1830 }
1831};
1832
1833} // namespace
1834
1835/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1836/// \#pragma GCC poison/system_header/dependency and \#pragma once.
1837void Preprocessor::RegisterBuiltinPragmas() {
1838 AddPragmaHandler(new PragmaOnceHandler());
1839 AddPragmaHandler(new PragmaMarkHandler());
1840 AddPragmaHandler(new PragmaPushMacroHandler());
1841 AddPragmaHandler(new PragmaPopMacroHandler());
1842 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1843
1844 // #pragma GCC ...
1845 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1846 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1847 AddPragmaHandler("GCC", new PragmaDependencyHandler());
1848 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1849 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1850 "GCC"));
1851 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1852 "GCC"));
1853 // #pragma clang ...
1854 AddPragmaHandler("clang", new PragmaPoisonHandler());
1855 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1856 AddPragmaHandler("clang", new PragmaDebugHandler());
1857 AddPragmaHandler("clang", new PragmaDependencyHandler());
1858 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1859 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1860 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
1861
1862 // #pragma clang module ...
1863 auto *ModuleHandler = new PragmaNamespace("module");
1864 AddPragmaHandler("clang", ModuleHandler);
1865 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
1866 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1867 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
1868 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1869 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
1870
1871 // Add region pragmas.
1872 AddPragmaHandler(new PragmaRegionHandler("region"));
1873 AddPragmaHandler(new PragmaRegionHandler("endregion"));
1874
1875 // MS extensions.
1876 if (LangOpts.MicrosoftExt) {
1877 AddPragmaHandler(new PragmaWarningHandler());
1878 AddPragmaHandler(new PragmaExecCharsetHandler());
1879 AddPragmaHandler(new PragmaIncludeAliasHandler());
1880 AddPragmaHandler(new PragmaHdrstopHandler());
1881 }
1882
1883 // Pragmas added by plugins
1884 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1885 ie = PragmaHandlerRegistry::end();
1886 it != ie; ++it) {
1887 AddPragmaHandler(it->instantiate().release());
1888 }
1889}
1890
1891/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1892/// warn about those pragmas being unknown.
1893void Preprocessor::IgnorePragmas() {
1894 AddPragmaHandler(new EmptyPragmaHandler());
1895 // Also ignore all pragmas in all namespaces created
1896 // in Preprocessor::RegisterBuiltinPragmas().
1897 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1898 AddPragmaHandler("clang", new EmptyPragmaHandler());
1899}