blob: 2404a47c1dca2e4d84c4769aca42ea009f597b82 [file] [log] [blame]
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001//===- Pragma.cpp - Pragma registration and handling ----------------------===//
Chris Lattnerb8761832006-06-24 21:31:03 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Chris Lattnerb8761832006-06-24 21:31:03 +00006//
7//===----------------------------------------------------------------------===//
8//
Chris Lattnerb694ba72006-07-02 22:41:36 +00009// This file implements the PragmaHandler/PragmaTable interfaces and implements
10// pragma related methods of the Preprocessor class.
Chris Lattnerb8761832006-06-24 21:31:03 +000011//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/Pragma.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000015#include "clang/Basic/Diagnostic.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000016#include "clang/Basic/FileManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000017#include "clang/Basic/IdentifierTable.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000018#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/Module.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000021#include "clang/Basic/SourceLocation.h"
Chris Lattnerb694ba72006-07-02 22:41:36 +000022#include "clang/Basic/SourceManager.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000023#include "clang/Basic/TokenKinds.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/HeaderSearch.h"
25#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000026#include "clang/Lex/Lexer.h"
Richard Smith9565c75b2017-06-19 23:09:36 +000027#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/MacroInfo.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000029#include "clang/Lex/ModuleLoader.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/Lex/PPCallbacks.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000032#include "clang/Lex/PreprocessorLexer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000033#include "clang/Lex/Token.h"
34#include "clang/Lex/TokenLexer.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/DenseMap.h"
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000037#include "llvm/ADT/STLExtras.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000038#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/SmallVector.h"
Andrew V. Tischenkoc88deb12018-04-10 10:34:13 +000040#include "llvm/ADT/StringSwitch.h"
Nico Weberade321e2018-04-10 18:53:28 +000041#include "llvm/ADT/StringRef.h"
Andrew V. Tischenkoc88deb12018-04-10 10:34:13 +000042#include "llvm/Support/CrashRecoveryContext.h"
Nico Weberade321e2018-04-10 18:53:28 +000043#include "llvm/Support/Compiler.h"
Daniel Dunbarf2cf3292010-08-17 22:32:48 +000044#include "llvm/Support/ErrorHandling.h"
Douglas Gregorc6d5edd2009-07-02 17:08:52 +000045#include <algorithm>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include <cassert>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000047#include <cstddef>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000048#include <cstdint>
49#include <limits>
50#include <string>
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000051#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000052#include <vector>
53
Chris Lattnerb8761832006-06-24 21:31:03 +000054using namespace clang;
55
56// Out-of-line destructor to provide a home for the class.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +000057PragmaHandler::~PragmaHandler() = default;
Chris Lattnerb8761832006-06-24 21:31:03 +000058
Chris Lattner2e155302006-07-03 05:34:41 +000059//===----------------------------------------------------------------------===//
Daniel Dunbard839e772010-06-11 20:10:12 +000060// EmptyPragmaHandler Implementation.
61//===----------------------------------------------------------------------===//
62
Hans Wennborg7357bbc2015-10-12 20:47:58 +000063EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000064
Fangrui Song6907ce22018-07-30 19:24:48 +000065void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
Douglas Gregorc7d65762010-09-09 22:45:38 +000066 PragmaIntroducerKind Introducer,
67 Token &FirstToken) {}
Daniel Dunbard839e772010-06-11 20:10:12 +000068
69//===----------------------------------------------------------------------===//
Chris Lattner2e155302006-07-03 05:34:41 +000070// PragmaNamespace Implementation.
71//===----------------------------------------------------------------------===//
72
Chris Lattner2e155302006-07-03 05:34:41 +000073PragmaNamespace::~PragmaNamespace() {
Reid Kleckner588c9372014-02-19 23:44:52 +000074 llvm::DeleteContainerSeconds(Handlers);
Chris Lattner2e155302006-07-03 05:34:41 +000075}
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.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000081PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
Chris Lattner2e155302006-07-03 05:34:41 +000082 bool IgnoreNull) const {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000083 if (PragmaHandler *Handler = Handlers.lookup(Name))
84 return Handler;
Craig Topperd2d442c2014-05-17 23:10:59 +000085 return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000086}
Mike Stump11289f42009-09-09 15:08:12 +000087
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000088void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
89 assert(!Handlers.lookup(Handler->getName()) &&
90 "A handler with this name is already registered in this namespace");
David Blaikie13156b62014-11-19 03:06:06 +000091 Handlers[Handler->getName()] = Handler;
Chris Lattner2e155302006-07-03 05:34:41 +000092}
93
Daniel Dunbar40596532008-10-04 19:17:46 +000094void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000095 assert(Handlers.lookup(Handler->getName()) &&
96 "Handler not registered in this namespace");
97 Handlers.erase(Handler->getName());
Daniel Dunbar40596532008-10-04 19:17:46 +000098}
99
Fangrui Song6907ce22018-07-30 19:24:48 +0000100void PragmaNamespace::HandlePragma(Preprocessor &PP,
Douglas Gregorc7d65762010-09-09 22:45:38 +0000101 PragmaIntroducerKind Introducer,
102 Token &Tok) {
Chris Lattnerb8761832006-06-24 21:31:03 +0000103 // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
104 // expand it, the user can have a STDC #define, that should not affect this.
105 PP.LexUnexpandedToken(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000106
Chris Lattnerb8761832006-06-24 21:31:03 +0000107 // Get the handler for this token. If there is no handler, ignore the pragma.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000108 PragmaHandler *Handler
109 = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000110 : StringRef(),
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000111 /*IgnoreNull=*/false);
Craig Topperd2d442c2014-05-17 23:10:59 +0000112 if (!Handler) {
Chris Lattner21656f22009-04-19 21:10:26 +0000113 PP.Diag(Tok, diag::warn_pragma_ignored);
114 return;
115 }
Mike Stump11289f42009-09-09 15:08:12 +0000116
Chris Lattnerb8761832006-06-24 21:31:03 +0000117 // Otherwise, pass it down.
Douglas Gregorc7d65762010-09-09 22:45:38 +0000118 Handler->HandlePragma(PP, Introducer, Tok);
Chris Lattnerb8761832006-06-24 21:31:03 +0000119}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000120
Chris Lattnerb694ba72006-07-02 22:41:36 +0000121//===----------------------------------------------------------------------===//
122// Preprocessor Pragma Directive Handling.
123//===----------------------------------------------------------------------===//
124
James Dennett18a6d792012-06-17 03:26:26 +0000125/// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
Chris Lattnerb694ba72006-07-02 22:41:36 +0000126/// rest of the pragma, passing it to the registered pragma handlers.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000127void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
128 PragmaIntroducerKind Introducer) {
129 if (Callbacks)
130 Callbacks->PragmaDirective(IntroducerLoc, Introducer);
131
Jordan Rosede1a2922012-06-08 18:06:21 +0000132 if (!PragmasEnabled)
133 return;
134
Chris Lattnerb694ba72006-07-02 22:41:36 +0000135 ++NumPragma;
Mike Stump11289f42009-09-09 15:08:12 +0000136
Chris Lattnerb694ba72006-07-02 22:41:36 +0000137 // Invoke the first level of pragma handlers which reads the namespace id.
Chris Lattner146762e2007-07-20 16:59:19 +0000138 Token Tok;
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000139 PragmaHandlers->HandlePragma(*this, Introducer, Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000140
Chris Lattnerb694ba72006-07-02 22:41:36 +0000141 // If the pragma handler didn't read the rest of the line, consume it now.
Fangrui Song6907ce22018-07-30 19:24:48 +0000142 if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
Peter Collingbourne2c9f9662011-02-22 13:49:00 +0000143 || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000144 DiscardUntilEndOfDirective();
145}
146
147/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
148/// return the first token after the directive. The _Pragma token has just
149/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000150void Preprocessor::Handle_Pragma(Token &Tok) {
Richard Smith75f96812019-04-11 21:18:22 +0000151 // C11 6.10.3.4/3:
152 // all pragma unary operator expressions within [a completely
153 // macro-replaced preprocessing token sequence] are [...] processed [after
154 // rescanning is complete]
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000155 //
Richard Smith75f96812019-04-11 21:18:22 +0000156 // This means that we execute _Pragma operators in two cases:
157 //
158 // 1) on token sequences that would otherwise be produced as the output of
159 // phase 4 of preprocessing, and
160 // 2) on token sequences formed as the macro-replaced token sequence of a
161 // macro argument
162 //
163 // Case #2 appears to be a wording bug: only _Pragmas that would survive to
164 // the end of phase 4 should actually be executed. Discussion on the WG14
165 // mailing list suggests that a _Pragma operator is notionally checked early,
166 // but only pragmas that survive to the end of phase 4 should be executed.
167 //
168 // In Case #2, we check the syntax now, but then put the tokens back into the
169 // token stream for later consumption.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000170
Richard Smith75f96812019-04-11 21:18:22 +0000171 struct TokenCollector {
172 Preprocessor &Self;
173 bool Collect;
174 SmallVector<Token, 3> Tokens;
175 Token &Tok;
176
177 void lex() {
178 if (Collect)
179 Tokens.push_back(Tok);
180 Self.Lex(Tok);
181 }
182
183 void revert() {
184 assert(Collect && "did not collect tokens");
185 assert(!Tokens.empty() && "collected unexpected number of tokens");
186
187 // Push the ( "string" ) tokens into the token stream.
188 auto Toks = llvm::make_unique<Token[]>(Tokens.size());
189 std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
190 Toks[Tokens.size() - 1] = Tok;
191 Self.EnterTokenStream(std::move(Toks), Tokens.size(),
Ilya Biryukov929af672019-05-17 09:32:05 +0000192 /*DisableMacroExpansion*/ true,
193 /*IsReinject*/ true);
Richard Smith75f96812019-04-11 21:18:22 +0000194
195 // ... and return the _Pragma token unchanged.
196 Tok = *Tokens.begin();
197 }
198 };
199
200 TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000201
Chris Lattnerb694ba72006-07-02 22:41:36 +0000202 // Remember the pragma token location.
203 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000204
Chris Lattnerb694ba72006-07-02 22:41:36 +0000205 // Read the '('.
Richard Smith75f96812019-04-11 21:18:22 +0000206 Toks.lex();
Chris Lattner907dfe92008-11-18 07:59:24 +0000207 if (Tok.isNot(tok::l_paren)) {
208 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smith75f96812019-04-11 21:18:22 +0000209 return;
Chris Lattner907dfe92008-11-18 07:59:24 +0000210 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000211
212 // Read the '"..."'.
Richard Smith75f96812019-04-11 21:18:22 +0000213 Toks.lex();
Richard Smithc98bb4e2013-03-09 23:30:15 +0000214 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000215 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000216 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000217 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000218 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000219 while (Tok.isNot(tok::r_paren) &&
220 !Tok.isAtStartOfLine() &&
221 Tok.isNot(tok::eof))
222 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000223 if (Tok.is(tok::r_paren))
224 Lex(Tok);
Richard Smith75f96812019-04-11 21:18:22 +0000225 return;
Richard Smithd67aea22012-03-06 03:21:47 +0000226 }
227
228 if (Tok.hasUDSuffix()) {
229 Diag(Tok, diag::err_invalid_string_udl);
230 // Skip this token, and the ')', if present.
231 Lex(Tok);
232 if (Tok.is(tok::r_paren))
233 Lex(Tok);
Richard Smith75f96812019-04-11 21:18:22 +0000234 return;
Chris Lattner907dfe92008-11-18 07:59:24 +0000235 }
Mike Stump11289f42009-09-09 15:08:12 +0000236
Chris Lattnerb694ba72006-07-02 22:41:36 +0000237 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000238 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000239
240 // Read the ')'.
Richard Smith75f96812019-04-11 21:18:22 +0000241 Toks.lex();
Chris Lattner907dfe92008-11-18 07:59:24 +0000242 if (Tok.isNot(tok::r_paren)) {
243 Diag(PragmaLoc, diag::err__Pragma_malformed);
Richard Smith75f96812019-04-11 21:18:22 +0000244 return;
Chris Lattner907dfe92008-11-18 07:59:24 +0000245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Richard Smith75f96812019-04-11 21:18:22 +0000247 // If we're expanding a macro argument, put the tokens back.
248 if (InMacroArgPreExpansion) {
249 Toks.revert();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000250 return;
Richard Smith75f96812019-04-11 21:18:22 +0000251 }
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000252
Chris Lattner9dc9c202009-02-15 20:52:18 +0000253 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000254 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000255
Richard Smithc98bb4e2013-03-09 23:30:15 +0000256 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
257 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000258 // deleting the leading and trailing double-quotes, replacing each escape
259 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
260 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000261 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
262 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000263 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000264 else if (StrVal[0] == 'u')
265 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
266
267 if (StrVal[0] == 'R') {
268 // FIXME: C++11 does not specify how to handle raw-string-literals here.
269 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
270 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
271 "Invalid raw string token!");
272
273 // Measure the length of the d-char-sequence.
274 unsigned NumDChars = 0;
275 while (StrVal[2 + NumDChars] != '(') {
276 assert(NumDChars < (StrVal.size() - 5) / 2 &&
277 "Invalid raw string token!");
278 ++NumDChars;
279 }
280 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
281
282 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
283 // parens below.
284 StrVal.erase(0, 2 + NumDChars);
285 StrVal.erase(StrVal.size() - 1 - NumDChars);
286 } else {
287 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
288 "Invalid string token!");
289
290 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000291 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000292 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000293 // Skip escapes. \\ -> '\' and \" -> '"'.
294 if (StrVal[i] == '\\' && i + 1 < e &&
295 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
296 ++i;
297 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000298 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000299 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000300 }
Mike Stump11289f42009-09-09 15:08:12 +0000301
Chris Lattnerb694ba72006-07-02 22:41:36 +0000302 // Remove the front quote, replacing it with a space, so that the pragma
303 // contents appear to have a space before them.
304 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000305
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000306 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000307 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000308
Peter Collingbournef29ce972011-02-22 13:49:06 +0000309 // Plop the string (including the newline and trailing null) into a buffer
310 // where we can lex it.
311 Token TmpTok;
312 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000313 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000314 SourceLocation TokLoc = TmpTok.getLocation();
315
316 // Make and enter a lexer object so that we lex and expand the tokens just
317 // like any others.
318 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
319 StrVal.size(), *this);
320
Craig Topperd2d442c2014-05-17 23:10:59 +0000321 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000322
323 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000324 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000325
326 // Finally, return whatever came after the pragma directive.
327 return Lex(Tok);
328}
329
330/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
331/// is not enclosed within a string literal.
332void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
333 // Remember the pragma token location.
334 SourceLocation PragmaLoc = Tok.getLocation();
335
336 // Read the '('.
337 Lex(Tok);
338 if (Tok.isNot(tok::l_paren)) {
339 Diag(PragmaLoc, diag::err__Pragma_malformed);
340 return;
341 }
342
Peter Collingbournef29ce972011-02-22 13:49:06 +0000343 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000344 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000345 int NumParens = 0;
346 Lex(Tok);
347 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000348 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000349 if (Tok.is(tok::l_paren))
350 NumParens++;
351 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
352 break;
John McCall89e925d2010-08-28 22:34:47 +0000353 Lex(Tok);
354 }
355
John McCall49039d42010-08-29 01:09:54 +0000356 if (Tok.is(tok::eof)) {
357 Diag(PragmaLoc, diag::err_unterminated___pragma);
358 return;
359 }
360
Peter Collingbournef29ce972011-02-22 13:49:06 +0000361 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000362
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000363 // Replace the ')' with an EOD to mark the end of the pragma.
364 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000365
366 Token *TokArray = new Token[PragmaToks.size()];
367 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
368
369 // Push the tokens onto the stack.
Ilya Biryukov929af672019-05-17 09:32:05 +0000370 EnterTokenStream(TokArray, PragmaToks.size(), true, true,
371 /*IsReinject*/ false);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000372
373 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000374 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000375
376 // Finally, return whatever came after the pragma directive.
377 return Lex(Tok);
378}
379
James Dennett18a6d792012-06-17 03:26:26 +0000380/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattner146762e2007-07-20 16:59:19 +0000381void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000382 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000383 // this is a prefix to a TU, which indicates we're generating a PCH file, or
384 // when the main file is a header (e.g. when -xc-header is provided on the
385 // commandline).
386 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000387 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
388 return;
389 }
Mike Stump11289f42009-09-09 15:08:12 +0000390
Chris Lattnerb694ba72006-07-02 22:41:36 +0000391 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000392 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000393 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000394}
395
Chris Lattnerc2383312007-12-19 19:38:36 +0000396void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000397 assert(CurPPLexer && "No current lexer?");
Erich Keane0a6b5b62018-12-04 14:34:09 +0000398 CurLexer->ReadToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000399}
400
James Dennett18a6d792012-06-17 03:26:26 +0000401/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000402void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000403 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000404
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000405 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000406 // Read the next token to poison. While doing this, pretend that we are
407 // skipping while reading the identifier to poison.
408 // This avoids errors on code like:
409 // #pragma GCC poison X
410 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000411 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000412 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000413 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattnerb694ba72006-07-02 22:41:36 +0000415 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000416 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000417
Chris Lattnerb694ba72006-07-02 22:41:36 +0000418 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000419 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000420 Diag(Tok, diag::err_pp_invalid_poison);
421 return;
422 }
Mike Stump11289f42009-09-09 15:08:12 +0000423
Chris Lattnercefc7682006-07-08 08:28:12 +0000424 // Look up the identifier info for the token. We disabled identifier lookup
425 // by saying we're skipping contents, so we need to do this manually.
426 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000427
Chris Lattnerb694ba72006-07-02 22:41:36 +0000428 // Already poisoned.
429 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattnerb694ba72006-07-02 22:41:36 +0000431 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000432 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000433 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattnerb694ba72006-07-02 22:41:36 +0000435 // Finally, poison it!
436 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000437 if (II->isFromAST())
438 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000439 }
440}
441
James Dennett18a6d792012-06-17 03:26:26 +0000442/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000443/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000444void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000445 if (isInPrimaryFile()) {
446 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
447 return;
448 }
Mike Stump11289f42009-09-09 15:08:12 +0000449
Chris Lattnerb694ba72006-07-02 22:41:36 +0000450 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000451 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000452
Chris Lattnerb694ba72006-07-02 22:41:36 +0000453 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000454 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000455
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000456 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000457 if (PLoc.isInvalid())
458 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000459
Jay Foad9a6b0982011-06-21 15:13:30 +0000460 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000461
Chris Lattner3bdc7672011-05-22 22:10:16 +0000462 // Notify the client, if desired, that we are in a new source file.
463 if (Callbacks)
464 Callbacks->FileChanged(SysHeaderTok.getLocation(),
465 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
466
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000467 // Emit a line marker. This will change any source locations from this point
468 // forward to realize they are in a system header.
469 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000470 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000471 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000472 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000473}
474
James Dennett18a6d792012-06-17 03:26:26 +0000475/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattner146762e2007-07-20 16:59:19 +0000476void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
477 Token FilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000478 if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000479 return;
Mike Stump11289f42009-09-09 15:08:12 +0000480
Richard Smithb9b05102019-03-19 01:51:19 +0000481 // If the next token wasn't a header-name, diagnose the error.
Richard Smith91e150d2019-03-19 22:09:55 +0000482 if (FilenameTok.isNot(tok::header_name)) {
Richard Smithb9b05102019-03-19 01:51:19 +0000483 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
484 return;
485 }
486
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000487 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000488 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000489 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000490 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000491 if (Invalid)
492 return;
Mike Stump11289f42009-09-09 15:08:12 +0000493
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000494 bool isAngled =
495 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000496 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
497 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000498 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000499 return;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000501 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000502 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000503 const FileEntry *File =
504 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000505 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000506 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000507 if (!SuppressIncludeNotFoundError)
508 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000509 return;
510 }
Mike Stump11289f42009-09-09 15:08:12 +0000511
Chris Lattnerd32480d2009-01-17 06:22:33 +0000512 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000513
514 // If this file is older than the file it depends on, emit a diagnostic.
515 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
516 // Lex tokens at the end of the message and include them in the message.
517 std::string Message;
518 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000519 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000520 Message += getSpelling(DependencyTok) + " ";
521 Lex(DependencyTok);
522 }
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattnerf0b04972010-09-05 23:16:09 +0000524 // Remove the trailing ' ' if present.
525 if (!Message.empty())
526 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000527 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000528 }
529}
530
Reid Kleckner002562a2013-05-06 21:02:12 +0000531/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000532/// Return the IdentifierInfo* associated with the macro to push or pop.
533IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
534 // Remember the pragma token location.
535 Token PragmaTok = Tok;
536
537 // Read the '('.
538 Lex(Tok);
539 if (Tok.isNot(tok::l_paren)) {
540 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
541 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000542 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000543 }
544
545 // Read the macro name string.
546 Lex(Tok);
547 if (Tok.isNot(tok::string_literal)) {
548 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
549 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000550 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000551 }
552
Richard Smithd67aea22012-03-06 03:21:47 +0000553 if (Tok.hasUDSuffix()) {
554 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000555 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000556 }
557
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000558 // Remember the macro string.
559 std::string StrVal = getSpelling(Tok);
560
561 // Read the ')'.
562 Lex(Tok);
563 if (Tok.isNot(tok::r_paren)) {
564 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
565 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000566 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000567 }
568
569 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
570 "Invalid string token!");
571
572 // Create a Token from the string.
573 Token MacroTok;
574 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000575 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000576 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000577
578 // Get the IdentifierInfo of MacroToPushTok.
579 return LookUpIdentifierInfo(MacroTok);
580}
581
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000582/// Handle \#pragma push_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000583///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000584/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000585/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000586/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000587/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000588void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
589 // Parse the pragma directive and get the macro IdentifierInfo*.
590 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
591 if (!IdentInfo) return;
592
593 // Get the MacroInfo associated with IdentInfo.
594 MacroInfo *MI = getMacroInfo(IdentInfo);
Fangrui Song6907ce22018-07-30 19:24:48 +0000595
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000596 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000597 // Allow the original MacroInfo to be redefined later.
598 MI->setIsAllowRedefinitionsWithoutWarning(true);
599 }
600
601 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000602 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000603}
604
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000605/// Handle \#pragma pop_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000606///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000607/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000608/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000609/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000610/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000611void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
612 SourceLocation MessageLoc = PopMacroTok.getLocation();
613
614 // Parse the pragma directive and get the macro IdentifierInfo*.
615 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
616 if (!IdentInfo) return;
617
618 // Find the vector<MacroInfo*> associated with the macro.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000619 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000620 PragmaPushMacroInfo.find(IdentInfo);
621 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000622 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000623 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000624 if (MI->isWarnIfUnused())
625 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
626 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000627 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000628
629 // Get the MacroInfo we want to reinstall.
630 MacroInfo *MacroToReInstall = iter->second.back();
631
Richard Smith713369b2015-04-23 20:40:50 +0000632 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000633 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000634 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000635
636 // Pop PragmaPushMacroInfo stack.
637 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000638 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000639 PragmaPushMacroInfo.erase(iter);
640 } else {
641 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
642 << IdentInfo->getName();
643 }
644}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000645
Aaron Ballman611306e2012-03-02 22:51:54 +0000646void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000647 // We will either get a quoted filename or a bracketed filename, and we
Aaron Ballman611306e2012-03-02 22:51:54 +0000648 // have to track which we got. The first filename is the source name,
649 // and the second name is the mapped filename. If the first is quoted,
650 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000651
652 // Get the open paren
653 Lex(Tok);
654 if (Tok.isNot(tok::l_paren)) {
655 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
656 return;
657 }
658
659 // We expect either a quoted string literal, or a bracketed name
660 Token SourceFilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000661 if (LexHeaderName(SourceFilenameTok))
Aaron Ballman611306e2012-03-02 22:51:54 +0000662 return;
Aaron Ballman611306e2012-03-02 22:51:54 +0000663
664 StringRef SourceFileName;
665 SmallString<128> FileNameBuffer;
Richard Smith91e150d2019-03-19 22:09:55 +0000666 if (SourceFilenameTok.is(tok::header_name)) {
Aaron Ballman611306e2012-03-02 22:51:54 +0000667 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
Aaron Ballman611306e2012-03-02 22:51:54 +0000668 } else {
669 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
670 return;
671 }
672 FileNameBuffer.clear();
673
674 // Now we expect a comma, followed by another include name
675 Lex(Tok);
676 if (Tok.isNot(tok::comma)) {
677 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
678 return;
679 }
680
681 Token ReplaceFilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000682 if (LexHeaderName(ReplaceFilenameTok))
Aaron Ballman611306e2012-03-02 22:51:54 +0000683 return;
Aaron Ballman611306e2012-03-02 22:51:54 +0000684
685 StringRef ReplaceFileName;
Richard Smith91e150d2019-03-19 22:09:55 +0000686 if (ReplaceFilenameTok.is(tok::header_name)) {
Aaron Ballman611306e2012-03-02 22:51:54 +0000687 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
Aaron Ballman611306e2012-03-02 22:51:54 +0000688 } else {
689 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
690 return;
691 }
692
693 // Finally, we expect the closing paren
694 Lex(Tok);
695 if (Tok.isNot(tok::r_paren)) {
696 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
697 return;
698 }
699
700 // Now that we have the source and target filenames, we need to make sure
701 // they're both of the same type (angled vs non-angled)
702 StringRef OriginalSource = SourceFileName;
703
Fangrui Song6907ce22018-07-30 19:24:48 +0000704 bool SourceIsAngled =
705 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
Aaron Ballman611306e2012-03-02 22:51:54 +0000706 SourceFileName);
707 bool ReplaceIsAngled =
708 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
709 ReplaceFileName);
710 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
711 (SourceIsAngled != ReplaceIsAngled)) {
712 unsigned int DiagID;
713 if (SourceIsAngled)
714 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
715 else
716 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
717
718 Diag(SourceFilenameTok.getLocation(), DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +0000719 << SourceFileName
Aaron Ballman611306e2012-03-02 22:51:54 +0000720 << ReplaceFileName;
721
722 return;
723 }
724
725 // Now we can let the include handler know about this mapping
726 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
727}
728
Richard Smith9565c75b2017-06-19 23:09:36 +0000729// Lex a component of a module name: either an identifier or a string literal;
730// for components that can be expressed both ways, the two forms are equivalent.
731static bool LexModuleNameComponent(
732 Preprocessor &PP, Token &Tok,
733 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
734 bool First) {
735 PP.LexUnexpandedToken(Tok);
736 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
737 StringLiteralParser Literal(Tok, PP);
738 if (Literal.hadError)
739 return true;
740 ModuleNameComponent = std::make_pair(
741 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
742 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
743 ModuleNameComponent =
744 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
745 } else {
746 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
747 return true;
748 }
749 return false;
750}
751
752static bool LexModuleName(
753 Preprocessor &PP, Token &Tok,
754 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
755 &ModuleName) {
756 while (true) {
757 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
758 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
759 return true;
760 ModuleName.push_back(NameComponent);
761
762 PP.LexUnexpandedToken(Tok);
763 if (Tok.isNot(tok::period))
764 return false;
765 }
766}
767
Richard Smith5d2ed482017-06-09 19:22:32 +0000768void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
769 SourceLocation Loc = Tok.getLocation();
770
Richard Smith9565c75b2017-06-19 23:09:36 +0000771 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
772 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000773 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000774 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000775
776 LexUnexpandedToken(Tok);
777 if (Tok.isNot(tok::eod)) {
778 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
779 DiscardUntilEndOfDirective();
780 }
781
Richard Smith5d2ed482017-06-09 19:22:32 +0000782 CurLexer->LexingRawMode = true;
783
784 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
785 if (Tok.getKind() != tok::raw_identifier ||
786 Tok.getRawIdentifier() != Ident)
787 return false;
788 CurLexer->Lex(Tok);
789 return true;
790 };
791
792 // Scan forward looking for the end of the module.
793 const char *Start = CurLexer->getBufferLocation();
794 const char *End = nullptr;
795 unsigned NestingLevel = 1;
796 while (true) {
797 End = CurLexer->getBufferLocation();
798 CurLexer->Lex(Tok);
799
800 if (Tok.is(tok::eof)) {
801 Diag(Loc, diag::err_pp_module_build_missing_end);
802 break;
803 }
804
805 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
806 // Token was part of module; keep going.
807 continue;
808 }
809
810 // We hit something directive-shaped; check to see if this is the end
811 // of the module build.
812 CurLexer->ParsingPreprocessorDirective = true;
813 CurLexer->Lex(Tok);
814 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
815 TryConsumeIdentifier("module")) {
816 if (TryConsumeIdentifier("build"))
817 // #pragma clang module build -> entering a nested module build.
818 ++NestingLevel;
819 else if (TryConsumeIdentifier("endbuild")) {
820 // #pragma clang module endbuild -> leaving a module build.
821 if (--NestingLevel == 0)
822 break;
823 }
824 // We should either be looking at the EOD or more of the current directive
825 // preceding the EOD. Either way we can ignore this token and keep going.
826 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
827 }
828 }
829
830 CurLexer->LexingRawMode = false;
831
832 // Load the extracted text as a preprocessed module.
833 assert(CurLexer->getBuffer().begin() <= Start &&
834 Start <= CurLexer->getBuffer().end() &&
835 CurLexer->getBuffer().begin() <= End &&
836 End <= CurLexer->getBuffer().end() &&
837 "module source range not contained within same file buffer");
838 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
839 StringRef(Start, End - Start));
840}
841
Mike Rice58df1af2018-09-11 17:10:44 +0000842void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
843 Lex(Tok);
844 if (Tok.is(tok::l_paren)) {
845 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
846
847 std::string FileName;
848 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
849 return;
850
851 if (Tok.isNot(tok::r_paren)) {
852 Diag(Tok, diag::err_expected) << tok::r_paren;
853 return;
854 }
855 Lex(Tok);
856 }
857 if (Tok.isNot(tok::eod))
858 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
859 << "pragma hdrstop";
860
861 if (creatingPCHWithPragmaHdrStop() &&
862 SourceMgr.isInMainFile(Tok.getLocation())) {
863 assert(CurLexer && "no lexer for #pragma hdrstop processing");
864 Token &Result = Tok;
865 Result.startToken();
866 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
867 CurLexer->cutOffLexing();
868 }
869 if (usingPCHWithPragmaHdrStop())
870 SkippingUntilPragmaHdrStop = false;
871}
872
Chris Lattnerb694ba72006-07-02 22:41:36 +0000873/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
874/// If 'Namespace' is non-null, then it is a token required to exist on the
875/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000877 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000878 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000879
Chris Lattnerb694ba72006-07-02 22:41:36 +0000880 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000881 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000882 // If there is already a pragma handler with the name of this namespace,
883 // we either have an error (directive with the same name as a namespace) or
884 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000885 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000886 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000887 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000888 " handler with the same name!");
889 } else {
890 // Otherwise, this namespace doesn't exist yet, create and insert the
891 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000892 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000893 PragmaHandlers->AddPragma(InsertNS);
894 }
895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
Chris Lattnerb694ba72006-07-02 22:41:36 +0000897 // Check to make sure we don't already have a pragma for this identifier.
898 assert(!InsertNS->FindHandler(Handler->getName()) &&
899 "Pragma handler already exists for this identifier!");
900 InsertNS->AddPragma(Handler);
901}
902
Daniel Dunbar40596532008-10-04 19:17:46 +0000903/// RemovePragmaHandler - Remove the specific pragma handler from the
904/// preprocessor. If \arg Namespace is non-null, then it should be the
905/// namespace that \arg Handler was added to. It is an error to remove
906/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000907void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000908 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000909 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000910
Daniel Dunbar40596532008-10-04 19:17:46 +0000911 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000912 if (!Namespace.empty()) {
913 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000914 assert(Existing && "Namespace containing handler does not exist!");
915
916 NS = Existing->getIfNamespace();
917 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
918 }
919
920 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000921
Craig Topperbe250302014-09-12 05:19:24 +0000922 // If this is a non-default namespace and it is now empty, remove it.
923 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000924 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000925 delete NS;
926 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000927}
928
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000929bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
930 Token Tok;
931 LexUnexpandedToken(Tok);
932
933 if (Tok.isNot(tok::identifier)) {
934 Diag(Tok, diag::ext_on_off_switch_syntax);
935 return true;
936 }
937 IdentifierInfo *II = Tok.getIdentifierInfo();
938 if (II->isStr("ON"))
939 Result = tok::OOS_ON;
940 else if (II->isStr("OFF"))
941 Result = tok::OOS_OFF;
942 else if (II->isStr("DEFAULT"))
943 Result = tok::OOS_DEFAULT;
944 else {
945 Diag(Tok, diag::ext_on_off_switch_syntax);
946 return true;
947 }
948
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000949 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000950 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000951 if (Tok.isNot(tok::eod))
952 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000953 return false;
954}
955
Chris Lattnerb694ba72006-07-02 22:41:36 +0000956namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000957
James Dennett18a6d792012-06-17 03:26:26 +0000958/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000959struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000960 PragmaOnceHandler() : PragmaHandler("once") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000961
Craig Topper9140dd22014-03-11 06:50:42 +0000962 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
963 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000964 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000965 PP.HandlePragmaOnce(OnceTok);
966 }
967};
968
James Dennett18a6d792012-06-17 03:26:26 +0000969/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000970/// rest of the line is not lexed.
971struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000972 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000973
Craig Topper9140dd22014-03-11 06:50:42 +0000974 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
975 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000976 PP.HandlePragmaMark();
977 }
978};
979
James Dennett18a6d792012-06-17 03:26:26 +0000980/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000981struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000982 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000983
Craig Topper9140dd22014-03-11 06:50:42 +0000984 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
985 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000986 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000987 }
988};
989
James Dennett18a6d792012-06-17 03:26:26 +0000990/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +0000991/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000992struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000993 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000994
Craig Topper9140dd22014-03-11 06:50:42 +0000995 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
996 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000997 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000998 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000999 }
1000};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001001
Chris Lattnerb694ba72006-07-02 22:41:36 +00001002struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001003 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001004
Craig Topper9140dd22014-03-11 06:50:42 +00001005 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1006 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001007 PP.HandlePragmaDependency(DepToken);
1008 }
1009};
Mike Stump11289f42009-09-09 15:08:12 +00001010
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001011struct PragmaDebugHandler : public PragmaHandler {
1012 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001013
Craig Topper9140dd22014-03-11 06:50:42 +00001014 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smith77e53cbe2019-04-18 00:57:01 +00001015 Token &DebugToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001016 Token Tok;
1017 PP.LexUnexpandedToken(Tok);
1018 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001019 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001020 return;
1021 }
1022 IdentifierInfo *II = Tok.getIdentifierInfo();
1023
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001024 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001025 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001026 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001027 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001028 } else if (II->isStr("parser_crash")) {
1029 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001030 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001031 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001032 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
Ilya Biryukov929af672019-05-17 09:32:05 +00001033 PP.EnterToken(Crasher, /*IsReinject*/false);
Richard Smithba3a4f92016-01-12 21:59:26 +00001034 } else if (II->isStr("dump")) {
1035 Token Identifier;
1036 PP.LexUnexpandedToken(Identifier);
1037 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1038 Token DumpAnnot;
1039 DumpAnnot.startToken();
1040 DumpAnnot.setKind(tok::annot_pragma_dump);
1041 DumpAnnot.setAnnotationRange(
1042 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1043 DumpAnnot.setAnnotationValue(DumpII);
1044 PP.DiscardUntilEndOfDirective();
Ilya Biryukov929af672019-05-17 09:32:05 +00001045 PP.EnterToken(DumpAnnot, /*IsReinject*/false);
Richard Smithba3a4f92016-01-12 21:59:26 +00001046 } else {
1047 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1048 << II->getName();
1049 }
Richard Smith6c2b5a82018-02-09 01:15:13 +00001050 } else if (II->isStr("diag_mapping")) {
1051 Token DiagName;
1052 PP.LexUnexpandedToken(DiagName);
1053 if (DiagName.is(tok::eod))
1054 PP.getDiagnostics().dump();
1055 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1056 StringLiteralParser Literal(DiagName, PP);
1057 if (Literal.hadError)
1058 return;
1059 PP.getDiagnostics().dump(Literal.GetString());
1060 } else {
1061 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1062 << II->getName();
1063 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001064 } else if (II->isStr("llvm_fatal_error")) {
1065 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1066 } else if (II->isStr("llvm_unreachable")) {
1067 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001068 } else if (II->isStr("macro")) {
1069 Token MacroName;
1070 PP.LexUnexpandedToken(MacroName);
1071 auto *MacroII = MacroName.getIdentifierInfo();
1072 if (MacroII)
1073 PP.dumpMacroInfo(MacroII);
1074 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001075 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1076 << II->getName();
Richard Smith77e53cbe2019-04-18 00:57:01 +00001077 } else if (II->isStr("module_map")) {
1078 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1079 ModuleName;
1080 if (LexModuleName(PP, Tok, ModuleName))
1081 return;
1082 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
1083 Module *M = nullptr;
1084 for (auto IIAndLoc : ModuleName) {
1085 M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
1086 if (!M) {
1087 PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
1088 << IIAndLoc.first;
1089 return;
1090 }
1091 }
1092 M->dump();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001093 } else if (II->isStr("overflow_stack")) {
1094 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001095 } else if (II->isStr("handle_crash")) {
1096 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1097 if (CRC)
1098 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001099 } else if (II->isStr("captured")) {
1100 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001101 } else {
1102 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1103 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001104 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001105
1106 PPCallbacks *Callbacks = PP.getPPCallbacks();
1107 if (Callbacks)
1108 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1109 }
1110
1111 void HandleCaptured(Preprocessor &PP) {
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001112 Token Tok;
1113 PP.LexUnexpandedToken(Tok);
1114
1115 if (Tok.isNot(tok::eod)) {
1116 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1117 << "pragma clang __debug captured";
1118 return;
1119 }
1120
1121 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001122 MutableArrayRef<Token> Toks(
1123 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1124 Toks[0].startToken();
1125 Toks[0].setKind(tok::annot_pragma_captured);
1126 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001127
Ilya Biryukov929af672019-05-17 09:32:05 +00001128 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1129 /*IsReinject=*/false);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001130 }
1131
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001132// Disable MSVC warning about runtime stack overflow.
1133#ifdef _MSC_VER
1134 #pragma warning(disable : 4717)
1135#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001136 static void DebugOverflowStack(void (*P)() = nullptr) {
1137 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1138 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001139 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001140#ifdef _MSC_VER
1141 #pragma warning(default : 4717)
1142#endif
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001143};
1144
James Dennett18a6d792012-06-17 03:26:26 +00001145/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001146struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001147private:
1148 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001149
Chris Lattnerfb42a182009-07-12 21:18:45 +00001150public:
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001151 explicit PragmaDiagnosticHandler(const char *NS)
1152 : PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001153
Craig Topper9140dd22014-03-11 06:50:42 +00001154 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1155 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001156 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001157 Token Tok;
1158 PP.LexUnexpandedToken(Tok);
1159 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001160 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001161 return;
1162 }
1163 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001164 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001165
Alp Toker46df1c02014-06-12 10:15:20 +00001166 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001167 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001168 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001169 else if (Callbacks)
1170 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001171 return;
1172 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001173 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001174 if (Callbacks)
1175 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001176 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001177 }
1178
1179 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1180 .Case("ignored", diag::Severity::Ignored)
1181 .Case("warning", diag::Severity::Warning)
1182 .Case("error", diag::Severity::Error)
1183 .Case("fatal", diag::Severity::Fatal)
1184 .Default(diag::Severity());
1185
1186 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001187 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001188 return;
1189 }
Mike Stump11289f42009-09-09 15:08:12 +00001190
Chris Lattner504af112009-04-19 23:16:58 +00001191 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001192 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001193
Andy Gibbs58905d22012-11-17 19:15:38 +00001194 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001195 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1196 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001197 return;
Mike Stump11289f42009-09-09 15:08:12 +00001198
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001199 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001200 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1201 return;
1202 }
Mike Stump11289f42009-09-09 15:08:12 +00001203
Chris Lattner504af112009-04-19 23:16:58 +00001204 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001205 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001206 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001207 return;
1208 }
Mike Stump11289f42009-09-09 15:08:12 +00001209
Sunil Srivastava5239de72016-02-13 01:44:05 +00001210 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1211 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001212 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001213 bool unknownDiag = false;
1214 if (Group == "everything") {
1215 // Special handling for pragma clang diagnostic ... "-Weverything".
1216 // There is no formal group named "everything", so there has to be a
1217 // special case for it.
1218 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1219 } else
1220 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1221 DiagLoc);
1222 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001223 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1224 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001225 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001226 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001227 }
1228};
Mike Stump11289f42009-09-09 15:08:12 +00001229
Mike Rice58df1af2018-09-11 17:10:44 +00001230/// "\#pragma hdrstop [<header-name-string>]"
1231struct PragmaHdrstopHandler : public PragmaHandler {
1232 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1233 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1234 Token &DepToken) override {
1235 PP.HandlePragmaHdrstop(DepToken);
1236 }
1237};
1238
Reid Kleckner881dff32013-09-13 22:00:30 +00001239/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1240/// diagnostics, so we don't really implement this pragma. We parse it and
1241/// ignore it to avoid -Wunknown-pragma warnings.
1242struct PragmaWarningHandler : public PragmaHandler {
1243 PragmaWarningHandler() : PragmaHandler("warning") {}
1244
Craig Topper9140dd22014-03-11 06:50:42 +00001245 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1246 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001247 // Parse things like:
1248 // warning(push, 1)
1249 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001250 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001251 SourceLocation DiagLoc = Tok.getLocation();
1252 PPCallbacks *Callbacks = PP.getPPCallbacks();
1253
1254 PP.Lex(Tok);
1255 if (Tok.isNot(tok::l_paren)) {
1256 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1257 return;
1258 }
1259
1260 PP.Lex(Tok);
1261 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001262
Alexander Musman6b080fc2015-05-25 11:21:20 +00001263 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001264 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001265 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001266 PP.Lex(Tok);
1267 if (Tok.is(tok::comma)) {
1268 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001269 uint64_t Value;
1270 if (Tok.is(tok::numeric_constant) &&
1271 PP.parseSimpleIntegerLiteral(Tok, Value))
1272 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001273 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001274 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1275 return;
1276 }
1277 }
1278 if (Callbacks)
1279 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001280 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001281 // #pragma warning( pop )
1282 PP.Lex(Tok);
1283 if (Callbacks)
1284 Callbacks->PragmaWarningPop(DiagLoc);
1285 } else {
1286 // #pragma warning( warning-specifier : warning-number-list
1287 // [; warning-specifier : warning-number-list...] )
1288 while (true) {
1289 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001290 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001291 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1292 return;
1293 }
1294
1295 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001296 bool SpecifierValid;
1297 StringRef Specifier;
1298 llvm::SmallString<1> SpecifierBuf;
1299 if (II) {
1300 Specifier = II->getName();
1301 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1302 .Cases("default", "disable", "error", "once",
1303 "suppress", true)
1304 .Default(false);
1305 // If we read a correct specifier, snatch next token (that should be
1306 // ":", checked later).
1307 if (SpecifierValid)
1308 PP.Lex(Tok);
1309 } else {
1310 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1311 uint64_t Value;
1312 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1313 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1314 SpecifierValid = (Value >= 1) && (Value <= 4);
1315 } else
1316 SpecifierValid = false;
1317 // Next token already snatched by parseSimpleIntegerLiteral.
1318 }
1319
Reid Kleckner881dff32013-09-13 22:00:30 +00001320 if (!SpecifierValid) {
1321 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1322 return;
1323 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001324 if (Tok.isNot(tok::colon)) {
1325 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1326 return;
1327 }
1328
1329 // Collect the warning ids.
1330 SmallVector<int, 4> Ids;
1331 PP.Lex(Tok);
1332 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001333 uint64_t Value;
1334 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001335 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001336 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1337 return;
1338 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001339 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001340 }
1341 if (Callbacks)
1342 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1343
1344 // Parse the next specifier if there is a semicolon.
1345 if (Tok.isNot(tok::semi))
1346 break;
1347 PP.Lex(Tok);
1348 }
1349 }
1350
1351 if (Tok.isNot(tok::r_paren)) {
1352 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1353 return;
1354 }
1355
1356 PP.Lex(Tok);
1357 if (Tok.isNot(tok::eod))
1358 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1359 }
1360};
1361
Reid Kleckner0f56b222019-03-14 18:12:17 +00001362/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1363/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1364/// otherwise to avoid -Wunknown-pragma warnings.
1365struct PragmaExecCharsetHandler : public PragmaHandler {
1366 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1367
1368 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1369 Token &Tok) override {
1370 // Parse things like:
1371 // execution_character_set(push, "UTF-8")
1372 // execution_character_set(pop)
1373 SourceLocation DiagLoc = Tok.getLocation();
1374 PPCallbacks *Callbacks = PP.getPPCallbacks();
1375
1376 PP.Lex(Tok);
1377 if (Tok.isNot(tok::l_paren)) {
1378 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1379 return;
1380 }
1381
1382 PP.Lex(Tok);
1383 IdentifierInfo *II = Tok.getIdentifierInfo();
1384
1385 if (II && II->isStr("push")) {
1386 // #pragma execution_character_set( push[ , string ] )
1387 PP.Lex(Tok);
1388 if (Tok.is(tok::comma)) {
1389 PP.Lex(Tok);
1390
1391 std::string ExecCharset;
1392 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1393 "pragma execution_character_set",
1394 /*MacroExpansion=*/false))
1395 return;
1396
1397 // MSVC supports either of these, but nothing else.
1398 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1399 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1400 return;
1401 }
1402 }
1403 if (Callbacks)
1404 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1405 } else if (II && II->isStr("pop")) {
1406 // #pragma execution_character_set( pop )
1407 PP.Lex(Tok);
1408 if (Callbacks)
1409 Callbacks->PragmaExecCharsetPop(DiagLoc);
1410 } else {
1411 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1412 return;
1413 }
1414
1415 if (Tok.isNot(tok::r_paren)) {
1416 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1417 return;
1418 }
1419
1420 PP.Lex(Tok);
1421 if (Tok.isNot(tok::eod))
1422 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1423 }
1424};
1425
James Dennett18a6d792012-06-17 03:26:26 +00001426/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001427struct PragmaIncludeAliasHandler : public PragmaHandler {
1428 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001429
Craig Topper9140dd22014-03-11 06:50:42 +00001430 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1431 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001432 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001433 }
1434};
1435
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001436/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1437/// extension. The syntax is:
1438/// \code
1439/// #pragma message(string)
1440/// \endcode
1441/// OR, in GCC mode:
1442/// \code
1443/// #pragma message string
1444/// \endcode
1445/// string is a string, which is fully macro expanded, and permits string
1446/// concatenation, embedded escape characters, etc... See MSDN for more details.
1447/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1448/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001449struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001450private:
1451 const PPCallbacks::PragmaMessageKind Kind;
1452 const StringRef Namespace;
1453
1454 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1455 bool PragmaNameOnly = false) {
1456 switch (Kind) {
1457 case PPCallbacks::PMK_Message:
1458 return PragmaNameOnly ? "message" : "pragma message";
1459 case PPCallbacks::PMK_Warning:
1460 return PragmaNameOnly ? "warning" : "pragma warning";
1461 case PPCallbacks::PMK_Error:
1462 return PragmaNameOnly ? "error" : "pragma error";
1463 }
1464 llvm_unreachable("Unknown PragmaMessageKind!");
1465 }
1466
1467public:
1468 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1469 StringRef Namespace = StringRef())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001470 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1471 Namespace(Namespace) {}
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001472
Craig Topper9140dd22014-03-11 06:50:42 +00001473 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1474 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001475 SourceLocation MessageLoc = Tok.getLocation();
1476 PP.Lex(Tok);
1477 bool ExpectClosingParen = false;
1478 switch (Tok.getKind()) {
1479 case tok::l_paren:
1480 // We have a MSVC style pragma message.
1481 ExpectClosingParen = true;
1482 // Read the string.
1483 PP.Lex(Tok);
1484 break;
1485 case tok::string_literal:
1486 // We have a GCC style pragma message, and we just read the string.
1487 break;
1488 default:
1489 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1490 return;
1491 }
1492
1493 std::string MessageString;
1494 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1495 /*MacroExpansion=*/true))
1496 return;
1497
1498 if (ExpectClosingParen) {
1499 if (Tok.isNot(tok::r_paren)) {
1500 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1501 return;
1502 }
1503 PP.Lex(Tok); // eat the r_paren.
1504 }
1505
1506 if (Tok.isNot(tok::eod)) {
1507 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1508 return;
1509 }
1510
1511 // Output the message.
1512 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1513 ? diag::err_pragma_message
1514 : diag::warn_pragma_message) << MessageString;
1515
1516 // If the pragma is lexically sound, notify any interested PPCallbacks.
1517 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1518 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001519 }
1520};
1521
Richard Smithc51c38b2017-04-29 00:34:47 +00001522/// Handle the clang \#pragma module import extension. The syntax is:
1523/// \code
1524/// #pragma clang module import some.module.name
1525/// \endcode
1526struct PragmaModuleImportHandler : public PragmaHandler {
1527 PragmaModuleImportHandler() : PragmaHandler("import") {}
1528
1529 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001530 Token &Tok) override {
1531 SourceLocation ImportLoc = Tok.getLocation();
1532
1533 // Read the module name.
1534 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1535 ModuleName;
1536 if (LexModuleName(PP, Tok, ModuleName))
1537 return;
1538
1539 if (Tok.isNot(tok::eod))
1540 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1541
1542 // If we have a non-empty module path, load the named module.
1543 Module *Imported =
1544 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1545 /*IsIncludeDirective=*/false);
1546 if (!Imported)
1547 return;
1548
1549 PP.makeModuleVisible(Imported, ImportLoc);
1550 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1551 tok::annot_module_include, Imported);
1552 if (auto *CB = PP.getPPCallbacks())
1553 CB->moduleImport(ImportLoc, ModuleName, Imported);
1554 }
1555};
1556
1557/// Handle the clang \#pragma module begin extension. The syntax is:
1558/// \code
1559/// #pragma clang module begin some.module.name
1560/// ...
1561/// #pragma clang module end
1562/// \endcode
1563struct PragmaModuleBeginHandler : public PragmaHandler {
1564 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1565
1566 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1567 Token &Tok) override {
1568 SourceLocation BeginLoc = Tok.getLocation();
1569
1570 // Read the module name.
1571 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1572 ModuleName;
1573 if (LexModuleName(PP, Tok, ModuleName))
1574 return;
1575
1576 if (Tok.isNot(tok::eod))
1577 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1578
1579 // We can only enter submodules of the current module.
1580 StringRef Current = PP.getLangOpts().CurrentModule;
1581 if (ModuleName.front().first->getName() != Current) {
1582 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1583 << ModuleName.front().first << (ModuleName.size() > 1)
1584 << Current.empty() << Current;
1585 return;
1586 }
1587
1588 // Find the module we're entering. We require that a module map for it
1589 // be loaded or implicitly loadable.
David Blaikie89e58dd2019-05-07 21:38:51 +00001590 auto &HSI = PP.getHeaderSearchInfo();
1591 Module *M = HSI.lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001592 if (!M) {
1593 PP.Diag(ModuleName.front().second,
1594 diag::err_pp_module_begin_no_module_map) << Current;
1595 return;
1596 }
1597 for (unsigned I = 1; I != ModuleName.size(); ++I) {
David Blaikie89e58dd2019-05-07 21:38:51 +00001598 auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
Richard Smithd1386302017-05-04 00:29:54 +00001599 if (!NewM) {
1600 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1601 << M->getFullModuleName() << ModuleName[I].first;
1602 return;
1603 }
1604 M = NewM;
1605 }
1606
Richard Smith51d09c52017-05-30 05:22:59 +00001607 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001608 if (Preprocessor::checkModuleIsAvailable(
1609 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001610 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1611 << M->getTopLevelModuleName();
1612 return;
1613 }
1614
Richard Smithd1386302017-05-04 00:29:54 +00001615 // Enter the scope of the submodule.
1616 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1617 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1618 tok::annot_module_begin, M);
1619 }
1620};
1621
1622/// Handle the clang \#pragma module end extension.
1623struct PragmaModuleEndHandler : public PragmaHandler {
1624 PragmaModuleEndHandler() : PragmaHandler("end") {}
1625
1626 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1627 Token &Tok) override {
1628 SourceLocation Loc = Tok.getLocation();
1629
1630 PP.LexUnexpandedToken(Tok);
1631 if (Tok.isNot(tok::eod))
1632 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1633
1634 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1635 if (M)
1636 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1637 else
1638 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001639 }
1640};
1641
Richard Smith5d2ed482017-06-09 19:22:32 +00001642/// Handle the clang \#pragma module build extension.
1643struct PragmaModuleBuildHandler : public PragmaHandler {
1644 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1645
1646 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1647 Token &Tok) override {
1648 PP.HandlePragmaModuleBuild(Tok);
1649 }
1650};
1651
1652/// Handle the clang \#pragma module load extension.
1653struct PragmaModuleLoadHandler : public PragmaHandler {
1654 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1655
1656 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1657 Token &Tok) override {
1658 SourceLocation Loc = Tok.getLocation();
1659
1660 // Read the module name.
1661 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1662 ModuleName;
1663 if (LexModuleName(PP, Tok, ModuleName))
1664 return;
1665
1666 if (Tok.isNot(tok::eod))
1667 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1668
1669 // Load the module, don't make it visible.
1670 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1671 /*IsIncludeDirective=*/false);
1672 }
1673};
1674
James Dennett18a6d792012-06-17 03:26:26 +00001675/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001676/// macro on the top of the stack.
1677struct PragmaPushMacroHandler : public PragmaHandler {
1678 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001679
Craig Topper9140dd22014-03-11 06:50:42 +00001680 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1681 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001682 PP.HandlePragmaPushMacro(PushMacroTok);
1683 }
1684};
1685
James Dennett18a6d792012-06-17 03:26:26 +00001686/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001687/// macro to the value on the top of the stack.
1688struct PragmaPopMacroHandler : public PragmaHandler {
1689 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001690
Craig Topper9140dd22014-03-11 06:50:42 +00001691 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1692 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001693 PP.HandlePragmaPopMacro(PopMacroTok);
1694 }
1695};
1696
Fangrui Song6907ce22018-07-30 19:24:48 +00001697/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001698/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001699struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1700 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001701
Craig Topper9140dd22014-03-11 06:50:42 +00001702 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1703 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001704 SourceLocation Loc = NameTok.getLocation();
1705 bool IsBegin;
1706
1707 Token Tok;
1708
1709 // Lex the 'begin' or 'end'.
1710 PP.LexUnexpandedToken(Tok);
1711 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1712 if (BeginEnd && BeginEnd->isStr("begin")) {
1713 IsBegin = true;
1714 } else if (BeginEnd && BeginEnd->isStr("end")) {
1715 IsBegin = false;
1716 } else {
1717 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1718 return;
1719 }
1720
1721 // Verify that this is followed by EOD.
1722 PP.LexUnexpandedToken(Tok);
1723 if (Tok.isNot(tok::eod))
1724 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1725
1726 // The start location of the active audit.
1727 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1728
1729 // The start location we want after processing this.
1730 SourceLocation NewLoc;
1731
1732 if (IsBegin) {
1733 // Complain about attempts to re-enter an audit.
1734 if (BeginLoc.isValid()) {
1735 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1736 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1737 }
1738 NewLoc = Loc;
1739 } else {
1740 // Complain about attempts to leave an audit that doesn't exist.
1741 if (!BeginLoc.isValid()) {
1742 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1743 return;
1744 }
1745 NewLoc = SourceLocation();
1746 }
1747
1748 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1749 }
1750};
1751
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001752/// PragmaAssumeNonNullHandler -
1753/// \#pragma clang assume_nonnull begin/end
1754struct PragmaAssumeNonNullHandler : public PragmaHandler {
1755 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001756
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001757 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1758 Token &NameTok) override {
1759 SourceLocation Loc = NameTok.getLocation();
1760 bool IsBegin;
1761
1762 Token Tok;
1763
1764 // Lex the 'begin' or 'end'.
1765 PP.LexUnexpandedToken(Tok);
1766 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1767 if (BeginEnd && BeginEnd->isStr("begin")) {
1768 IsBegin = true;
1769 } else if (BeginEnd && BeginEnd->isStr("end")) {
1770 IsBegin = false;
1771 } else {
1772 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1773 return;
1774 }
1775
1776 // Verify that this is followed by EOD.
1777 PP.LexUnexpandedToken(Tok);
1778 if (Tok.isNot(tok::eod))
1779 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1780
1781 // The start location of the active audit.
1782 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1783
1784 // The start location we want after processing this.
1785 SourceLocation NewLoc;
Eli Friedman16fee082017-09-27 23:29:37 +00001786 PPCallbacks *Callbacks = PP.getPPCallbacks();
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001787
1788 if (IsBegin) {
1789 // Complain about attempts to re-enter an audit.
1790 if (BeginLoc.isValid()) {
1791 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1792 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1793 }
1794 NewLoc = Loc;
Eli Friedman16fee082017-09-27 23:29:37 +00001795 if (Callbacks)
1796 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001797 } else {
1798 // Complain about attempts to leave an audit that doesn't exist.
1799 if (!BeginLoc.isValid()) {
1800 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1801 return;
1802 }
1803 NewLoc = SourceLocation();
Eli Friedman16fee082017-09-27 23:29:37 +00001804 if (Callbacks)
1805 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001806 }
1807
1808 PP.setPragmaAssumeNonNullLoc(NewLoc);
1809 }
1810};
1811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001812/// Handle "\#pragma region [...]"
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001813///
1814/// The syntax is
1815/// \code
1816/// #pragma region [optional name]
1817/// #pragma endregion [optional comment]
1818/// \endcode
1819///
1820/// \note This is
1821/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1822/// pragma, just skipped by compiler.
1823struct PragmaRegionHandler : public PragmaHandler {
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001824 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
Aaron Ballman406ea512012-11-30 19:52:30 +00001825
Craig Topper9140dd22014-03-11 06:50:42 +00001826 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1827 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001828 // #pragma region: endregion matches can be verified
1829 // __pragma(region): no sense, but ignored by msvc
1830 // _Pragma is not valid for MSVC, but there isn't any point
1831 // to handle a _Pragma differently.
1832 }
1833};
Aaron Ballman406ea512012-11-30 19:52:30 +00001834
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001835} // namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001836
1837/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001838/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001839void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001840 AddPragmaHandler(new PragmaOnceHandler());
1841 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001842 AddPragmaHandler(new PragmaPushMacroHandler());
1843 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001844 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001845
Chris Lattnerb61448d2009-05-12 18:21:11 +00001846 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001847 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1848 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1849 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001850 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001851 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1852 "GCC"));
1853 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1854 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001855 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001856 AddPragmaHandler("clang", new PragmaPoisonHandler());
1857 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001858 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001859 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001860 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001861 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001862 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001863
Richard Smithc51c38b2017-04-29 00:34:47 +00001864 // #pragma clang module ...
1865 auto *ModuleHandler = new PragmaNamespace("module");
1866 AddPragmaHandler("clang", ModuleHandler);
1867 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001868 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1869 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001870 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1871 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Fangrui Song6907ce22018-07-30 19:24:48 +00001872
Matt Davis1edb9052018-01-27 00:25:29 +00001873 // Add region pragmas.
1874 AddPragmaHandler(new PragmaRegionHandler("region"));
1875 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Richard Smithc51c38b2017-04-29 00:34:47 +00001876
Chris Lattner2ff698d2009-01-16 08:21:25 +00001877 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001878 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001879 AddPragmaHandler(new PragmaWarningHandler());
Reid Kleckner0f56b222019-03-14 18:12:17 +00001880 AddPragmaHandler(new PragmaExecCharsetHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001881 AddPragmaHandler(new PragmaIncludeAliasHandler());
Mike Rice58df1af2018-09-11 17:10:44 +00001882 AddPragmaHandler(new PragmaHdrstopHandler());
Chris Lattner30c924b2010-06-26 17:11:39 +00001883 }
John Brawn8e62db32016-04-04 14:22:58 +00001884
1885 // Pragmas added by plugins
1886 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1887 ie = PragmaHandlerRegistry::end();
1888 it != ie; ++it) {
1889 AddPragmaHandler(it->instantiate().release());
1890 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001891}
Lubos Lunak576a0412014-05-01 12:54:03 +00001892
1893/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1894/// warn about those pragmas being unknown.
1895void Preprocessor::IgnorePragmas() {
1896 AddPragmaHandler(new EmptyPragmaHandler());
1897 // Also ignore all pragmas in all namespaces created
1898 // in Preprocessor::RegisterBuiltinPragmas().
1899 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1900 AddPragmaHandler("clang", new EmptyPragmaHandler());
Lubos Lunak576a0412014-05-01 12:54:03 +00001901}