blob: 369fd92dd6116f3971fef9a9a60949563b280bd0 [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;
Richard Smithb9b05102019-03-19 01:51:19 +0000485 if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
Chris Lattnerb694ba72006-07-02 22:41:36 +0000486 return;
Mike Stump11289f42009-09-09 15:08:12 +0000487
Richard Smithb9b05102019-03-19 01:51:19 +0000488 // If the next token wasn't a header-name, diagnose the error.
489 if (!FilenameTok.isOneOf(tok::angle_string_literal, tok::string_literal)) {
490 Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
491 return;
492 }
493
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000494 // Reserve a buffer to get the spelling.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000495 SmallString<128> FilenameBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +0000496 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +0000498 if (Invalid)
499 return;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000501 bool isAngled =
502 GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000503 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
504 // error.
Chris Lattnerd081f8c2010-01-10 01:35:12 +0000505 if (Filename.empty())
Chris Lattnerc07ba1f2006-10-30 05:58:32 +0000506 return;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Chris Lattner59a9ebd2006-10-18 05:34:33 +0000508 // Search include directories for this file.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000509 const DirectoryLookup *CurDir;
Richard Smith25d50752014-10-20 00:15:49 +0000510 const FileEntry *File =
511 LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
Volodymyr Sapsai421380a2019-02-05 22:34:55 +0000512 nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
Craig Topperd2d442c2014-05-17 23:10:59 +0000513 if (!File) {
Eli Friedman3781a362011-08-30 23:07:51 +0000514 if (!SuppressIncludeNotFoundError)
515 Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
Chris Lattner97b8e842008-11-18 08:02:48 +0000516 return;
517 }
Mike Stump11289f42009-09-09 15:08:12 +0000518
Chris Lattnerd32480d2009-01-17 06:22:33 +0000519 const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000520
521 // If this file is older than the file it depends on, emit a diagnostic.
522 if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
523 // Lex tokens at the end of the message and include them in the message.
524 std::string Message;
525 Lex(DependencyTok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000526 while (DependencyTok.isNot(tok::eod)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000527 Message += getSpelling(DependencyTok) + " ";
528 Lex(DependencyTok);
529 }
Mike Stump11289f42009-09-09 15:08:12 +0000530
Chris Lattnerf0b04972010-09-05 23:16:09 +0000531 // Remove the trailing ' ' if present.
532 if (!Message.empty())
533 Message.erase(Message.end()-1);
Chris Lattner97b8e842008-11-18 08:02:48 +0000534 Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
Chris Lattnerb694ba72006-07-02 22:41:36 +0000535 }
536}
537
Reid Kleckner002562a2013-05-06 21:02:12 +0000538/// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000539/// Return the IdentifierInfo* associated with the macro to push or pop.
540IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
541 // Remember the pragma token location.
542 Token PragmaTok = Tok;
543
544 // Read the '('.
545 Lex(Tok);
546 if (Tok.isNot(tok::l_paren)) {
547 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
548 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000549 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000550 }
551
552 // Read the macro name string.
553 Lex(Tok);
554 if (Tok.isNot(tok::string_literal)) {
555 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
556 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000557 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000558 }
559
Richard Smithd67aea22012-03-06 03:21:47 +0000560 if (Tok.hasUDSuffix()) {
561 Diag(Tok, diag::err_invalid_string_udl);
Craig Topperd2d442c2014-05-17 23:10:59 +0000562 return nullptr;
Richard Smithd67aea22012-03-06 03:21:47 +0000563 }
564
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000565 // Remember the macro string.
566 std::string StrVal = getSpelling(Tok);
567
568 // Read the ')'.
569 Lex(Tok);
570 if (Tok.isNot(tok::r_paren)) {
571 Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
572 << getSpelling(PragmaTok);
Craig Topperd2d442c2014-05-17 23:10:59 +0000573 return nullptr;
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000574 }
575
576 assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
577 "Invalid string token!");
578
579 // Create a Token from the string.
580 Token MacroTok;
581 MacroTok.startToken();
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000582 MacroTok.setKind(tok::raw_identifier);
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000583 CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000584
585 // Get the IdentifierInfo of MacroToPushTok.
586 return LookUpIdentifierInfo(MacroTok);
587}
588
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000589/// Handle \#pragma push_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000590///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000591/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000592/// \code
Dmitri Gribenko9ebd1612012-11-30 20:04:39 +0000593/// #pragma push_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000594/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000595void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
596 // Parse the pragma directive and get the macro IdentifierInfo*.
597 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
598 if (!IdentInfo) return;
599
600 // Get the MacroInfo associated with IdentInfo.
601 MacroInfo *MI = getMacroInfo(IdentInfo);
Fangrui Song6907ce22018-07-30 19:24:48 +0000602
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000603 if (MI) {
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000604 // Allow the original MacroInfo to be redefined later.
605 MI->setIsAllowRedefinitionsWithoutWarning(true);
606 }
607
608 // Push the cloned MacroInfo so we can retrieve it later.
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +0000609 PragmaPushMacroInfo[IdentInfo].push_back(MI);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000610}
611
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000612/// Handle \#pragma pop_macro.
James Dennett18a6d792012-06-17 03:26:26 +0000613///
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000614/// The syntax is:
James Dennett18a6d792012-06-17 03:26:26 +0000615/// \code
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000616/// #pragma pop_macro("macro")
James Dennett18a6d792012-06-17 03:26:26 +0000617/// \endcode
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000618void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
619 SourceLocation MessageLoc = PopMacroTok.getLocation();
620
621 // Parse the pragma directive and get the macro IdentifierInfo*.
622 IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
623 if (!IdentInfo) return;
624
625 // Find the vector<MacroInfo*> associated with the macro.
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000626 llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000627 PragmaPushMacroInfo.find(IdentInfo);
628 if (iter != PragmaPushMacroInfo.end()) {
Alexander Kornienko8b3f6232012-08-29 00:20:03 +0000629 // Forget the MacroInfo currently associated with IdentInfo.
Richard Smith20e883e2015-04-29 23:20:19 +0000630 if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000631 if (MI->isWarnIfUnused())
632 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
633 appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000634 }
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000635
636 // Get the MacroInfo we want to reinstall.
637 MacroInfo *MacroToReInstall = iter->second.back();
638
Richard Smith713369b2015-04-23 20:40:50 +0000639 if (MacroToReInstall)
Alexander Kornienkoc0b49282012-08-29 16:56:24 +0000640 // Reinstall the previously pushed macro.
Richard Smith713369b2015-04-23 20:40:50 +0000641 appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000642
643 // Pop PragmaPushMacroInfo stack.
644 iter->second.pop_back();
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000645 if (iter->second.empty())
Chris Lattnerc0a585d2010-08-17 15:55:45 +0000646 PragmaPushMacroInfo.erase(iter);
647 } else {
648 Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
649 << IdentInfo->getName();
650 }
651}
Chris Lattnerb694ba72006-07-02 22:41:36 +0000652
Aaron Ballman611306e2012-03-02 22:51:54 +0000653void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000654 // We will either get a quoted filename or a bracketed filename, and we
Aaron Ballman611306e2012-03-02 22:51:54 +0000655 // have to track which we got. The first filename is the source name,
656 // and the second name is the mapped filename. If the first is quoted,
657 // the second must be as well (cannot mix and match quotes and brackets).
Aaron Ballman611306e2012-03-02 22:51:54 +0000658
659 // Get the open paren
660 Lex(Tok);
661 if (Tok.isNot(tok::l_paren)) {
662 Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
663 return;
664 }
665
666 // We expect either a quoted string literal, or a bracketed name
667 Token SourceFilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000668 if (LexHeaderName(SourceFilenameTok))
Aaron Ballman611306e2012-03-02 22:51:54 +0000669 return;
Aaron Ballman611306e2012-03-02 22:51:54 +0000670
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);
Aaron Ballman611306e2012-03-02 22:51:54 +0000676 } else {
677 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
678 return;
679 }
680 FileNameBuffer.clear();
681
682 // Now we expect a comma, followed by another include name
683 Lex(Tok);
684 if (Tok.isNot(tok::comma)) {
685 Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
686 return;
687 }
688
689 Token ReplaceFilenameTok;
Richard Smithb9b05102019-03-19 01:51:19 +0000690 if (LexHeaderName(ReplaceFilenameTok))
Aaron Ballman611306e2012-03-02 22:51:54 +0000691 return;
Aaron Ballman611306e2012-03-02 22:51:54 +0000692
693 StringRef ReplaceFileName;
Fangrui Song6907ce22018-07-30 19:24:48 +0000694 if (ReplaceFilenameTok.is(tok::string_literal) ||
Aaron Ballman611306e2012-03-02 22:51:54 +0000695 ReplaceFilenameTok.is(tok::angle_string_literal)) {
696 ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
Aaron Ballman611306e2012-03-02 22:51:54 +0000697 } else {
698 Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
699 return;
700 }
701
702 // Finally, we expect the closing paren
703 Lex(Tok);
704 if (Tok.isNot(tok::r_paren)) {
705 Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
706 return;
707 }
708
709 // Now that we have the source and target filenames, we need to make sure
710 // they're both of the same type (angled vs non-angled)
711 StringRef OriginalSource = SourceFileName;
712
Fangrui Song6907ce22018-07-30 19:24:48 +0000713 bool SourceIsAngled =
714 GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
Aaron Ballman611306e2012-03-02 22:51:54 +0000715 SourceFileName);
716 bool ReplaceIsAngled =
717 GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
718 ReplaceFileName);
719 if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
720 (SourceIsAngled != ReplaceIsAngled)) {
721 unsigned int DiagID;
722 if (SourceIsAngled)
723 DiagID = diag::warn_pragma_include_alias_mismatch_angle;
724 else
725 DiagID = diag::warn_pragma_include_alias_mismatch_quote;
726
727 Diag(SourceFilenameTok.getLocation(), DiagID)
Fangrui Song6907ce22018-07-30 19:24:48 +0000728 << SourceFileName
Aaron Ballman611306e2012-03-02 22:51:54 +0000729 << ReplaceFileName;
730
731 return;
732 }
733
734 // Now we can let the include handler know about this mapping
735 getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
736}
737
Richard Smith9565c75b2017-06-19 23:09:36 +0000738// Lex a component of a module name: either an identifier or a string literal;
739// for components that can be expressed both ways, the two forms are equivalent.
740static bool LexModuleNameComponent(
741 Preprocessor &PP, Token &Tok,
742 std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
743 bool First) {
744 PP.LexUnexpandedToken(Tok);
745 if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
746 StringLiteralParser Literal(Tok, PP);
747 if (Literal.hadError)
748 return true;
749 ModuleNameComponent = std::make_pair(
750 PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
751 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
752 ModuleNameComponent =
753 std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
754 } else {
755 PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
756 return true;
757 }
758 return false;
759}
760
761static bool LexModuleName(
762 Preprocessor &PP, Token &Tok,
763 llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
764 &ModuleName) {
765 while (true) {
766 std::pair<IdentifierInfo*, SourceLocation> NameComponent;
767 if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
768 return true;
769 ModuleName.push_back(NameComponent);
770
771 PP.LexUnexpandedToken(Tok);
772 if (Tok.isNot(tok::period))
773 return false;
774 }
775}
776
Richard Smith5d2ed482017-06-09 19:22:32 +0000777void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
778 SourceLocation Loc = Tok.getLocation();
779
Richard Smith9565c75b2017-06-19 23:09:36 +0000780 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
781 if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
Richard Smith5d2ed482017-06-09 19:22:32 +0000782 return;
Richard Smith9565c75b2017-06-19 23:09:36 +0000783 IdentifierInfo *ModuleName = ModuleNameLoc.first;
Richard Smith5d2ed482017-06-09 19:22:32 +0000784
785 LexUnexpandedToken(Tok);
786 if (Tok.isNot(tok::eod)) {
787 Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
788 DiscardUntilEndOfDirective();
789 }
790
Richard Smith5d2ed482017-06-09 19:22:32 +0000791 CurLexer->LexingRawMode = true;
792
793 auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
794 if (Tok.getKind() != tok::raw_identifier ||
795 Tok.getRawIdentifier() != Ident)
796 return false;
797 CurLexer->Lex(Tok);
798 return true;
799 };
800
801 // Scan forward looking for the end of the module.
802 const char *Start = CurLexer->getBufferLocation();
803 const char *End = nullptr;
804 unsigned NestingLevel = 1;
805 while (true) {
806 End = CurLexer->getBufferLocation();
807 CurLexer->Lex(Tok);
808
809 if (Tok.is(tok::eof)) {
810 Diag(Loc, diag::err_pp_module_build_missing_end);
811 break;
812 }
813
814 if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
815 // Token was part of module; keep going.
816 continue;
817 }
818
819 // We hit something directive-shaped; check to see if this is the end
820 // of the module build.
821 CurLexer->ParsingPreprocessorDirective = true;
822 CurLexer->Lex(Tok);
823 if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
824 TryConsumeIdentifier("module")) {
825 if (TryConsumeIdentifier("build"))
826 // #pragma clang module build -> entering a nested module build.
827 ++NestingLevel;
828 else if (TryConsumeIdentifier("endbuild")) {
829 // #pragma clang module endbuild -> leaving a module build.
830 if (--NestingLevel == 0)
831 break;
832 }
833 // We should either be looking at the EOD or more of the current directive
834 // preceding the EOD. Either way we can ignore this token and keep going.
835 assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
836 }
837 }
838
839 CurLexer->LexingRawMode = false;
840
841 // Load the extracted text as a preprocessed module.
842 assert(CurLexer->getBuffer().begin() <= Start &&
843 Start <= CurLexer->getBuffer().end() &&
844 CurLexer->getBuffer().begin() <= End &&
845 End <= CurLexer->getBuffer().end() &&
846 "module source range not contained within same file buffer");
847 TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
848 StringRef(Start, End - Start));
849}
850
Mike Rice58df1af2018-09-11 17:10:44 +0000851void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
852 Lex(Tok);
853 if (Tok.is(tok::l_paren)) {
854 Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
855
856 std::string FileName;
857 if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
858 return;
859
860 if (Tok.isNot(tok::r_paren)) {
861 Diag(Tok, diag::err_expected) << tok::r_paren;
862 return;
863 }
864 Lex(Tok);
865 }
866 if (Tok.isNot(tok::eod))
867 Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
868 << "pragma hdrstop";
869
870 if (creatingPCHWithPragmaHdrStop() &&
871 SourceMgr.isInMainFile(Tok.getLocation())) {
872 assert(CurLexer && "no lexer for #pragma hdrstop processing");
873 Token &Result = Tok;
874 Result.startToken();
875 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
876 CurLexer->cutOffLexing();
877 }
878 if (usingPCHWithPragmaHdrStop())
879 SkippingUntilPragmaHdrStop = false;
880}
881
Chris Lattnerb694ba72006-07-02 22:41:36 +0000882/// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
883/// If 'Namespace' is non-null, then it is a token required to exist on the
884/// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000885void Preprocessor::AddPragmaHandler(StringRef Namespace,
Chris Lattnerb694ba72006-07-02 22:41:36 +0000886 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000887 PragmaNamespace *InsertNS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000888
Chris Lattnerb694ba72006-07-02 22:41:36 +0000889 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000890 if (!Namespace.empty()) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000891 // If there is already a pragma handler with the name of this namespace,
892 // we either have an error (directive with the same name as a namespace) or
893 // we already have the namespace to insert into.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000894 if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
Chris Lattnerb694ba72006-07-02 22:41:36 +0000895 InsertNS = Existing->getIfNamespace();
Craig Topperd2d442c2014-05-17 23:10:59 +0000896 assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
Chris Lattnerb694ba72006-07-02 22:41:36 +0000897 " handler with the same name!");
898 } else {
899 // Otherwise, this namespace doesn't exist yet, create and insert the
900 // handler for it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000901 InsertNS = new PragmaNamespace(Namespace);
Chris Lattnerb694ba72006-07-02 22:41:36 +0000902 PragmaHandlers->AddPragma(InsertNS);
903 }
904 }
Mike Stump11289f42009-09-09 15:08:12 +0000905
Chris Lattnerb694ba72006-07-02 22:41:36 +0000906 // Check to make sure we don't already have a pragma for this identifier.
907 assert(!InsertNS->FindHandler(Handler->getName()) &&
908 "Pragma handler already exists for this identifier!");
909 InsertNS->AddPragma(Handler);
910}
911
Daniel Dunbar40596532008-10-04 19:17:46 +0000912/// RemovePragmaHandler - Remove the specific pragma handler from the
913/// preprocessor. If \arg Namespace is non-null, then it should be the
914/// namespace that \arg Handler was added to. It is an error to remove
915/// a handler that has not been registered.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000916void Preprocessor::RemovePragmaHandler(StringRef Namespace,
Daniel Dunbar40596532008-10-04 19:17:46 +0000917 PragmaHandler *Handler) {
Craig Topperbe250302014-09-12 05:19:24 +0000918 PragmaNamespace *NS = PragmaHandlers.get();
Mike Stump11289f42009-09-09 15:08:12 +0000919
Daniel Dunbar40596532008-10-04 19:17:46 +0000920 // If this is specified to be in a namespace, step down into it.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000921 if (!Namespace.empty()) {
922 PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
Daniel Dunbar40596532008-10-04 19:17:46 +0000923 assert(Existing && "Namespace containing handler does not exist!");
924
925 NS = Existing->getIfNamespace();
926 assert(NS && "Invalid namespace, registered as a regular pragma handler!");
927 }
928
929 NS->RemovePragmaHandler(Handler);
Mike Stump11289f42009-09-09 15:08:12 +0000930
Craig Topperbe250302014-09-12 05:19:24 +0000931 // If this is a non-default namespace and it is now empty, remove it.
932 if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
Daniel Dunbar40596532008-10-04 19:17:46 +0000933 PragmaHandlers->RemovePragmaHandler(NS);
Argyrios Kyrtzidis7ce75262012-01-06 00:22:09 +0000934 delete NS;
935 }
Daniel Dunbar40596532008-10-04 19:17:46 +0000936}
937
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000938bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
939 Token Tok;
940 LexUnexpandedToken(Tok);
941
942 if (Tok.isNot(tok::identifier)) {
943 Diag(Tok, diag::ext_on_off_switch_syntax);
944 return true;
945 }
946 IdentifierInfo *II = Tok.getIdentifierInfo();
947 if (II->isStr("ON"))
948 Result = tok::OOS_ON;
949 else if (II->isStr("OFF"))
950 Result = tok::OOS_OFF;
951 else if (II->isStr("DEFAULT"))
952 Result = tok::OOS_DEFAULT;
953 else {
954 Diag(Tok, diag::ext_on_off_switch_syntax);
955 return true;
956 }
957
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000958 // Verify that this is followed by EOD.
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000959 LexUnexpandedToken(Tok);
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +0000960 if (Tok.isNot(tok::eod))
961 Diag(Tok, diag::ext_pragma_syntax_eod);
Peter Collingbourne3bffa522011-02-14 01:42:24 +0000962 return false;
963}
964
Chris Lattnerb694ba72006-07-02 22:41:36 +0000965namespace {
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000966
James Dennett18a6d792012-06-17 03:26:26 +0000967/// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000968struct PragmaOnceHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000969 PragmaOnceHandler() : PragmaHandler("once") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +0000970
Craig Topper9140dd22014-03-11 06:50:42 +0000971 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
972 Token &OnceTok) override {
Chris Lattnerce2ab6f2009-04-14 05:07:49 +0000973 PP.CheckEndOfDirective("pragma once");
Chris Lattnerb694ba72006-07-02 22:41:36 +0000974 PP.HandlePragmaOnce(OnceTok);
975 }
976};
977
James Dennett18a6d792012-06-17 03:26:26 +0000978/// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
Chris Lattnerc2383312007-12-19 19:38:36 +0000979/// rest of the line is not lexed.
980struct PragmaMarkHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000981 PragmaMarkHandler() : PragmaHandler("mark") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000982
Craig Topper9140dd22014-03-11 06:50:42 +0000983 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
984 Token &MarkTok) override {
Chris Lattnerc2383312007-12-19 19:38:36 +0000985 PP.HandlePragmaMark();
986 }
987};
988
James Dennett18a6d792012-06-17 03:26:26 +0000989/// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
Chris Lattnerb694ba72006-07-02 22:41:36 +0000990struct PragmaPoisonHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +0000991 PragmaPoisonHandler() : PragmaHandler("poison") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000992
Craig Topper9140dd22014-03-11 06:50:42 +0000993 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
994 Token &PoisonTok) override {
Erik Verbruggen851ce0e2016-10-26 11:46:10 +0000995 PP.HandlePragmaPoison();
Chris Lattnerb694ba72006-07-02 22:41:36 +0000996 }
997};
998
James Dennett18a6d792012-06-17 03:26:26 +0000999/// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
Chris Lattnerc2383312007-12-19 19:38:36 +00001000/// as a system header, which silences warnings in it.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001001struct PragmaSystemHeaderHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001002 PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001003
Craig Topper9140dd22014-03-11 06:50:42 +00001004 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1005 Token &SHToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001006 PP.HandlePragmaSystemHeader(SHToken);
Chris Lattnerce2ab6f2009-04-14 05:07:49 +00001007 PP.CheckEndOfDirective("pragma");
Chris Lattnerb694ba72006-07-02 22:41:36 +00001008 }
1009};
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001010
Chris Lattnerb694ba72006-07-02 22:41:36 +00001011struct PragmaDependencyHandler : public PragmaHandler {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001012 PragmaDependencyHandler() : PragmaHandler("dependency") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001013
Craig Topper9140dd22014-03-11 06:50:42 +00001014 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1015 Token &DepToken) override {
Chris Lattnerb694ba72006-07-02 22:41:36 +00001016 PP.HandlePragmaDependency(DepToken);
1017 }
1018};
Mike Stump11289f42009-09-09 15:08:12 +00001019
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001020struct PragmaDebugHandler : public PragmaHandler {
1021 PragmaDebugHandler() : PragmaHandler("__debug") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001022
Craig Topper9140dd22014-03-11 06:50:42 +00001023 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1024 Token &DepToken) override {
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001025 Token Tok;
1026 PP.LexUnexpandedToken(Tok);
1027 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001028 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001029 return;
1030 }
1031 IdentifierInfo *II = Tok.getIdentifierInfo();
1032
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001033 if (II->isStr("assert")) {
David Blaikie83d382b2011-09-23 05:06:16 +00001034 llvm_unreachable("This is an assertion!");
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001035 } else if (II->isStr("crash")) {
David Blaikie5bd4c2a2012-08-21 18:56:49 +00001036 LLVM_BUILTIN_TRAP;
David Blaikie5d577a22012-06-29 22:03:56 +00001037 } else if (II->isStr("parser_crash")) {
1038 Token Crasher;
Benjamin Kramer3162f292015-03-08 19:28:24 +00001039 Crasher.startToken();
David Blaikie5d577a22012-06-29 22:03:56 +00001040 Crasher.setKind(tok::annot_pragma_parser_crash);
Benjamin Kramer3162f292015-03-08 19:28:24 +00001041 Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
David Blaikie5d577a22012-06-29 22:03:56 +00001042 PP.EnterToken(Crasher);
Richard Smithba3a4f92016-01-12 21:59:26 +00001043 } else if (II->isStr("dump")) {
1044 Token Identifier;
1045 PP.LexUnexpandedToken(Identifier);
1046 if (auto *DumpII = Identifier.getIdentifierInfo()) {
1047 Token DumpAnnot;
1048 DumpAnnot.startToken();
1049 DumpAnnot.setKind(tok::annot_pragma_dump);
1050 DumpAnnot.setAnnotationRange(
1051 SourceRange(Tok.getLocation(), Identifier.getLocation()));
1052 DumpAnnot.setAnnotationValue(DumpII);
1053 PP.DiscardUntilEndOfDirective();
1054 PP.EnterToken(DumpAnnot);
1055 } else {
1056 PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
1057 << II->getName();
1058 }
Richard Smith6c2b5a82018-02-09 01:15:13 +00001059 } else if (II->isStr("diag_mapping")) {
1060 Token DiagName;
1061 PP.LexUnexpandedToken(DiagName);
1062 if (DiagName.is(tok::eod))
1063 PP.getDiagnostics().dump();
1064 else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
1065 StringLiteralParser Literal(DiagName, PP);
1066 if (Literal.hadError)
1067 return;
1068 PP.getDiagnostics().dump(Literal.GetString());
1069 } else {
1070 PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
1071 << II->getName();
1072 }
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001073 } else if (II->isStr("llvm_fatal_error")) {
1074 llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
1075 } else if (II->isStr("llvm_unreachable")) {
1076 llvm_unreachable("#pragma clang __debug llvm_unreachable");
Richard Smith3ffa61d2015-04-30 23:10:40 +00001077 } else if (II->isStr("macro")) {
1078 Token MacroName;
1079 PP.LexUnexpandedToken(MacroName);
1080 auto *MacroII = MacroName.getIdentifierInfo();
1081 if (MacroII)
1082 PP.dumpMacroInfo(MacroII);
1083 else
Richard Smithba3a4f92016-01-12 21:59:26 +00001084 PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
1085 << II->getName();
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001086 } else if (II->isStr("overflow_stack")) {
1087 DebugOverflowStack();
Daniel Dunbar211a7872010-08-18 23:09:23 +00001088 } else if (II->isStr("handle_crash")) {
1089 llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
1090 if (CRC)
1091 CRC->HandleCrash();
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001092 } else if (II->isStr("captured")) {
1093 HandleCaptured(PP);
Daniel Dunbarf2cf3292010-08-17 22:32:48 +00001094 } else {
1095 PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
1096 << II->getName();
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001097 }
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001098
1099 PPCallbacks *Callbacks = PP.getPPCallbacks();
1100 if (Callbacks)
1101 Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
1102 }
1103
1104 void HandleCaptured(Preprocessor &PP) {
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001105 Token Tok;
1106 PP.LexUnexpandedToken(Tok);
1107
1108 if (Tok.isNot(tok::eod)) {
1109 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
1110 << "pragma clang __debug captured";
1111 return;
1112 }
1113
1114 SourceLocation NameLoc = Tok.getLocation();
David Blaikie2eabcc92016-02-09 18:52:09 +00001115 MutableArrayRef<Token> Toks(
1116 PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
1117 Toks[0].startToken();
1118 Toks[0].setKind(tok::annot_pragma_captured);
1119 Toks[0].setLocation(NameLoc);
Tareq A. Siraj0de0dd42013-04-16 18:41:26 +00001120
David Blaikie2eabcc92016-02-09 18:52:09 +00001121 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true);
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001122 }
1123
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001124// Disable MSVC warning about runtime stack overflow.
1125#ifdef _MSC_VER
1126 #pragma warning(disable : 4717)
1127#endif
Matthias Braun285f88d2017-04-24 18:41:00 +00001128 static void DebugOverflowStack(void (*P)() = nullptr) {
1129 void (*volatile Self)(void(*P)()) = DebugOverflowStack;
1130 Self(reinterpret_cast<void(*)()>(Self));
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001131 }
Francois Pichet2e11f5d2011-05-25 16:15:03 +00001132#ifdef _MSC_VER
1133 #pragma warning(default : 4717)
1134#endif
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001135};
1136
James Dennett18a6d792012-06-17 03:26:26 +00001137/// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
Chris Lattner504af112009-04-19 23:16:58 +00001138struct PragmaDiagnosticHandler : public PragmaHandler {
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001139private:
1140 const char *Namespace;
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001141
Chris Lattnerfb42a182009-07-12 21:18:45 +00001142public:
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001143 explicit PragmaDiagnosticHandler(const char *NS)
1144 : PragmaHandler("diagnostic"), Namespace(NS) {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001145
Craig Topper9140dd22014-03-11 06:50:42 +00001146 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1147 Token &DiagToken) override {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001148 SourceLocation DiagLoc = DiagToken.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001149 Token Tok;
1150 PP.LexUnexpandedToken(Tok);
1151 if (Tok.isNot(tok::identifier)) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001152 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001153 return;
1154 }
1155 IdentifierInfo *II = Tok.getIdentifierInfo();
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001156 PPCallbacks *Callbacks = PP.getPPCallbacks();
Mike Stump11289f42009-09-09 15:08:12 +00001157
Alp Toker46df1c02014-06-12 10:15:20 +00001158 if (II->isStr("pop")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001159 if (!PP.getDiagnostics().popMappings(DiagLoc))
Douglas Gregor3cc26482010-08-30 15:15:34 +00001160 PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001161 else if (Callbacks)
1162 Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
Douglas Gregor3cc26482010-08-30 15:15:34 +00001163 return;
1164 } else if (II->isStr("push")) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00001165 PP.getDiagnostics().pushMappings(DiagLoc);
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001166 if (Callbacks)
1167 Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
Chris Lattnerfb42a182009-07-12 21:18:45 +00001168 return;
Alp Toker46df1c02014-06-12 10:15:20 +00001169 }
1170
1171 diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
1172 .Case("ignored", diag::Severity::Ignored)
1173 .Case("warning", diag::Severity::Warning)
1174 .Case("error", diag::Severity::Error)
1175 .Case("fatal", diag::Severity::Fatal)
1176 .Default(diag::Severity());
1177
1178 if (SV == diag::Severity()) {
Douglas Gregor3cc26482010-08-30 15:15:34 +00001179 PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
Chris Lattner504af112009-04-19 23:16:58 +00001180 return;
1181 }
Mike Stump11289f42009-09-09 15:08:12 +00001182
Chris Lattner504af112009-04-19 23:16:58 +00001183 PP.LexUnexpandedToken(Tok);
Andy Gibbs58905d22012-11-17 19:15:38 +00001184 SourceLocation StringLoc = Tok.getLocation();
Chris Lattner504af112009-04-19 23:16:58 +00001185
Andy Gibbs58905d22012-11-17 19:15:38 +00001186 std::string WarningName;
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001187 if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
1188 /*MacroExpansion=*/false))
Chris Lattner504af112009-04-19 23:16:58 +00001189 return;
Mike Stump11289f42009-09-09 15:08:12 +00001190
Peter Collingbourne2f1e36b2011-02-28 02:37:51 +00001191 if (Tok.isNot(tok::eod)) {
Chris Lattner504af112009-04-19 23:16:58 +00001192 PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
1193 return;
1194 }
Mike Stump11289f42009-09-09 15:08:12 +00001195
Chris Lattner504af112009-04-19 23:16:58 +00001196 if (WarningName.size() < 3 || WarningName[0] != '-' ||
Richard Smith3be1cb22014-08-07 00:24:21 +00001197 (WarningName[1] != 'W' && WarningName[1] != 'R')) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001198 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
Chris Lattner504af112009-04-19 23:16:58 +00001199 return;
1200 }
Mike Stump11289f42009-09-09 15:08:12 +00001201
Sunil Srivastava5239de72016-02-13 01:44:05 +00001202 diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1203 : diag::Flavor::Remark;
Benjamin Kramer2193e232016-02-13 13:42:41 +00001204 StringRef Group = StringRef(WarningName).substr(2);
Sunil Srivastava5239de72016-02-13 01:44:05 +00001205 bool unknownDiag = false;
1206 if (Group == "everything") {
1207 // Special handling for pragma clang diagnostic ... "-Weverything".
1208 // There is no formal group named "everything", so there has to be a
1209 // special case for it.
1210 PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
1211 } else
1212 unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
1213 DiagLoc);
1214 if (unknownDiag)
Andy Gibbs58905d22012-11-17 19:15:38 +00001215 PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1216 << WarningName;
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001217 else if (Callbacks)
Alp Toker46df1c02014-06-12 10:15:20 +00001218 Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
Chris Lattner504af112009-04-19 23:16:58 +00001219 }
1220};
Mike Stump11289f42009-09-09 15:08:12 +00001221
Mike Rice58df1af2018-09-11 17:10:44 +00001222/// "\#pragma hdrstop [<header-name-string>]"
1223struct PragmaHdrstopHandler : public PragmaHandler {
1224 PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
1225 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1226 Token &DepToken) override {
1227 PP.HandlePragmaHdrstop(DepToken);
1228 }
1229};
1230
Reid Kleckner881dff32013-09-13 22:00:30 +00001231/// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
1232/// diagnostics, so we don't really implement this pragma. We parse it and
1233/// ignore it to avoid -Wunknown-pragma warnings.
1234struct PragmaWarningHandler : public PragmaHandler {
1235 PragmaWarningHandler() : PragmaHandler("warning") {}
1236
Craig Topper9140dd22014-03-11 06:50:42 +00001237 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1238 Token &Tok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001239 // Parse things like:
1240 // warning(push, 1)
1241 // warning(pop)
John Thompson4762b232013-11-16 00:16:03 +00001242 // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
Reid Kleckner881dff32013-09-13 22:00:30 +00001243 SourceLocation DiagLoc = Tok.getLocation();
1244 PPCallbacks *Callbacks = PP.getPPCallbacks();
1245
1246 PP.Lex(Tok);
1247 if (Tok.isNot(tok::l_paren)) {
1248 PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1249 return;
1250 }
1251
1252 PP.Lex(Tok);
1253 IdentifierInfo *II = Tok.getIdentifierInfo();
Reid Kleckner881dff32013-09-13 22:00:30 +00001254
Alexander Musman6b080fc2015-05-25 11:21:20 +00001255 if (II && II->isStr("push")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001256 // #pragma warning( push[ ,n ] )
Reid Kleckner4d185102013-10-02 15:19:23 +00001257 int Level = -1;
Reid Kleckner881dff32013-09-13 22:00:30 +00001258 PP.Lex(Tok);
1259 if (Tok.is(tok::comma)) {
1260 PP.Lex(Tok);
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001261 uint64_t Value;
1262 if (Tok.is(tok::numeric_constant) &&
1263 PP.parseSimpleIntegerLiteral(Tok, Value))
1264 Level = int(Value);
Reid Kleckner4d185102013-10-02 15:19:23 +00001265 if (Level < 0 || Level > 4) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001266 PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1267 return;
1268 }
1269 }
1270 if (Callbacks)
1271 Callbacks->PragmaWarningPush(DiagLoc, Level);
Alexander Musman6b080fc2015-05-25 11:21:20 +00001272 } else if (II && II->isStr("pop")) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001273 // #pragma warning( pop )
1274 PP.Lex(Tok);
1275 if (Callbacks)
1276 Callbacks->PragmaWarningPop(DiagLoc);
1277 } else {
1278 // #pragma warning( warning-specifier : warning-number-list
1279 // [; warning-specifier : warning-number-list...] )
1280 while (true) {
1281 II = Tok.getIdentifierInfo();
Alexander Musman6b080fc2015-05-25 11:21:20 +00001282 if (!II && !Tok.is(tok::numeric_constant)) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001283 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1284 return;
1285 }
1286
1287 // Figure out which warning specifier this is.
Alexander Musman6b080fc2015-05-25 11:21:20 +00001288 bool SpecifierValid;
1289 StringRef Specifier;
1290 llvm::SmallString<1> SpecifierBuf;
1291 if (II) {
1292 Specifier = II->getName();
1293 SpecifierValid = llvm::StringSwitch<bool>(Specifier)
1294 .Cases("default", "disable", "error", "once",
1295 "suppress", true)
1296 .Default(false);
1297 // If we read a correct specifier, snatch next token (that should be
1298 // ":", checked later).
1299 if (SpecifierValid)
1300 PP.Lex(Tok);
1301 } else {
1302 // Token is a numeric constant. It should be either 1, 2, 3 or 4.
1303 uint64_t Value;
1304 Specifier = PP.getSpelling(Tok, SpecifierBuf);
1305 if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
1306 SpecifierValid = (Value >= 1) && (Value <= 4);
1307 } else
1308 SpecifierValid = false;
1309 // Next token already snatched by parseSimpleIntegerLiteral.
1310 }
1311
Reid Kleckner881dff32013-09-13 22:00:30 +00001312 if (!SpecifierValid) {
1313 PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1314 return;
1315 }
Reid Kleckner881dff32013-09-13 22:00:30 +00001316 if (Tok.isNot(tok::colon)) {
1317 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1318 return;
1319 }
1320
1321 // Collect the warning ids.
1322 SmallVector<int, 4> Ids;
1323 PP.Lex(Tok);
1324 while (Tok.is(tok::numeric_constant)) {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001325 uint64_t Value;
1326 if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001327 Value > std::numeric_limits<int>::max()) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001328 PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1329 return;
1330 }
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001331 Ids.push_back(int(Value));
Reid Kleckner881dff32013-09-13 22:00:30 +00001332 }
1333 if (Callbacks)
1334 Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1335
1336 // Parse the next specifier if there is a semicolon.
1337 if (Tok.isNot(tok::semi))
1338 break;
1339 PP.Lex(Tok);
1340 }
1341 }
1342
1343 if (Tok.isNot(tok::r_paren)) {
1344 PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1345 return;
1346 }
1347
1348 PP.Lex(Tok);
1349 if (Tok.isNot(tok::eod))
1350 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1351 }
1352};
1353
Reid Kleckner0f56b222019-03-14 18:12:17 +00001354/// "\#pragma execution_character_set(...)". MSVC supports this pragma only
1355/// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
1356/// otherwise to avoid -Wunknown-pragma warnings.
1357struct PragmaExecCharsetHandler : public PragmaHandler {
1358 PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
1359
1360 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1361 Token &Tok) override {
1362 // Parse things like:
1363 // execution_character_set(push, "UTF-8")
1364 // execution_character_set(pop)
1365 SourceLocation DiagLoc = Tok.getLocation();
1366 PPCallbacks *Callbacks = PP.getPPCallbacks();
1367
1368 PP.Lex(Tok);
1369 if (Tok.isNot(tok::l_paren)) {
1370 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
1371 return;
1372 }
1373
1374 PP.Lex(Tok);
1375 IdentifierInfo *II = Tok.getIdentifierInfo();
1376
1377 if (II && II->isStr("push")) {
1378 // #pragma execution_character_set( push[ , string ] )
1379 PP.Lex(Tok);
1380 if (Tok.is(tok::comma)) {
1381 PP.Lex(Tok);
1382
1383 std::string ExecCharset;
1384 if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
1385 "pragma execution_character_set",
1386 /*MacroExpansion=*/false))
1387 return;
1388
1389 // MSVC supports either of these, but nothing else.
1390 if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
1391 PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
1392 return;
1393 }
1394 }
1395 if (Callbacks)
1396 Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
1397 } else if (II && II->isStr("pop")) {
1398 // #pragma execution_character_set( pop )
1399 PP.Lex(Tok);
1400 if (Callbacks)
1401 Callbacks->PragmaExecCharsetPop(DiagLoc);
1402 } else {
1403 PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
1404 return;
1405 }
1406
1407 if (Tok.isNot(tok::r_paren)) {
1408 PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
1409 return;
1410 }
1411
1412 PP.Lex(Tok);
1413 if (Tok.isNot(tok::eod))
1414 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
1415 }
1416};
1417
James Dennett18a6d792012-06-17 03:26:26 +00001418/// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
Aaron Ballman611306e2012-03-02 22:51:54 +00001419struct PragmaIncludeAliasHandler : public PragmaHandler {
1420 PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001421
Craig Topper9140dd22014-03-11 06:50:42 +00001422 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1423 Token &IncludeAliasTok) override {
Reid Kleckner881dff32013-09-13 22:00:30 +00001424 PP.HandlePragmaIncludeAlias(IncludeAliasTok);
Aaron Ballman611306e2012-03-02 22:51:54 +00001425 }
1426};
1427
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001428/// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1429/// extension. The syntax is:
1430/// \code
1431/// #pragma message(string)
1432/// \endcode
1433/// OR, in GCC mode:
1434/// \code
1435/// #pragma message string
1436/// \endcode
1437/// string is a string, which is fully macro expanded, and permits string
1438/// concatenation, embedded escape characters, etc... See MSDN for more details.
1439/// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1440/// form as \#pragma message.
Chris Lattner30c924b2010-06-26 17:11:39 +00001441struct PragmaMessageHandler : public PragmaHandler {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001442private:
1443 const PPCallbacks::PragmaMessageKind Kind;
1444 const StringRef Namespace;
1445
1446 static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1447 bool PragmaNameOnly = false) {
1448 switch (Kind) {
1449 case PPCallbacks::PMK_Message:
1450 return PragmaNameOnly ? "message" : "pragma message";
1451 case PPCallbacks::PMK_Warning:
1452 return PragmaNameOnly ? "warning" : "pragma warning";
1453 case PPCallbacks::PMK_Error:
1454 return PragmaNameOnly ? "error" : "pragma error";
1455 }
1456 llvm_unreachable("Unknown PragmaMessageKind!");
1457 }
1458
1459public:
1460 PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1461 StringRef Namespace = StringRef())
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001462 : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
1463 Namespace(Namespace) {}
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001464
Craig Topper9140dd22014-03-11 06:50:42 +00001465 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1466 Token &Tok) override {
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001467 SourceLocation MessageLoc = Tok.getLocation();
1468 PP.Lex(Tok);
1469 bool ExpectClosingParen = false;
1470 switch (Tok.getKind()) {
1471 case tok::l_paren:
1472 // We have a MSVC style pragma message.
1473 ExpectClosingParen = true;
1474 // Read the string.
1475 PP.Lex(Tok);
1476 break;
1477 case tok::string_literal:
1478 // We have a GCC style pragma message, and we just read the string.
1479 break;
1480 default:
1481 PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1482 return;
1483 }
1484
1485 std::string MessageString;
1486 if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1487 /*MacroExpansion=*/true))
1488 return;
1489
1490 if (ExpectClosingParen) {
1491 if (Tok.isNot(tok::r_paren)) {
1492 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1493 return;
1494 }
1495 PP.Lex(Tok); // eat the r_paren.
1496 }
1497
1498 if (Tok.isNot(tok::eod)) {
1499 PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1500 return;
1501 }
1502
1503 // Output the message.
1504 PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1505 ? diag::err_pragma_message
1506 : diag::warn_pragma_message) << MessageString;
1507
1508 // If the pragma is lexically sound, notify any interested PPCallbacks.
1509 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1510 Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
Chris Lattner30c924b2010-06-26 17:11:39 +00001511 }
1512};
1513
Richard Smithc51c38b2017-04-29 00:34:47 +00001514/// Handle the clang \#pragma module import extension. The syntax is:
1515/// \code
1516/// #pragma clang module import some.module.name
1517/// \endcode
1518struct PragmaModuleImportHandler : public PragmaHandler {
1519 PragmaModuleImportHandler() : PragmaHandler("import") {}
1520
1521 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
Richard Smithd1386302017-05-04 00:29:54 +00001522 Token &Tok) override {
1523 SourceLocation ImportLoc = Tok.getLocation();
1524
1525 // Read the module name.
1526 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1527 ModuleName;
1528 if (LexModuleName(PP, Tok, ModuleName))
1529 return;
1530
1531 if (Tok.isNot(tok::eod))
1532 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1533
1534 // If we have a non-empty module path, load the named module.
1535 Module *Imported =
1536 PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
1537 /*IsIncludeDirective=*/false);
1538 if (!Imported)
1539 return;
1540
1541 PP.makeModuleVisible(Imported, ImportLoc);
1542 PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
1543 tok::annot_module_include, Imported);
1544 if (auto *CB = PP.getPPCallbacks())
1545 CB->moduleImport(ImportLoc, ModuleName, Imported);
1546 }
1547};
1548
1549/// Handle the clang \#pragma module begin extension. The syntax is:
1550/// \code
1551/// #pragma clang module begin some.module.name
1552/// ...
1553/// #pragma clang module end
1554/// \endcode
1555struct PragmaModuleBeginHandler : public PragmaHandler {
1556 PragmaModuleBeginHandler() : PragmaHandler("begin") {}
1557
1558 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1559 Token &Tok) override {
1560 SourceLocation BeginLoc = Tok.getLocation();
1561
1562 // Read the module name.
1563 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1564 ModuleName;
1565 if (LexModuleName(PP, Tok, ModuleName))
1566 return;
1567
1568 if (Tok.isNot(tok::eod))
1569 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1570
1571 // We can only enter submodules of the current module.
1572 StringRef Current = PP.getLangOpts().CurrentModule;
1573 if (ModuleName.front().first->getName() != Current) {
1574 PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
1575 << ModuleName.front().first << (ModuleName.size() > 1)
1576 << Current.empty() << Current;
1577 return;
1578 }
1579
1580 // Find the module we're entering. We require that a module map for it
1581 // be loaded or implicitly loadable.
1582 // FIXME: We could create the submodule here. We'd need to know whether
1583 // it's supposed to be explicit, but not much else.
Richard Smith9565c75b2017-06-19 23:09:36 +00001584 Module *M = PP.getHeaderSearchInfo().lookupModule(Current);
Richard Smithd1386302017-05-04 00:29:54 +00001585 if (!M) {
1586 PP.Diag(ModuleName.front().second,
1587 diag::err_pp_module_begin_no_module_map) << Current;
1588 return;
1589 }
1590 for (unsigned I = 1; I != ModuleName.size(); ++I) {
1591 auto *NewM = M->findSubmodule(ModuleName[I].first->getName());
1592 if (!NewM) {
1593 PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
1594 << M->getFullModuleName() << ModuleName[I].first;
1595 return;
1596 }
1597 M = NewM;
1598 }
1599
Richard Smith51d09c52017-05-30 05:22:59 +00001600 // If the module isn't available, it doesn't make sense to enter it.
Richard Smith27e5aa02017-06-05 18:57:56 +00001601 if (Preprocessor::checkModuleIsAvailable(
1602 PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
Richard Smith51d09c52017-05-30 05:22:59 +00001603 PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
1604 << M->getTopLevelModuleName();
1605 return;
1606 }
1607
Richard Smithd1386302017-05-04 00:29:54 +00001608 // Enter the scope of the submodule.
1609 PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
1610 PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
1611 tok::annot_module_begin, M);
1612 }
1613};
1614
1615/// Handle the clang \#pragma module end extension.
1616struct PragmaModuleEndHandler : public PragmaHandler {
1617 PragmaModuleEndHandler() : PragmaHandler("end") {}
1618
1619 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1620 Token &Tok) override {
1621 SourceLocation Loc = Tok.getLocation();
1622
1623 PP.LexUnexpandedToken(Tok);
1624 if (Tok.isNot(tok::eod))
1625 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1626
1627 Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
1628 if (M)
1629 PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
1630 else
1631 PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
Richard Smithc51c38b2017-04-29 00:34:47 +00001632 }
1633};
1634
Richard Smith5d2ed482017-06-09 19:22:32 +00001635/// Handle the clang \#pragma module build extension.
1636struct PragmaModuleBuildHandler : public PragmaHandler {
1637 PragmaModuleBuildHandler() : PragmaHandler("build") {}
1638
1639 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1640 Token &Tok) override {
1641 PP.HandlePragmaModuleBuild(Tok);
1642 }
1643};
1644
1645/// Handle the clang \#pragma module load extension.
1646struct PragmaModuleLoadHandler : public PragmaHandler {
1647 PragmaModuleLoadHandler() : PragmaHandler("load") {}
1648
1649 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1650 Token &Tok) override {
1651 SourceLocation Loc = Tok.getLocation();
1652
1653 // Read the module name.
1654 llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
1655 ModuleName;
1656 if (LexModuleName(PP, Tok, ModuleName))
1657 return;
1658
1659 if (Tok.isNot(tok::eod))
1660 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1661
1662 // Load the module, don't make it visible.
1663 PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
1664 /*IsIncludeDirective=*/false);
1665 }
1666};
1667
James Dennett18a6d792012-06-17 03:26:26 +00001668/// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001669/// macro on the top of the stack.
1670struct PragmaPushMacroHandler : public PragmaHandler {
1671 PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001672
Craig Topper9140dd22014-03-11 06:50:42 +00001673 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1674 Token &PushMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001675 PP.HandlePragmaPushMacro(PushMacroTok);
1676 }
1677};
1678
James Dennett18a6d792012-06-17 03:26:26 +00001679/// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001680/// macro to the value on the top of the stack.
1681struct PragmaPopMacroHandler : public PragmaHandler {
1682 PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001683
Craig Topper9140dd22014-03-11 06:50:42 +00001684 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1685 Token &PopMacroTok) override {
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001686 PP.HandlePragmaPopMacro(PopMacroTok);
1687 }
1688};
1689
Fangrui Song6907ce22018-07-30 19:24:48 +00001690/// PragmaARCCFCodeAuditedHandler -
James Dennett18a6d792012-06-17 03:26:26 +00001691/// \#pragma clang arc_cf_code_audited begin/end
John McCall32f5fe12011-09-30 05:12:12 +00001692struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1693 PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001694
Craig Topper9140dd22014-03-11 06:50:42 +00001695 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1696 Token &NameTok) override {
John McCall32f5fe12011-09-30 05:12:12 +00001697 SourceLocation Loc = NameTok.getLocation();
1698 bool IsBegin;
1699
1700 Token Tok;
1701
1702 // Lex the 'begin' or 'end'.
1703 PP.LexUnexpandedToken(Tok);
1704 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1705 if (BeginEnd && BeginEnd->isStr("begin")) {
1706 IsBegin = true;
1707 } else if (BeginEnd && BeginEnd->isStr("end")) {
1708 IsBegin = false;
1709 } else {
1710 PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1711 return;
1712 }
1713
1714 // Verify that this is followed by EOD.
1715 PP.LexUnexpandedToken(Tok);
1716 if (Tok.isNot(tok::eod))
1717 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1718
1719 // The start location of the active audit.
1720 SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1721
1722 // The start location we want after processing this.
1723 SourceLocation NewLoc;
1724
1725 if (IsBegin) {
1726 // Complain about attempts to re-enter an audit.
1727 if (BeginLoc.isValid()) {
1728 PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1729 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1730 }
1731 NewLoc = Loc;
1732 } else {
1733 // Complain about attempts to leave an audit that doesn't exist.
1734 if (!BeginLoc.isValid()) {
1735 PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1736 return;
1737 }
1738 NewLoc = SourceLocation();
1739 }
1740
1741 PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1742 }
1743};
1744
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001745/// PragmaAssumeNonNullHandler -
1746/// \#pragma clang assume_nonnull begin/end
1747struct PragmaAssumeNonNullHandler : public PragmaHandler {
1748 PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +00001749
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001750 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1751 Token &NameTok) override {
1752 SourceLocation Loc = NameTok.getLocation();
1753 bool IsBegin;
1754
1755 Token Tok;
1756
1757 // Lex the 'begin' or 'end'.
1758 PP.LexUnexpandedToken(Tok);
1759 const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1760 if (BeginEnd && BeginEnd->isStr("begin")) {
1761 IsBegin = true;
1762 } else if (BeginEnd && BeginEnd->isStr("end")) {
1763 IsBegin = false;
1764 } else {
1765 PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
1766 return;
1767 }
1768
1769 // Verify that this is followed by EOD.
1770 PP.LexUnexpandedToken(Tok);
1771 if (Tok.isNot(tok::eod))
1772 PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1773
1774 // The start location of the active audit.
1775 SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
1776
1777 // The start location we want after processing this.
1778 SourceLocation NewLoc;
Eli Friedman16fee082017-09-27 23:29:37 +00001779 PPCallbacks *Callbacks = PP.getPPCallbacks();
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001780
1781 if (IsBegin) {
1782 // Complain about attempts to re-enter an audit.
1783 if (BeginLoc.isValid()) {
1784 PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
1785 PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1786 }
1787 NewLoc = Loc;
Eli Friedman16fee082017-09-27 23:29:37 +00001788 if (Callbacks)
1789 Callbacks->PragmaAssumeNonNullBegin(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001790 } else {
1791 // Complain about attempts to leave an audit that doesn't exist.
1792 if (!BeginLoc.isValid()) {
1793 PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
1794 return;
1795 }
1796 NewLoc = SourceLocation();
Eli Friedman16fee082017-09-27 23:29:37 +00001797 if (Callbacks)
1798 Callbacks->PragmaAssumeNonNullEnd(NewLoc);
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001799 }
1800
1801 PP.setPragmaAssumeNonNullLoc(NewLoc);
1802 }
1803};
1804
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001805/// Handle "\#pragma region [...]"
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001806///
1807/// The syntax is
1808/// \code
1809/// #pragma region [optional name]
1810/// #pragma endregion [optional comment]
1811/// \endcode
1812///
1813/// \note This is
1814/// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1815/// pragma, just skipped by compiler.
1816struct PragmaRegionHandler : public PragmaHandler {
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001817 PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
Aaron Ballman406ea512012-11-30 19:52:30 +00001818
Craig Topper9140dd22014-03-11 06:50:42 +00001819 void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1820 Token &NameTok) override {
David Majnemer7aa8c2f2013-06-30 08:18:16 +00001821 // #pragma region: endregion matches can be verified
1822 // __pragma(region): no sense, but ignored by msvc
1823 // _Pragma is not valid for MSVC, but there isn't any point
1824 // to handle a _Pragma differently.
1825 }
1826};
Aaron Ballman406ea512012-11-30 19:52:30 +00001827
Eugene Zelenkocb96ac62017-12-08 22:39:26 +00001828} // namespace
Chris Lattnerb694ba72006-07-02 22:41:36 +00001829
1830/// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
James Dennett18a6d792012-06-17 03:26:26 +00001831/// \#pragma GCC poison/system_header/dependency and \#pragma once.
Chris Lattnerb694ba72006-07-02 22:41:36 +00001832void Preprocessor::RegisterBuiltinPragmas() {
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001833 AddPragmaHandler(new PragmaOnceHandler());
1834 AddPragmaHandler(new PragmaMarkHandler());
Chris Lattnerc0a585d2010-08-17 15:55:45 +00001835 AddPragmaHandler(new PragmaPushMacroHandler());
1836 AddPragmaHandler(new PragmaPopMacroHandler());
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001837 AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
Mike Stump11289f42009-09-09 15:08:12 +00001838
Chris Lattnerb61448d2009-05-12 18:21:11 +00001839 // #pragma GCC ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001840 AddPragmaHandler("GCC", new PragmaPoisonHandler());
1841 AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1842 AddPragmaHandler("GCC", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001843 AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
Andy Gibbs9c2ccd62013-04-17 16:16:16 +00001844 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1845 "GCC"));
1846 AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1847 "GCC"));
Chris Lattnerb61448d2009-05-12 18:21:11 +00001848 // #pragma clang ...
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001849 AddPragmaHandler("clang", new PragmaPoisonHandler());
1850 AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
Daniel Dunbarb8068c32010-07-28 15:40:33 +00001851 AddPragmaHandler("clang", new PragmaDebugHandler());
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +00001852 AddPragmaHandler("clang", new PragmaDependencyHandler());
Douglas Gregor3bde9b12011-06-22 19:41:48 +00001853 AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
John McCall32f5fe12011-09-30 05:12:12 +00001854 AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
Douglas Gregor2a20bd12015-06-19 18:25:57 +00001855 AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
Chris Lattnerb61448d2009-05-12 18:21:11 +00001856
Richard Smithc51c38b2017-04-29 00:34:47 +00001857 // #pragma clang module ...
1858 auto *ModuleHandler = new PragmaNamespace("module");
1859 AddPragmaHandler("clang", ModuleHandler);
1860 ModuleHandler->AddPragma(new PragmaModuleImportHandler());
Richard Smithd1386302017-05-04 00:29:54 +00001861 ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
1862 ModuleHandler->AddPragma(new PragmaModuleEndHandler());
Richard Smith5d2ed482017-06-09 19:22:32 +00001863 ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
1864 ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
Fangrui Song6907ce22018-07-30 19:24:48 +00001865
Matt Davis1edb9052018-01-27 00:25:29 +00001866 // Add region pragmas.
1867 AddPragmaHandler(new PragmaRegionHandler("region"));
1868 AddPragmaHandler(new PragmaRegionHandler("endregion"));
Richard Smithc51c38b2017-04-29 00:34:47 +00001869
Chris Lattner2ff698d2009-01-16 08:21:25 +00001870 // MS extensions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001871 if (LangOpts.MicrosoftExt) {
Reid Kleckner881dff32013-09-13 22:00:30 +00001872 AddPragmaHandler(new PragmaWarningHandler());
Reid Kleckner0f56b222019-03-14 18:12:17 +00001873 AddPragmaHandler(new PragmaExecCharsetHandler());
Aaron Ballman611306e2012-03-02 22:51:54 +00001874 AddPragmaHandler(new PragmaIncludeAliasHandler());
Mike Rice58df1af2018-09-11 17:10:44 +00001875 AddPragmaHandler(new PragmaHdrstopHandler());
Chris Lattner30c924b2010-06-26 17:11:39 +00001876 }
John Brawn8e62db32016-04-04 14:22:58 +00001877
1878 // Pragmas added by plugins
1879 for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
1880 ie = PragmaHandlerRegistry::end();
1881 it != ie; ++it) {
1882 AddPragmaHandler(it->instantiate().release());
1883 }
Chris Lattnerb694ba72006-07-02 22:41:36 +00001884}
Lubos Lunak576a0412014-05-01 12:54:03 +00001885
1886/// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1887/// warn about those pragmas being unknown.
1888void Preprocessor::IgnorePragmas() {
1889 AddPragmaHandler(new EmptyPragmaHandler());
1890 // Also ignore all pragmas in all namespaces created
1891 // in Preprocessor::RegisterBuiltinPragmas().
1892 AddPragmaHandler("GCC", new EmptyPragmaHandler());
1893 AddPragmaHandler("clang", new EmptyPragmaHandler());
Lubos Lunak576a0412014-05-01 12:54:03 +00001894}