blob: 5564c0c40a09c38b7177da3dbb1a07daa93fb05d [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
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000147namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000148
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000149/// Helper class for \see Preprocessor::Handle_Pragma.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000150class LexingFor_PragmaRAII {
151 Preprocessor &PP;
152 bool InMacroArgPreExpansion;
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000153 bool Failed = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000154 Token &OutTok;
155 Token PragmaTok;
156
157public:
158 LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
159 Token &Tok)
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000160 : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion), OutTok(Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000161 if (InMacroArgPreExpansion) {
162 PragmaTok = OutTok;
163 PP.EnableBacktrackAtThisPos();
164 }
165 }
166
167 ~LexingFor_PragmaRAII() {
168 if (InMacroArgPreExpansion) {
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000169 // When committing/backtracking the cached pragma tokens in a macro
170 // argument pre-expansion we want to ensure that either the tokens which
171 // have been committed will be removed from the cache or that the tokens
172 // over which we just backtracked won't remain in the cache after they're
173 // consumed and that the caching will stop after consuming them.
174 // Otherwise the caching will interfere with the way macro expansion
175 // works, because we will continue to cache tokens after consuming the
176 // backtracked tokens, which shouldn't happen when we're dealing with
177 // macro argument pre-expansion.
178 auto CachedTokenRange = PP.LastCachedTokenRange();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000179 if (Failed) {
180 PP.CommitBacktrackedTokens();
181 } else {
182 PP.Backtrack();
183 OutTok = PragmaTok;
184 }
Alex Lorenz24a1bed2017-02-24 17:45:16 +0000185 PP.EraseCachedTokens(CachedTokenRange);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000186 }
187 }
188
189 void failed() {
190 Failed = true;
191 }
192};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000193
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000194} // namespace
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000195
Chris Lattnerb694ba72006-07-02 22:41:36 +0000196/// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
197/// return the first token after the directive. The _Pragma token has just
198/// been read into 'Tok'.
Chris Lattner146762e2007-07-20 16:59:19 +0000199void Preprocessor::Handle_Pragma(Token &Tok) {
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000200 // This works differently if we are pre-expanding a macro argument.
201 // In that case we don't actually "activate" the pragma now, we only lex it
202 // until we are sure it is lexically correct and then we backtrack so that
203 // we activate the pragma whenever we encounter the tokens again in the token
204 // stream. This ensures that we will activate it in the correct location
205 // or that we will ignore it if it never enters the token stream, e.g:
206 //
207 // #define EMPTY(x)
208 // #define INACTIVE(x) EMPTY(x)
209 // INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
210
211 LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
212
Chris Lattnerb694ba72006-07-02 22:41:36 +0000213 // Remember the pragma token location.
214 SourceLocation PragmaLoc = Tok.getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000215
Chris Lattnerb694ba72006-07-02 22:41:36 +0000216 // Read the '('.
217 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000218 if (Tok.isNot(tok::l_paren)) {
219 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000220 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000221 }
Chris Lattnerb694ba72006-07-02 22:41:36 +0000222
223 // Read the '"..."'.
224 Lex(Tok);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000225 if (!tok::isStringLiteral(Tok.getKind())) {
Chris Lattner907dfe92008-11-18 07:59:24 +0000226 Diag(PragmaLoc, diag::err__Pragma_malformed);
Hubert Tong0deb6942015-07-30 21:30:00 +0000227 // Skip bad tokens, and the ')', if present.
Reid Kleckner53e6a5d2014-08-14 19:47:06 +0000228 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
Richard Smithd67aea22012-03-06 03:21:47 +0000229 Lex(Tok);
Hubert Tong0deb6942015-07-30 21:30:00 +0000230 while (Tok.isNot(tok::r_paren) &&
231 !Tok.isAtStartOfLine() &&
232 Tok.isNot(tok::eof))
233 Lex(Tok);
Richard Smithd67aea22012-03-06 03:21:47 +0000234 if (Tok.is(tok::r_paren))
235 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000236 return _PragmaLexing.failed();
Richard Smithd67aea22012-03-06 03:21:47 +0000237 }
238
239 if (Tok.hasUDSuffix()) {
240 Diag(Tok, diag::err_invalid_string_udl);
241 // Skip this token, and the ')', if present.
242 Lex(Tok);
243 if (Tok.is(tok::r_paren))
244 Lex(Tok);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000245 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000246 }
Mike Stump11289f42009-09-09 15:08:12 +0000247
Chris Lattnerb694ba72006-07-02 22:41:36 +0000248 // Remember the string.
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000249 Token StrTok = Tok;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000250
251 // Read the ')'.
252 Lex(Tok);
Chris Lattner907dfe92008-11-18 07:59:24 +0000253 if (Tok.isNot(tok::r_paren)) {
254 Diag(PragmaLoc, diag::err__Pragma_malformed);
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000255 return _PragmaLexing.failed();
Chris Lattner907dfe92008-11-18 07:59:24 +0000256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000258 if (InMacroArgPreExpansion)
259 return;
260
Chris Lattner9dc9c202009-02-15 20:52:18 +0000261 SourceLocation RParenLoc = Tok.getLocation();
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000262 std::string StrVal = getSpelling(StrTok);
Mike Stump11289f42009-09-09 15:08:12 +0000263
Richard Smithc98bb4e2013-03-09 23:30:15 +0000264 // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
265 // "The string literal is destringized by deleting any encoding prefix,
Chris Lattner262d4e32009-01-16 18:59:23 +0000266 // deleting the leading and trailing double-quotes, replacing each escape
267 // sequence \" by a double-quote, and replacing each escape sequence \\ by a
268 // single backslash."
Richard Smithc98bb4e2013-03-09 23:30:15 +0000269 if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
270 (StrVal[0] == 'u' && StrVal[1] != '8'))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000271 StrVal.erase(StrVal.begin());
Richard Smithc98bb4e2013-03-09 23:30:15 +0000272 else if (StrVal[0] == 'u')
273 StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
274
275 if (StrVal[0] == 'R') {
276 // FIXME: C++11 does not specify how to handle raw-string-literals here.
277 // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
278 assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
279 "Invalid raw string token!");
280
281 // Measure the length of the d-char-sequence.
282 unsigned NumDChars = 0;
283 while (StrVal[2 + NumDChars] != '(') {
284 assert(NumDChars < (StrVal.size() - 5) / 2 &&
285 "Invalid raw string token!");
286 ++NumDChars;
287 }
288 assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
289
290 // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
291 // parens below.
292 StrVal.erase(0, 2 + NumDChars);
293 StrVal.erase(StrVal.size() - 1 - NumDChars);
294 } else {
295 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
296 "Invalid string token!");
297
298 // Remove escaped quotes and escapes.
Benjamin Kramerc2f5f292013-05-04 10:37:20 +0000299 unsigned ResultPos = 1;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000300 for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
Reid Kleckner95e036c2013-09-25 16:42:48 +0000301 // Skip escapes. \\ -> '\' and \" -> '"'.
302 if (StrVal[i] == '\\' && i + 1 < e &&
303 (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
304 ++i;
305 StrVal[ResultPos++] = StrVal[i];
Richard Smithc98bb4e2013-03-09 23:30:15 +0000306 }
Reid Kleckner95e036c2013-09-25 16:42:48 +0000307 StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
Richard Smithc98bb4e2013-03-09 23:30:15 +0000308 }
Mike Stump11289f42009-09-09 15:08:12 +0000309
Chris Lattnerb694ba72006-07-02 22:41:36 +0000310 // Remove the front quote, replacing it with a space, so that the pragma
311 // contents appear to have a space before them.
312 StrVal[0] = ' ';
Mike Stump11289f42009-09-09 15:08:12 +0000313
Chris Lattnerfa217bd2009-03-08 08:08:45 +0000314 // Replace the terminating quote with a \n.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000315 StrVal[StrVal.size()-1] = '\n';
Mike Stump11289f42009-09-09 15:08:12 +0000316
Peter Collingbournef29ce972011-02-22 13:49:06 +0000317 // Plop the string (including the newline and trailing null) into a buffer
318 // where we can lex it.
319 Token TmpTok;
320 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000321 CreateString(StrVal, TmpTok);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000322 SourceLocation TokLoc = TmpTok.getLocation();
323
324 // Make and enter a lexer object so that we lex and expand the tokens just
325 // like any others.
326 Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
327 StrVal.size(), *this);
328
Craig Topperd2d442c2014-05-17 23:10:59 +0000329 EnterSourceFileWithLexer(TL, nullptr);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000330
331 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000332 HandlePragmaDirective(PragmaLoc, PIK__Pragma);
John McCall89e925d2010-08-28 22:34:47 +0000333
334 // Finally, return whatever came after the pragma directive.
335 return Lex(Tok);
336}
337
338/// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
339/// is not enclosed within a string literal.
340void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
341 // Remember the pragma token location.
342 SourceLocation PragmaLoc = Tok.getLocation();
343
344 // Read the '('.
345 Lex(Tok);
346 if (Tok.isNot(tok::l_paren)) {
347 Diag(PragmaLoc, diag::err__Pragma_malformed);
348 return;
349 }
350
Peter Collingbournef29ce972011-02-22 13:49:06 +0000351 // Get the tokens enclosed within the __pragma(), as well as the final ')'.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000352 SmallVector<Token, 32> PragmaToks;
John McCall89e925d2010-08-28 22:34:47 +0000353 int NumParens = 0;
354 Lex(Tok);
355 while (Tok.isNot(tok::eof)) {
Peter Collingbournef29ce972011-02-22 13:49:06 +0000356 PragmaToks.push_back(Tok);
John McCall89e925d2010-08-28 22:34:47 +0000357 if (Tok.is(tok::l_paren))
358 NumParens++;
359 else if (Tok.is(tok::r_paren) && NumParens-- == 0)
360 break;
John McCall89e925d2010-08-28 22:34:47 +0000361 Lex(Tok);
362 }
363
John McCall49039d42010-08-29 01:09:54 +0000364 if (Tok.is(tok::eof)) {
365 Diag(PragmaLoc, diag::err_unterminated___pragma);
366 return;
367 }
368
Peter Collingbournef29ce972011-02-22 13:49:06 +0000369 PragmaToks.front().setFlag(Token::LeadingSpace);
John McCall89e925d2010-08-28 22:34:47 +0000370
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000371 // Replace the ')' with an EOD to mark the end of the pragma.
372 PragmaToks.back().setKind(tok::eod);
Peter Collingbournef29ce972011-02-22 13:49:06 +0000373
374 Token *TokArray = new Token[PragmaToks.size()];
375 std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
376
377 // Push the tokens onto the stack.
378 EnterTokenStream(TokArray, PragmaToks.size(), true, true);
379
380 // With everything set up, lex this as a #pragma directive.
Enea Zaffanella5afb04a2013-07-20 20:09:11 +0000381 HandlePragmaDirective(PragmaLoc, PIK___pragma);
John McCall89e925d2010-08-28 22:34:47 +0000382
383 // Finally, return whatever came after the pragma directive.
384 return Lex(Tok);
385}
386
James Dennett18a6d792012-06-17 03:26:26 +0000387/// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
Chris Lattner146762e2007-07-20 16:59:19 +0000388void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
Sunil Srivastavafe583272016-07-25 17:17:06 +0000389 // Don't honor the 'once' when handling the primary source file, unless
Erik Verbruggene0bde752016-10-27 14:17:10 +0000390 // this is a prefix to a TU, which indicates we're generating a PCH file, or
391 // when the main file is a header (e.g. when -xc-header is provided on the
392 // commandline).
393 if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000394 Diag(OnceTok, diag::pp_pragma_once_in_main_file);
395 return;
396 }
Mike Stump11289f42009-09-09 15:08:12 +0000397
Chris Lattnerb694ba72006-07-02 22:41:36 +0000398 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000399 // Mark the file as a once-only file now.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000400 HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
Chris Lattnerb694ba72006-07-02 22:41:36 +0000401}
402
Chris Lattnerc2383312007-12-19 19:38:36 +0000403void Preprocessor::HandlePragmaMark() {
Ted Kremenek76c34412008-11-19 22:21:33 +0000404 assert(CurPPLexer && "No current lexer?");
Erich Keane0a6b5b62018-12-04 14:34:09 +0000405 CurLexer->ReadToEndOfLine();
Chris Lattnerc2383312007-12-19 19:38:36 +0000406}
407
James Dennett18a6d792012-06-17 03:26:26 +0000408/// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000409void Preprocessor::HandlePragmaPoison() {
Chris Lattner146762e2007-07-20 16:59:19 +0000410 Token Tok;
Chris Lattner538d7f32006-07-20 04:31:52 +0000411
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000412 while (true) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000413 // Read the next token to poison. While doing this, pretend that we are
414 // skipping while reading the identifier to poison.
415 // This avoids errors on code like:
416 // #pragma GCC poison X
417 // #pragma GCC poison X
Ted Kremenek551c82a2008-11-18 01:12:54 +0000418 if (CurPPLexer) CurPPLexer->LexingRawMode = true;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000419 LexUnexpandedToken(Tok);
Ted Kremenek551c82a2008-11-18 01:12:54 +0000420 if (CurPPLexer) CurPPLexer->LexingRawMode = false;
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattnerb694ba72006-07-02 22:41:36 +0000422 // If we reached the end of line, we're done.
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000423 if (Tok.is(tok::eod)) return;
Mike Stump11289f42009-09-09 15:08:12 +0000424
Chris Lattnerb694ba72006-07-02 22:41:36 +0000425 // Can only poison identifiers.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000426 if (Tok.isNot(tok::raw_identifier)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000427 Diag(Tok, diag::err_pp_invalid_poison);
428 return;
429 }
Mike Stump11289f42009-09-09 15:08:12 +0000430
Chris Lattnercefc7682006-07-08 08:28:12 +0000431 // Look up the identifier info for the token. We disabled identifier lookup
432 // by saying we're skipping contents, so we need to do this manually.
433 IdentifierInfo *II = LookUpIdentifierInfo(Tok);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattnerb694ba72006-07-02 22:41:36 +0000435 // Already poisoned.
436 if (II->isPoisoned()) continue;
Mike Stump11289f42009-09-09 15:08:12 +0000437
Chris Lattnerb694ba72006-07-02 22:41:36 +0000438 // If this is a macro identifier, emit a warning.
Richard Smith20e883e2015-04-29 23:20:19 +0000439 if (isMacroDefined(II))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000440 Diag(Tok, diag::pp_poisoning_existing_macro);
Mike Stump11289f42009-09-09 15:08:12 +0000441
Chris Lattnerb694ba72006-07-02 22:41:36 +0000442 // Finally, poison it!
443 II->setIsPoisoned();
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000444 if (II->isFromAST())
445 II->setChangedSinceDeserialization();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000446 }
447}
448
James Dennett18a6d792012-06-17 03:26:26 +0000449/// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
Chris Lattnerb694ba72006-07-02 22:41:36 +0000450/// that the whole directive has been parsed.
Chris Lattner146762e2007-07-20 16:59:19 +0000451void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000452 if (isInPrimaryFile()) {
453 Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
454 return;
455 }
Mike Stump11289f42009-09-09 15:08:12 +0000456
Chris Lattnerb694ba72006-07-02 22:41:36 +0000457 // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
Ted Kremenek300590b2008-11-20 01:45:11 +0000458 PreprocessorLexer *TheLexer = getCurrentFileLexer();
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattnerb694ba72006-07-02 22:41:36 +0000460 // Mark the file as a system header.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000461 HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
Mike Stump11289f42009-09-09 15:08:12 +0000462
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000463 PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
Douglas Gregor453b0122010-11-12 07:15:47 +0000464 if (PLoc.isInvalid())
465 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000466
Jay Foad9a6b0982011-06-21 15:13:30 +0000467 unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
Mike Stump11289f42009-09-09 15:08:12 +0000468
Chris Lattner3bdc7672011-05-22 22:10:16 +0000469 // Notify the client, if desired, that we are in a new source file.
470 if (Callbacks)
471 Callbacks->FileChanged(SysHeaderTok.getLocation(),
472 PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
473
Chris Lattnerd9efb6e2009-06-15 05:02:34 +0000474 // Emit a line marker. This will change any source locations from this point
475 // forward to realize they are in a system header.
476 // Create a line note with this information.
Reid Klecknereb00ee02017-05-22 21:42:58 +0000477 SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
Jordan Rose111c4a62013-04-17 19:09:18 +0000478 FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
Reid Klecknereb00ee02017-05-22 21:42:58 +0000479 SrcMgr::C_System);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000480}
481
James Dennett18a6d792012-06-17 03:26:26 +0000482/// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
Chris Lattner146762e2007-07-20 16:59:19 +0000483void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
484 Token FilenameTok;
Ted Kremenek551c82a2008-11-18 01:12:54 +0000485 CurPPLexer->LexIncludeFilename(FilenameTok);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000486
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000487 // If the token kind is EOD, the error has already been diagnosed.
488 if (FilenameTok.is(tok::eod))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000489 return;
Mike Stump11289f42009-09-09 15:08:12 +0000490
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000491 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000492 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000493 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000494 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000495 if (Invalid)
496 return;
Mike Stump11289f42009-09-09 15:08:12 +0000497
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000498 bool isAngled =
499 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000500 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
501 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000502 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000503 return;
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000505 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000506 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000507 const FileEntry *File =
508 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000509 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000510 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000511 if (!SuppressIncludeNotFoundError)
512 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000513 return;
514 }
Mike Stump11289f42009-09-09 15:08:12 +0000515
Chris Lattnerd32480d2009-01-17 06:22:33 +0000516 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000517
518 // If this file is older than the file it depends on, emit a diagnostic.
519 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
520 // Lex tokens at the end of the message and include them in the message.
521 std::string Message;
522 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000523 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000524 Message += getSpelling(DependencyTok) + " ";
525 Lex(DependencyTok);
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattnerf0b04972010-09-05 23:16:09 +0000528 // Remove the trailing ' ' if present.
529 if (!Message.empty())
530 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000531 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000532 }
533}
534
Reid Kleckner002562a2013-05-06 21:02:12 +0000535/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000536/// Return the IdentifierInfo* associated with the macro to push or pop.
537IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
538 // Remember the pragma token location.
539 Token PragmaTok = Tok;
540
541 // Read the '('.
542 Lex(Tok);
543 if (Tok.isNot(tok::l_paren)) {
544 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
545 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000546 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000547 }
548
549 // Read the macro name string.
550 Lex(Tok);
551 if (Tok.isNot(tok::string_literal)) {
552 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
553 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000554 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000555 }
556
Richard Smithd67aea22012-03-06 03:21:47 +0000557 if (Tok.hasUDSuffix()) {
558 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000559 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000560 }
561
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000562 // Remember the macro string.
563 std::string StrVal = getSpelling(Tok);
564
565 // Read the ')'.
566 Lex(Tok);
567 if (Tok.isNot(tok::r_paren)) {
568 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
569 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000570 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000571 }
572
573 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
574 "Invalid string token!");
575
576 // Create a Token from the string.
577 Token MacroTok;
578 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000579 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000580 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000581
582 // Get the IdentifierInfo of MacroToPushTok.
583 return LookUpIdentifierInfo(MacroTok);
584}
585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000586/// Handle \#pragma push_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000587///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000588/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000589/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000590/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000591/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000592void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
593 // Parse the pragma directive and get the macro IdentifierInfo*.
594 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
595 if (!IdentInfo) return;
596
597 // Get the MacroInfo associated with IdentInfo.
598 MacroInfo *MI = getMacroInfo(IdentInfo);
Fangrui Song6907ce22018-07-30 19:24:48 +0000599
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000600 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000601 // Allow the original MacroInfo to be redefined later.
602 MI->setIsAllowRedefinitionsWithoutWarning(true);
603 }
604
605 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000606 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000607}
608
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000609/// Handle \#pragma pop_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000610///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000611/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000612/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000613/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000614/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000615void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
616 SourceLocation MessageLoc = PopMacroTok.getLocation();
617
618 // Parse the pragma directive and get the macro IdentifierInfo*.
619 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
620 if (!IdentInfo) return;
621
622 // Find the vector<MacroInfo*> associated with the macro.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000623 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000624 PragmaPushMacroInfo.find(IdentInfo);
625 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000626 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000627 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000628 if (MI->isWarnIfUnused())
629 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
630 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000631 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000632
633 // Get the MacroInfo we want to reinstall.
634 MacroInfo *MacroToReInstall = iter->second.back();
635
Richard Smith713369b2015-04-23 20:40:50 +0000636 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000637 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000638 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000639
640 // Pop PragmaPushMacroInfo stack.
641 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000642 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000643 PragmaPushMacroInfo.erase(iter);
644 } else {
645 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
646 << IdentInfo->getName();
647 }
648}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000649
Aaron Ballman611306e2012-03-02 22:51:54 +0000650void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000651 // We will either get a quoted filename or a bracketed filename, and we
Aaron Ballman611306e2012-03-02 22:51:54 +0000652 // have to track which we got. The first filename is the source name,
653 // and the second name is the mapped filename. If the first is quoted,
654 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000655
656 // Get the open paren
657 Lex(Tok);
658 if (Tok.isNot(tok::l_paren)) {
659 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
660 return;
661 }
662
663 // We expect either a quoted string literal, or a bracketed name
664 Token SourceFilenameTok;
665 CurPPLexer->LexIncludeFilename(SourceFilenameTok);
666 if (SourceFilenameTok.is(tok::eod)) {
667 // The diagnostic has already been handled
668 return;
669 }
670
671 StringRef SourceFileName;
672 SmallString<128> FileNameBuffer;
Fangrui Song6907ce22018-07-30 19:24:48 +0000673 if (SourceFilenameTok.is(tok::string_literal) ||
Aaron Ballman611306e2012-03-02 22:51:54 +0000674 SourceFilenameTok.is(tok::angle_string_literal)) {
675 SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
676 } else if (SourceFilenameTok.is(tok::less)) {
677 // This could be a path instead of just a name
678 FileNameBuffer.push_back('<');
679 SourceLocation End;
680 if (ConcatenateIncludeName(FileNameBuffer, End))
681 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000682 SourceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000683 } else {
684 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
685 return;
686 }
687 FileNameBuffer.clear();
688
689 // Now we expect a comma, followed by another include name
690 Lex(Tok);
691 if (Tok.isNot(tok::comma)) {
692 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
693 return;
694 }
695
696 Token ReplaceFilenameTok;
697 CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
698 if (ReplaceFilenameTok.is(tok::eod)) {
699 // The diagnostic has already been handled
700 return;
701 }
702
703 StringRef ReplaceFileName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000704 if (ReplaceFilenameTok.is(tok::string_literal) ||
Aaron Ballman611306e2012-03-02 22:51:54 +0000705 ReplaceFilenameTok.is(tok::angle_string_literal)) {
706 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
707 } else if (ReplaceFilenameTok.is(tok::less)) {
708 // This could be a path instead of just a name
709 FileNameBuffer.push_back('<');
710 SourceLocation End;
711 if (ConcatenateIncludeName(FileNameBuffer, End))
712 return; // Diagnostic already emitted
Yaron Keren92e1b622015-03-18 10:17:07 +0000713 ReplaceFileName = FileNameBuffer;
Aaron Ballman611306e2012-03-02 22:51:54 +0000714 } else {
715 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
716 return;
717 }
718
719 // Finally, we expect the closing paren
720 Lex(Tok);
721 if (Tok.isNot(tok::r_paren)) {
722 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
723 return;
724 }
725
726 // Now that we have the source and target filenames, we need to make sure
727 // they're both of the same type (angled vs non-angled)
728 StringRef OriginalSource = SourceFileName;
729
Fangrui Song6907ce22018-07-30 19:24:48 +0000730 bool SourceIsAngled =
731 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
Aaron Ballman611306e2012-03-02 22:51:54 +0000732 SourceFileName);
733 bool ReplaceIsAngled =
734 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
735 ReplaceFileName);
736 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
737 (SourceIsAngled != ReplaceIsAngled)) {
738 unsigned int DiagID;
739 if (SourceIsAngled)
740 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
741 else
742 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
743
744 Diag(SourceFilenameTok.getLocation(), DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +0000745 << SourceFileName
Aaron Ballman611306e2012-03-02 22:51:54 +0000746 << ReplaceFileName;
747
748 return;
749 }
750
751 // Now we can let the include handler know about this mapping
752 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
753}
754
Richard Smith9565c75b2017-06-19 23:09:36 +0000755// Lex a component of a module name: either an identifier or a string literal;
756// for components that can be expressed both ways, the two forms are equivalent.
757static bool LexModuleNameComponent(
758 Preprocessor &PP, Token &Tok,
759 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
760 bool First) {
761 PP.LexUnexpandedToken(Tok);
762 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
763 StringLiteralParser Literal(Tok, PP);
764 if (Literal.hadError)
765 return true;
766 ModuleNameComponent = std::make_pair(
767 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
768 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
769 ModuleNameComponent =
770 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
771 } else {
772 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
773 return true;
774 }
775 return false;
776}
777
778static bool LexModuleName(
779 Preprocessor &PP, Token &Tok,
780 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
781 &ModuleName) {
782 while (true) {
783 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
784 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
785 return true;
786 ModuleName.push_back(NameComponent);
787
788 PP.LexUnexpandedToken(Tok);
789 if (Tok.isNot(tok::period))
790 return false;
791 }
792}
793
Richard Smith5d2ed482017-06-09 19:22:32 +0000794void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
795 SourceLocation Loc = Tok.getLocation();
796
Richard Smith9565c75b2017-06-19 23:09:36 +0000797 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
798 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000799 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000800 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000801
802 LexUnexpandedToken(Tok);
803 if (Tok.isNot(tok::eod)) {
804 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
805 DiscardUntilEndOfDirective();
806 }
807
Richard Smith5d2ed482017-06-09 19:22:32 +0000808 CurLexer->LexingRawMode = true;
809
810 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
811 if (Tok.getKind() != tok::raw_identifier ||
812 Tok.getRawIdentifier() != Ident)
813 return false;
814 CurLexer->Lex(Tok);
815 return true;
816 };
817
818 // Scan forward looking for the end of the module.
819 const char *Start = CurLexer->getBufferLocation();
820 const char *End = nullptr;
821 unsigned NestingLevel = 1;
822 while (true) {
823 End = CurLexer->getBufferLocation();
824 CurLexer->Lex(Tok);
825
826 if (Tok.is(tok::eof)) {
827 Diag(Loc, diag::err_pp_module_build_missing_end);
828 break;
829 }
830
831 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
832 // Token was part of module; keep going.
833 continue;
834 }
835
836 // We hit something directive-shaped; check to see if this is the end
837 // of the module build.
838 CurLexer->ParsingPreprocessorDirective = true;
839 CurLexer->Lex(Tok);
840 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
841 TryConsumeIdentifier("module")) {
842 if (TryConsumeIdentifier("build"))
843 // #pragma clang module build -> entering a nested module build.
844 ++NestingLevel;
845 else if (TryConsumeIdentifier("endbuild")) {
846 // #pragma clang module endbuild -> leaving a module build.
847 if (--NestingLevel == 0)
848 break;
849 }
850 // We should either be looking at the EOD or more of the current directive
851 // preceding the EOD. Either way we can ignore this token and keep going.
852 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
853 }
854 }
855
856 CurLexer->LexingRawMode = false;
857
858 // Load the extracted text as a preprocessed module.
859 assert(CurLexer->getBuffer().begin() <= Start &&
860 Start <= CurLexer->getBuffer().end() &&
861 CurLexer->getBuffer().begin() <= End &&
862 End <= CurLexer->getBuffer().end() &&
863 "module source range not contained within same file buffer");
864 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
865 StringRef(Start, End - Start));
866}
867
Mike Rice58df1af2018-09-11 17:10:44 +0000868void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
869 Lex(Tok);
870 if (Tok.is(tok::l_paren)) {
871 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
872
873 std::string FileName;
874 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
875 return;
876
877 if (Tok.isNot(tok::r_paren)) {
878 Diag(Tok, diag::err_expected) << tok::r_paren;
879 return;
880 }
881 Lex(Tok);
882 }
883 if (Tok.isNot(tok::eod))
884 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
885 << "pragma hdrstop";
886
887 if (creatingPCHWithPragmaHdrStop() &&
888 SourceMgr.isInMainFile(Tok.getLocation())) {
889 assert(CurLexer && "no lexer for #pragma hdrstop processing");
890 Token &Result = Tok;
891 Result.startToken();
892 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
893 CurLexer->cutOffLexing();
894 }
895 if (usingPCHWithPragmaHdrStop())
896 SkippingUntilPragmaHdrStop = false;
897}
898
Chris Lattnerb694ba72006-07-02 22:41:36 +0000899/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
900/// If 'Namespace' is non-null, then it is a token required to exist on the
901/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000902void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000903 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000904 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattnerb694ba72006-07-02 22:41:36 +0000906 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000907 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000908 // If there is already a pragma handler with the name of this namespace,
909 // we either have an error (directive with the same name as a namespace) or
910 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000911 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000912 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000913 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000914 " handler with the same name!");
915 } else {
916 // Otherwise, this namespace doesn't exist yet, create and insert the
917 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000918 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000919 PragmaHandlers->AddPragma(InsertNS);
920 }
921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Chris Lattnerb694ba72006-07-02 22:41:36 +0000923 // Check to make sure we don't already have a pragma for this identifier.
924 assert(!InsertNS->FindHandler(Handler->getName()) &&
925 "Pragma handler already exists for this identifier!");
926 InsertNS->AddPragma(Handler);
927}
928
Daniel Dunbar40596532008-10-04 19:17:46 +0000929/// RemovePragmaHandler - Remove the specific pragma handler from the
930/// preprocessor. If \arg Namespace is non-null, then it should be the
931/// namespace that \arg Handler was added to. It is an error to remove
932/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000933void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000934 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000935 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000936
Daniel Dunbar40596532008-10-04 19:17:46 +0000937 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000938 if (!Namespace.empty()) {
939 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000940 assert(Existing && "Namespace containing handler does not exist!");
941
942 NS = Existing->getIfNamespace();
943 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
944 }
945
946 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000947
Craig Topperbe250302014-09-12 05:19:24 +0000948 // If this is a non-default namespace and it is now empty, remove it.
949 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000950 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000951 delete NS;
952 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000953}
954
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000955bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
956 Token Tok;
957 LexUnexpandedToken(Tok);
958
959 if (Tok.isNot(tok::identifier)) {
960 Diag(Tok, diag::ext_on_off_switch_syntax);
961 return true;
962 }
963 IdentifierInfo *II = Tok.getIdentifierInfo();
964 if (II->isStr("ON"))
965 Result = tok::OOS_ON;
966 else if (II->isStr("OFF"))
967 Result = tok::OOS_OFF;
968 else if (II->isStr("DEFAULT"))
969 Result = tok::OOS_DEFAULT;
970 else {
971 Diag(Tok, diag::ext_on_off_switch_syntax);
972 return true;
973 }
974
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000975 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000976 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000977 if (Tok.isNot(tok::eod))
978 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000979 return false;
980}
981
Chris Lattnerb694ba72006-07-02 22:41:36 +0000982namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000983
James Dennett18a6d792012-06-17 03:26:26 +0000984/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000985struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000986 PragmaOnceHandler() : PragmaHandler("once") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000987
Craig Topper9140dd22014-03-11 06:50:42 +0000988 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
989 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000990 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000991 PP.HandlePragmaOnce(OnceTok);
992 }
993};
994
James Dennett18a6d792012-06-17 03:26:26 +0000995/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000996/// rest of the line is not lexed.
997struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000998 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000999
Craig Topper9140dd22014-03-11 06:50:42 +00001000 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1001 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +00001002 PP.HandlePragmaMark();
1003 }
1004};
1005
James Dennett18a6d792012-06-17 03:26:26 +00001006/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001007struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001008 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001009
Craig Topper9140dd22014-03-11 06:50:42 +00001010 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1011 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +00001012 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +00001013 }
1014};
1015
James Dennett18a6d792012-06-17 03:26:26 +00001016/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +00001017/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001018struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001019 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001020
Craig Topper9140dd22014-03-11 06:50:42 +00001021 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1022 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001023 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001024 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +00001025 }
1026};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001027
Chris Lattnerb694ba72006-07-02 22:41:36 +00001028struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001029 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001030
Craig Topper9140dd22014-03-11 06:50:42 +00001031 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1032 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001033 PP.HandlePragmaDependency(DepToken);
1034 }
1035};
Mike Stump11289f42009-09-09 15:08:12 +00001036
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001037struct PragmaDebugHandler : public PragmaHandler {
1038 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001039
Craig Topper9140dd22014-03-11 06:50:42 +00001040 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1041 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001042 Token Tok;
1043 PP.LexUnexpandedToken(Tok);
1044 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001045 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001046 return;
1047 }
1048 IdentifierInfo *II = Tok.getIdentifierInfo();
1049
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001050 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001051 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001052 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001053 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001054 } else if (II->isStr("parser_crash")) {
1055 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001056 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001057 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001058 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +00001059 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +00001060 } else if (II->isStr("dump")) {
1061 Token Identifier;
1062 PP.LexUnexpandedToken(Identifier);
1063 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1064 Token DumpAnnot;
1065 DumpAnnot.startToken();
1066 DumpAnnot.setKind(tok::annot_pragma_dump);
1067 DumpAnnot.setAnnotationRange(
1068 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1069 DumpAnnot.setAnnotationValue(DumpII);
1070 PP.DiscardUntilEndOfDirective();
1071 PP.EnterToken(DumpAnnot);
1072 } else {
1073 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1074 << II->getName();
1075 }
Richard Smith6c2b5a82018-02-09 01:15:13 +00001076 } else if (II->isStr("diag_mapping")) {
1077 Token DiagName;
1078 PP.LexUnexpandedToken(DiagName);
1079 if (DiagName.is(tok::eod))
1080 PP.getDiagnostics().dump();
1081 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1082 StringLiteralParser Literal(DiagName, PP);
1083 if (Literal.hadError)
1084 return;
1085 PP.getDiagnostics().dump(Literal.GetString());
1086 } else {
1087 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1088 << II->getName();
1089 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001090 } else if (II->isStr("llvm_fatal_error")) {
1091 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1092 } else if (II->isStr("llvm_unreachable")) {
1093 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001094 } else if (II->isStr("macro")) {
1095 Token MacroName;
1096 PP.LexUnexpandedToken(MacroName);
1097 auto *MacroII = MacroName.getIdentifierInfo();
1098 if (MacroII)
1099 PP.dumpMacroInfo(MacroII);
1100 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001101 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1102 << II->getName();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001103 } else if (II->isStr("overflow_stack")) {
1104 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001105 } else if (II->isStr("handle_crash")) {
1106 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1107 if (CRC)
1108 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001109 } else if (II->isStr("captured")) {
1110 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001111 } else {
1112 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1113 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001114 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001115
1116 PPCallbacks *Callbacks = PP.getPPCallbacks();
1117 if (Callbacks)
1118 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1119 }
1120
1121 void HandleCaptured(Preprocessor &PP) {
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001122 Token Tok;
1123 PP.LexUnexpandedToken(Tok);
1124
1125 if (Tok.isNot(tok::eod)) {
1126 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1127 << "pragma clang __debug captured";
1128 return;
1129 }
1130
1131 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001132 MutableArrayRef<Token> Toks(
1133 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1134 Toks[0].startToken();
1135 Toks[0].setKind(tok::annot_pragma_captured);
1136 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001137
David Blaikie2eabcc92016-02-09 18:52:09 +00001138 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001139 }
1140
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001141// Disable MSVC warning about runtime stack overflow.
1142#ifdef _MSC_VER
1143 #pragma warning(disable : 4717)
1144#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001145 static void DebugOverflowStack(void (*P)() = nullptr) {
1146 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1147 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001148 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001149#ifdef _MSC_VER
1150 #pragma warning(default : 4717)
1151#endif
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001152};
1153
James Dennett18a6d792012-06-17 03:26:26 +00001154/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001155struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001156private:
1157 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001158
Chris Lattnerfb42a182009-07-12 21:18:45 +00001159public:
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001160 explicit PragmaDiagnosticHandler(const char *NS)
1161 : PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001162
Craig Topper9140dd22014-03-11 06:50:42 +00001163 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1164 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001165 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001166 Token Tok;
1167 PP.LexUnexpandedToken(Tok);
1168 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001169 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001170 return;
1171 }
1172 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001173 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001174
Alp Toker46df1c02014-06-12 10:15:20 +00001175 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001176 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001177 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001178 else if (Callbacks)
1179 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001180 return;
1181 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001182 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001183 if (Callbacks)
1184 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001185 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001186 }
1187
1188 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1189 .Case("ignored", diag::Severity::Ignored)
1190 .Case("warning", diag::Severity::Warning)
1191 .Case("error", diag::Severity::Error)
1192 .Case("fatal", diag::Severity::Fatal)
1193 .Default(diag::Severity());
1194
1195 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001196 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001197 return;
1198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
Chris Lattner504af112009-04-19 23:16:58 +00001200 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001201 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001202
Andy Gibbs58905d22012-11-17 19:15:38 +00001203 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001204 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1205 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001206 return;
Mike Stump11289f42009-09-09 15:08:12 +00001207
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001208 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001209 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1210 return;
1211 }
Mike Stump11289f42009-09-09 15:08:12 +00001212
Chris Lattner504af112009-04-19 23:16:58 +00001213 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001214 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001215 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001216 return;
1217 }
Mike Stump11289f42009-09-09 15:08:12 +00001218
Sunil Srivastava5239de72016-02-13 01:44:05 +00001219 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1220 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001221 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001222 bool unknownDiag = false;
1223 if (Group == "everything") {
1224 // Special handling for pragma clang diagnostic ... "-Weverything".
1225 // There is no formal group named "everything", so there has to be a
1226 // special case for it.
1227 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1228 } else
1229 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1230 DiagLoc);
1231 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001232 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1233 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001234 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001235 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001236 }
1237};
Mike Stump11289f42009-09-09 15:08:12 +00001238
Mike Rice58df1af2018-09-11 17:10:44 +00001239/// "\#pragma hdrstop [<header-name-string>]"
1240struct PragmaHdrstopHandler : public PragmaHandler {
1241 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1242 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1243 Token &DepToken) override {
1244 PP.HandlePragmaHdrstop(DepToken);
1245 }
1246};
1247
Reid Kleckner881dff32013-09-13 22:00:30 +00001248/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1249/// diagnostics, so we don't really implement this pragma. We parse it and
1250/// ignore it to avoid -Wunknown-pragma warnings.
1251struct PragmaWarningHandler : public PragmaHandler {
1252 PragmaWarningHandler() : PragmaHandler("warning") {}
1253
Craig Topper9140dd22014-03-11 06:50:42 +00001254 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1255 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001256 // Parse things like:
1257 // warning(push, 1)
1258 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001259 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001260 SourceLocation DiagLoc = Tok.getLocation();
1261 PPCallbacks *Callbacks = PP.getPPCallbacks();
1262
1263 PP.Lex(Tok);
1264 if (Tok.isNot(tok::l_paren)) {
1265 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1266 return;
1267 }
1268
1269 PP.Lex(Tok);
1270 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001271
Alexander Musman6b080fc2015-05-25 11:21:20 +00001272 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001273 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001274 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001275 PP.Lex(Tok);
1276 if (Tok.is(tok::comma)) {
1277 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001278 uint64_t Value;
1279 if (Tok.is(tok::numeric_constant) &&
1280 PP.parseSimpleIntegerLiteral(Tok, Value))
1281 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001282 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001283 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1284 return;
1285 }
1286 }
1287 if (Callbacks)
1288 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001289 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001290 // #pragma warning( pop )
1291 PP.Lex(Tok);
1292 if (Callbacks)
1293 Callbacks->PragmaWarningPop(DiagLoc);
1294 } else {
1295 // #pragma warning( warning-specifier : warning-number-list
1296 // [; warning-specifier : warning-number-list...] )
1297 while (true) {
1298 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001299 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001300 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1301 return;
1302 }
1303
1304 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001305 bool SpecifierValid;
1306 StringRef Specifier;
1307 llvm::SmallString<1> SpecifierBuf;
1308 if (II) {
1309 Specifier = II->getName();
1310 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1311 .Cases("default", "disable", "error", "once",
1312 "suppress", true)
1313 .Default(false);
1314 // If we read a correct specifier, snatch next token (that should be
1315 // ":", checked later).
1316 if (SpecifierValid)
1317 PP.Lex(Tok);
1318 } else {
1319 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1320 uint64_t Value;
1321 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1322 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1323 SpecifierValid = (Value >= 1) && (Value <= 4);
1324 } else
1325 SpecifierValid = false;
1326 // Next token already snatched by parseSimpleIntegerLiteral.
1327 }
1328
Reid Kleckner881dff32013-09-13 22:00:30 +00001329 if (!SpecifierValid) {
1330 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1331 return;
1332 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001333 if (Tok.isNot(tok::colon)) {
1334 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1335 return;
1336 }
1337
1338 // Collect the warning ids.
1339 SmallVector<int, 4> Ids;
1340 PP.Lex(Tok);
1341 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001342 uint64_t Value;
1343 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001344 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001345 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1346 return;
1347 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001348 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001349 }
1350 if (Callbacks)
1351 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1352
1353 // Parse the next specifier if there is a semicolon.
1354 if (Tok.isNot(tok::semi))
1355 break;
1356 PP.Lex(Tok);
1357 }
1358 }
1359
1360 if (Tok.isNot(tok::r_paren)) {
1361 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1362 return;
1363 }
1364
1365 PP.Lex(Tok);
1366 if (Tok.isNot(tok::eod))
1367 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1368 }
1369};
1370
Reid Kleckner0f56b222019-03-14 18:12:17 +00001371/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1372/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1373/// otherwise to avoid -Wunknown-pragma warnings.
1374struct PragmaExecCharsetHandler : public PragmaHandler {
1375 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1376
1377 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1378 Token &Tok) override {
1379 // Parse things like:
1380 // execution_character_set(push, "UTF-8")
1381 // execution_character_set(pop)
1382 SourceLocation DiagLoc = Tok.getLocation();
1383 PPCallbacks *Callbacks = PP.getPPCallbacks();
1384
1385 PP.Lex(Tok);
1386 if (Tok.isNot(tok::l_paren)) {
1387 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1388 return;
1389 }
1390
1391 PP.Lex(Tok);
1392 IdentifierInfo *II = Tok.getIdentifierInfo();
1393
1394 if (II && II->isStr("push")) {
1395 // #pragma execution_character_set( push[ , string ] )
1396 PP.Lex(Tok);
1397 if (Tok.is(tok::comma)) {
1398 PP.Lex(Tok);
1399
1400 std::string ExecCharset;
1401 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1402 "pragma execution_character_set",
1403 /*MacroExpansion=*/false))
1404 return;
1405
1406 // MSVC supports either of these, but nothing else.
1407 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1408 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1409 return;
1410 }
1411 }
1412 if (Callbacks)
1413 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1414 } else if (II && II->isStr("pop")) {
1415 // #pragma execution_character_set( pop )
1416 PP.Lex(Tok);
1417 if (Callbacks)
1418 Callbacks->PragmaExecCharsetPop(DiagLoc);
1419 } else {
1420 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1421 return;
1422 }
1423
1424 if (Tok.isNot(tok::r_paren)) {
1425 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1426 return;
1427 }
1428
1429 PP.Lex(Tok);
1430 if (Tok.isNot(tok::eod))
1431 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1432 }
1433};
1434
James Dennett18a6d792012-06-17 03:26:26 +00001435/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001436struct PragmaIncludeAliasHandler : public PragmaHandler {
1437 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001438
Craig Topper9140dd22014-03-11 06:50:42 +00001439 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1440 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001441 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001442 }
1443};
1444
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001445/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1446/// extension. The syntax is:
1447/// \code
1448/// #pragma message(string)
1449/// \endcode
1450/// OR, in GCC mode:
1451/// \code
1452/// #pragma message string
1453/// \endcode
1454/// string is a string, which is fully macro expanded, and permits string
1455/// concatenation, embedded escape characters, etc... See MSDN for more details.
1456/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1457/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001458struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001459private:
1460 const PPCallbacks::PragmaMessageKind Kind;
1461 const StringRef Namespace;
1462
1463 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1464 bool PragmaNameOnly = false) {
1465 switch (Kind) {
1466 case PPCallbacks::PMK_Message:
1467 return PragmaNameOnly ? "message" : "pragma message";
1468 case PPCallbacks::PMK_Warning:
1469 return PragmaNameOnly ? "warning" : "pragma warning";
1470 case PPCallbacks::PMK_Error:
1471 return PragmaNameOnly ? "error" : "pragma error";
1472 }
1473 llvm_unreachable("Unknown PragmaMessageKind!");
1474 }
1475
1476public:
1477 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1478 StringRef Namespace = StringRef())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001479 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1480 Namespace(Namespace) {}
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001481
Craig Topper9140dd22014-03-11 06:50:42 +00001482 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1483 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001484 SourceLocation MessageLoc = Tok.getLocation();
1485 PP.Lex(Tok);
1486 bool ExpectClosingParen = false;
1487 switch (Tok.getKind()) {
1488 case tok::l_paren:
1489 // We have a MSVC style pragma message.
1490 ExpectClosingParen = true;
1491 // Read the string.
1492 PP.Lex(Tok);
1493 break;
1494 case tok::string_literal:
1495 // We have a GCC style pragma message, and we just read the string.
1496 break;
1497 default:
1498 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1499 return;
1500 }
1501
1502 std::string MessageString;
1503 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1504 /*MacroExpansion=*/true))
1505 return;
1506
1507 if (ExpectClosingParen) {
1508 if (Tok.isNot(tok::r_paren)) {
1509 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1510 return;
1511 }
1512 PP.Lex(Tok); // eat the r_paren.
1513 }
1514
1515 if (Tok.isNot(tok::eod)) {
1516 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1517 return;
1518 }
1519
1520 // Output the message.
1521 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1522 ? diag::err_pragma_message
1523 : diag::warn_pragma_message) << MessageString;
1524
1525 // If the pragma is lexically sound, notify any interested PPCallbacks.
1526 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1527 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001528 }
1529};
1530
Richard Smithc51c38b2017-04-29 00:34:47 +00001531/// Handle the clang \#pragma module import extension. The syntax is:
1532/// \code
1533/// #pragma clang module import some.module.name
1534/// \endcode
1535struct PragmaModuleImportHandler : public PragmaHandler {
1536 PragmaModuleImportHandler() : PragmaHandler("import") {}
1537
1538 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001539 Token &Tok) override {
1540 SourceLocation ImportLoc = Tok.getLocation();
1541
1542 // Read the module name.
1543 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1544 ModuleName;
1545 if (LexModuleName(PP, Tok, ModuleName))
1546 return;
1547
1548 if (Tok.isNot(tok::eod))
1549 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1550
1551 // If we have a non-empty module path, load the named module.
1552 Module *Imported =
1553 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1554 /*IsIncludeDirective=*/false);
1555 if (!Imported)
1556 return;
1557
1558 PP.makeModuleVisible(Imported, ImportLoc);
1559 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1560 tok::annot_module_include, Imported);
1561 if (auto *CB = PP.getPPCallbacks())
1562 CB->moduleImport(ImportLoc, ModuleName, Imported);
1563 }
1564};
1565
1566/// Handle the clang \#pragma module begin extension. The syntax is:
1567/// \code
1568/// #pragma clang module begin some.module.name
1569/// ...
1570/// #pragma clang module end
1571/// \endcode
1572struct PragmaModuleBeginHandler : public PragmaHandler {
1573 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1574
1575 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1576 Token &Tok) override {
1577 SourceLocation BeginLoc = Tok.getLocation();
1578
1579 // Read the module name.
1580 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1581 ModuleName;
1582 if (LexModuleName(PP, Tok, ModuleName))
1583 return;
1584
1585 if (Tok.isNot(tok::eod))
1586 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1587
1588 // We can only enter submodules of the current module.
1589 StringRef Current = PP.getLangOpts().CurrentModule;
1590 if (ModuleName.front().first->getName() != Current) {
1591 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1592 << ModuleName.front().first << (ModuleName.size() > 1)
1593 << Current.empty() << Current;
1594 return;
1595 }
1596
1597 // Find the module we're entering. We require that a module map for it
1598 // be loaded or implicitly loadable.
1599 // FIXME: We could create the submodule here. We'd need to know whether
1600 // it's supposed to be explicit, but not much else.
Richard Smith9565c75b2017-06-19 23:09:36 +00001601 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001602 if (!M) {
1603 PP.Diag(ModuleName.front().second,
1604 diag::err_pp_module_begin_no_module_map) << Current;
1605 return;
1606 }
1607 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1608 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1609 if (!NewM) {
1610 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1611 << M->getFullModuleName() << ModuleName[I].first;
1612 return;
1613 }
1614 M = NewM;
1615 }
1616
Richard Smith51d09c52017-05-30 05:22:59 +00001617 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001618 if (Preprocessor::checkModuleIsAvailable(
1619 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001620 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1621 << M->getTopLevelModuleName();
1622 return;
1623 }
1624
Richard Smithd1386302017-05-04 00:29:54 +00001625 // Enter the scope of the submodule.
1626 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1627 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1628 tok::annot_module_begin, M);
1629 }
1630};
1631
1632/// Handle the clang \#pragma module end extension.
1633struct PragmaModuleEndHandler : public PragmaHandler {
1634 PragmaModuleEndHandler() : PragmaHandler("end") {}
1635
1636 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1637 Token &Tok) override {
1638 SourceLocation Loc = Tok.getLocation();
1639
1640 PP.LexUnexpandedToken(Tok);
1641 if (Tok.isNot(tok::eod))
1642 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1643
1644 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1645 if (M)
1646 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1647 else
1648 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001649 }
1650};
1651
Richard Smith5d2ed482017-06-09 19:22:32 +00001652/// Handle the clang \#pragma module build extension.
1653struct PragmaModuleBuildHandler : public PragmaHandler {
1654 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1655
1656 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1657 Token &Tok) override {
1658 PP.HandlePragmaModuleBuild(Tok);
1659 }
1660};
1661
1662/// Handle the clang \#pragma module load extension.
1663struct PragmaModuleLoadHandler : public PragmaHandler {
1664 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1665
1666 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1667 Token &Tok) override {
1668 SourceLocation Loc = Tok.getLocation();
1669
1670 // Read the module name.
1671 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1672 ModuleName;
1673 if (LexModuleName(PP, Tok, ModuleName))
1674 return;
1675
1676 if (Tok.isNot(tok::eod))
1677 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1678
1679 // Load the module, don't make it visible.
1680 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1681 /*IsIncludeDirective=*/false);
1682 }
1683};
1684
James Dennett18a6d792012-06-17 03:26:26 +00001685/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001686/// macro on the top of the stack.
1687struct PragmaPushMacroHandler : public PragmaHandler {
1688 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001689
Craig Topper9140dd22014-03-11 06:50:42 +00001690 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1691 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001692 PP.HandlePragmaPushMacro(PushMacroTok);
1693 }
1694};
1695
James Dennett18a6d792012-06-17 03:26:26 +00001696/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001697/// macro to the value on the top of the stack.
1698struct PragmaPopMacroHandler : public PragmaHandler {
1699 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001700
Craig Topper9140dd22014-03-11 06:50:42 +00001701 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1702 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001703 PP.HandlePragmaPopMacro(PopMacroTok);
1704 }
1705};
1706
Fangrui Song6907ce22018-07-30 19:24:48 +00001707/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001708/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001709struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1710 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001711
Craig Topper9140dd22014-03-11 06:50:42 +00001712 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1713 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001714 SourceLocation Loc = NameTok.getLocation();
1715 bool IsBegin;
1716
1717 Token Tok;
1718
1719 // Lex the 'begin' or 'end'.
1720 PP.LexUnexpandedToken(Tok);
1721 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1722 if (BeginEnd && BeginEnd->isStr("begin")) {
1723 IsBegin = true;
1724 } else if (BeginEnd && BeginEnd->isStr("end")) {
1725 IsBegin = false;
1726 } else {
1727 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1728 return;
1729 }
1730
1731 // Verify that this is followed by EOD.
1732 PP.LexUnexpandedToken(Tok);
1733 if (Tok.isNot(tok::eod))
1734 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1735
1736 // The start location of the active audit.
1737 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1738
1739 // The start location we want after processing this.
1740 SourceLocation NewLoc;
1741
1742 if (IsBegin) {
1743 // Complain about attempts to re-enter an audit.
1744 if (BeginLoc.isValid()) {
1745 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1746 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1747 }
1748 NewLoc = Loc;
1749 } else {
1750 // Complain about attempts to leave an audit that doesn't exist.
1751 if (!BeginLoc.isValid()) {
1752 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1753 return;
1754 }
1755 NewLoc = SourceLocation();
1756 }
1757
1758 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1759 }
1760};
1761
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001762/// PragmaAssumeNonNullHandler -
1763/// \#pragma clang assume_nonnull begin/end
1764struct PragmaAssumeNonNullHandler : public PragmaHandler {
1765 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001766
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001767 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1768 Token &NameTok) override {
1769 SourceLocation Loc = NameTok.getLocation();
1770 bool IsBegin;
1771
1772 Token Tok;
1773
1774 // Lex the 'begin' or 'end'.
1775 PP.LexUnexpandedToken(Tok);
1776 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1777 if (BeginEnd && BeginEnd->isStr("begin")) {
1778 IsBegin = true;
1779 } else if (BeginEnd && BeginEnd->isStr("end")) {
1780 IsBegin = false;
1781 } else {
1782 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1783 return;
1784 }
1785
1786 // Verify that this is followed by EOD.
1787 PP.LexUnexpandedToken(Tok);
1788 if (Tok.isNot(tok::eod))
1789 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1790
1791 // The start location of the active audit.
1792 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1793
1794 // The start location we want after processing this.
1795 SourceLocation NewLoc;
Eli Friedman16fee082017-09-27 23:29:37 +00001796 PPCallbacks *Callbacks = PP.getPPCallbacks();
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001797
1798 if (IsBegin) {
1799 // Complain about attempts to re-enter an audit.
1800 if (BeginLoc.isValid()) {
1801 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1802 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1803 }
1804 NewLoc = Loc;
Eli Friedman16fee082017-09-27 23:29:37 +00001805 if (Callbacks)
1806 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001807 } else {
1808 // Complain about attempts to leave an audit that doesn't exist.
1809 if (!BeginLoc.isValid()) {
1810 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1811 return;
1812 }
1813 NewLoc = SourceLocation();
Eli Friedman16fee082017-09-27 23:29:37 +00001814 if (Callbacks)
1815 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001816 }
1817
1818 PP.setPragmaAssumeNonNullLoc(NewLoc);
1819 }
1820};
1821
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001822/// Handle "\#pragma region [...]"
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001823///
1824/// The syntax is
1825/// \code
1826/// #pragma region [optional name]
1827/// #pragma endregion [optional comment]
1828/// \endcode
1829///
1830/// \note This is
1831/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1832/// pragma, just skipped by compiler.
1833struct PragmaRegionHandler : public PragmaHandler {
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001834 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
Aaron Ballman406ea512012-11-30 19:52:30 +00001835
Craig Topper9140dd22014-03-11 06:50:42 +00001836 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1837 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001838 // #pragma region: endregion matches can be verified
1839 // __pragma(region): no sense, but ignored by msvc
1840 // _Pragma is not valid for MSVC, but there isn't any point
1841 // to handle a _Pragma differently.
1842 }
1843};
Aaron Ballman406ea512012-11-30 19:52:30 +00001844
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001845} // namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001846
1847/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001848/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001849void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001850 AddPragmaHandler(new PragmaOnceHandler());
1851 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001852 AddPragmaHandler(new PragmaPushMacroHandler());
1853 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001854 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001855
Chris Lattnerb61448d2009-05-12 18:21:11 +00001856 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001857 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1858 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1859 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001860 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001861 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1862 "GCC"));
1863 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1864 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001865 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001866 AddPragmaHandler("clang", new PragmaPoisonHandler());
1867 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001868 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001869 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001870 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001871 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001872 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001873
Richard Smithc51c38b2017-04-29 00:34:47 +00001874 // #pragma clang module ...
1875 auto *ModuleHandler = new PragmaNamespace("module");
1876 AddPragmaHandler("clang", ModuleHandler);
1877 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001878 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1879 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001880 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1881 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Fangrui Song6907ce22018-07-30 19:24:48 +00001882
Matt Davis1edb9052018-01-27 00:25:29 +00001883 // Add region pragmas.
1884 AddPragmaHandler(new PragmaRegionHandler("region"));
1885 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Richard Smithc51c38b2017-04-29 00:34:47 +00001886
Chris Lattner2ff698d2009-01-16 08:21:25 +00001887 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001888 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001889 AddPragmaHandler(new PragmaWarningHandler());
Reid Kleckner0f56b222019-03-14 18:12:17 +00001890 AddPragmaHandler(new PragmaExecCharsetHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001891 AddPragmaHandler(new PragmaIncludeAliasHandler());
Mike Rice58df1af2018-09-11 17:10:44 +00001892 AddPragmaHandler(new PragmaHdrstopHandler());
Chris Lattner30c924b2010-06-26 17:11:39 +00001893 }
John Brawn8e62db32016-04-04 14:22:58 +00001894
1895 // Pragmas added by plugins
1896 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1897 ie = PragmaHandlerRegistry::end();
1898 it != ie; ++it) {
1899 AddPragmaHandler(it->instantiate().release());
1900 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001901}
Lubos Lunak576a0412014-05-01 12:54:03 +00001902
1903/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1904/// warn about those pragmas being unknown.
1905void Preprocessor::IgnorePragmas() {
1906 AddPragmaHandler(new EmptyPragmaHandler());
1907 // Also ignore all pragmas in all namespaces created
1908 // in Preprocessor::RegisterBuiltinPragmas().
1909 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1910 AddPragmaHandler("clang", new EmptyPragmaHandler());
Lubos Lunak576a0412014-05-01 12:54:03 +00001911}