1 //===--- Pragma.cpp - Pragma registration and handling --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the PragmaHandler/PragmaTable interfaces and implements
11 // pragma related methods of the Preprocessor class.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Lex/Pragma.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/MacroInfo.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/CrashRecoveryContext.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include <algorithm>
28 using namespace clang;
29 
30 #include "llvm/Support/raw_ostream.h"
31 
32 // Out-of-line destructor to provide a home for the class.
33 PragmaHandler::~PragmaHandler() {
34 }
35 
36 //===----------------------------------------------------------------------===//
37 // EmptyPragmaHandler Implementation.
38 //===----------------------------------------------------------------------===//
39 
40 EmptyPragmaHandler::EmptyPragmaHandler() {}
41 
42 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
43                                       PragmaIntroducerKind Introducer,
44                                       Token &FirstToken) {}
45 
46 //===----------------------------------------------------------------------===//
47 // PragmaNamespace Implementation.
48 //===----------------------------------------------------------------------===//
49 
50 PragmaNamespace::~PragmaNamespace() {
51   llvm::DeleteContainerSeconds(Handlers);
52 }
53 
54 /// FindHandler - Check to see if there is already a handler for the
55 /// specified name.  If not, return the handler for the null identifier if it
56 /// exists, otherwise return null.  If IgnoreNull is true (the default) then
57 /// the null handler isn't returned on failure to match.
58 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
59                                             bool IgnoreNull) const {
60   if (PragmaHandler *Handler = Handlers.lookup(Name))
61     return Handler;
62   return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
63 }
64 
65 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
66   assert(!Handlers.lookup(Handler->getName()) &&
67          "A handler with this name is already registered in this namespace");
68   llvm::StringMapEntry<PragmaHandler *> &Entry =
69     Handlers.GetOrCreateValue(Handler->getName());
70   Entry.setValue(Handler);
71 }
72 
73 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
74   assert(Handlers.lookup(Handler->getName()) &&
75          "Handler not registered in this namespace");
76   Handlers.erase(Handler->getName());
77 }
78 
79 void PragmaNamespace::HandlePragma(Preprocessor &PP,
80                                    PragmaIntroducerKind Introducer,
81                                    Token &Tok) {
82   // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
83   // expand it, the user can have a STDC #define, that should not affect this.
84   PP.LexUnexpandedToken(Tok);
85 
86   // Get the handler for this token.  If there is no handler, ignore the pragma.
87   PragmaHandler *Handler
88     = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
89                                           : StringRef(),
90                   /*IgnoreNull=*/false);
91   if (!Handler) {
92     PP.Diag(Tok, diag::warn_pragma_ignored);
93     return;
94   }
95 
96   // Otherwise, pass it down.
97   Handler->HandlePragma(PP, Introducer, Tok);
98 }
99 
100 //===----------------------------------------------------------------------===//
101 // Preprocessor Pragma Directive Handling.
102 //===----------------------------------------------------------------------===//
103 
104 /// HandlePragmaDirective - The "\#pragma" directive has been parsed.  Lex the
105 /// rest of the pragma, passing it to the registered pragma handlers.
106 void Preprocessor::HandlePragmaDirective(SourceLocation IntroducerLoc,
107                                          PragmaIntroducerKind Introducer) {
108   if (Callbacks)
109     Callbacks->PragmaDirective(IntroducerLoc, Introducer);
110 
111   if (!PragmasEnabled)
112     return;
113 
114   ++NumPragma;
115 
116   // Invoke the first level of pragma handlers which reads the namespace id.
117   Token Tok;
118   PragmaHandlers->HandlePragma(*this, Introducer, Tok);
119 
120   // If the pragma handler didn't read the rest of the line, consume it now.
121   if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
122    || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
123     DiscardUntilEndOfDirective();
124 }
125 
126 namespace {
127 /// \brief Helper class for \see Preprocessor::Handle_Pragma.
128 class LexingFor_PragmaRAII {
129   Preprocessor &PP;
130   bool InMacroArgPreExpansion;
131   bool Failed;
132   Token &OutTok;
133   Token PragmaTok;
134 
135 public:
136   LexingFor_PragmaRAII(Preprocessor &PP, bool InMacroArgPreExpansion,
137                        Token &Tok)
138     : PP(PP), InMacroArgPreExpansion(InMacroArgPreExpansion),
139       Failed(false), OutTok(Tok) {
140     if (InMacroArgPreExpansion) {
141       PragmaTok = OutTok;
142       PP.EnableBacktrackAtThisPos();
143     }
144   }
145 
146   ~LexingFor_PragmaRAII() {
147     if (InMacroArgPreExpansion) {
148       if (Failed) {
149         PP.CommitBacktrackedTokens();
150       } else {
151         PP.Backtrack();
152         OutTok = PragmaTok;
153       }
154     }
155   }
156 
157   void failed() {
158     Failed = true;
159   }
160 };
161 }
162 
163 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
164 /// return the first token after the directive.  The _Pragma token has just
165 /// been read into 'Tok'.
166 void Preprocessor::Handle_Pragma(Token &Tok) {
167 
168   // This works differently if we are pre-expanding a macro argument.
169   // In that case we don't actually "activate" the pragma now, we only lex it
170   // until we are sure it is lexically correct and then we backtrack so that
171   // we activate the pragma whenever we encounter the tokens again in the token
172   // stream. This ensures that we will activate it in the correct location
173   // or that we will ignore it if it never enters the token stream, e.g:
174   //
175   //     #define EMPTY(x)
176   //     #define INACTIVE(x) EMPTY(x)
177   //     INACTIVE(_Pragma("clang diagnostic ignored \"-Wconversion\""))
178 
179   LexingFor_PragmaRAII _PragmaLexing(*this, InMacroArgPreExpansion, Tok);
180 
181   // Remember the pragma token location.
182   SourceLocation PragmaLoc = Tok.getLocation();
183 
184   // Read the '('.
185   Lex(Tok);
186   if (Tok.isNot(tok::l_paren)) {
187     Diag(PragmaLoc, diag::err__Pragma_malformed);
188     return _PragmaLexing.failed();
189   }
190 
191   // Read the '"..."'.
192   Lex(Tok);
193   if (!tok::isStringLiteral(Tok.getKind())) {
194     Diag(PragmaLoc, diag::err__Pragma_malformed);
195     // Skip this token, and the ')', if present.
196     if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
197       Lex(Tok);
198     if (Tok.is(tok::r_paren))
199       Lex(Tok);
200     return _PragmaLexing.failed();
201   }
202 
203   if (Tok.hasUDSuffix()) {
204     Diag(Tok, diag::err_invalid_string_udl);
205     // Skip this token, and the ')', if present.
206     Lex(Tok);
207     if (Tok.is(tok::r_paren))
208       Lex(Tok);
209     return _PragmaLexing.failed();
210   }
211 
212   // Remember the string.
213   Token StrTok = Tok;
214 
215   // Read the ')'.
216   Lex(Tok);
217   if (Tok.isNot(tok::r_paren)) {
218     Diag(PragmaLoc, diag::err__Pragma_malformed);
219     return _PragmaLexing.failed();
220   }
221 
222   if (InMacroArgPreExpansion)
223     return;
224 
225   SourceLocation RParenLoc = Tok.getLocation();
226   std::string StrVal = getSpelling(StrTok);
227 
228   // The _Pragma is lexically sound.  Destringize according to C11 6.10.9.1:
229   // "The string literal is destringized by deleting any encoding prefix,
230   // deleting the leading and trailing double-quotes, replacing each escape
231   // sequence \" by a double-quote, and replacing each escape sequence \\ by a
232   // single backslash."
233   if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
234       (StrVal[0] == 'u' && StrVal[1] != '8'))
235     StrVal.erase(StrVal.begin());
236   else if (StrVal[0] == 'u')
237     StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
238 
239   if (StrVal[0] == 'R') {
240     // FIXME: C++11 does not specify how to handle raw-string-literals here.
241     // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
242     assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
243            "Invalid raw string token!");
244 
245     // Measure the length of the d-char-sequence.
246     unsigned NumDChars = 0;
247     while (StrVal[2 + NumDChars] != '(') {
248       assert(NumDChars < (StrVal.size() - 5) / 2 &&
249              "Invalid raw string token!");
250       ++NumDChars;
251     }
252     assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
253 
254     // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
255     // parens below.
256     StrVal.erase(0, 2 + NumDChars);
257     StrVal.erase(StrVal.size() - 1 - NumDChars);
258   } else {
259     assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
260            "Invalid string token!");
261 
262     // Remove escaped quotes and escapes.
263     unsigned ResultPos = 1;
264     for (unsigned i = 1, e = StrVal.size() - 1; i != e; ++i) {
265       // Skip escapes.  \\ -> '\' and \" -> '"'.
266       if (StrVal[i] == '\\' && i + 1 < e &&
267           (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
268         ++i;
269       StrVal[ResultPos++] = StrVal[i];
270     }
271     StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
272   }
273 
274   // Remove the front quote, replacing it with a space, so that the pragma
275   // contents appear to have a space before them.
276   StrVal[0] = ' ';
277 
278   // Replace the terminating quote with a \n.
279   StrVal[StrVal.size()-1] = '\n';
280 
281   // Plop the string (including the newline and trailing null) into a buffer
282   // where we can lex it.
283   Token TmpTok;
284   TmpTok.startToken();
285   CreateString(StrVal, TmpTok);
286   SourceLocation TokLoc = TmpTok.getLocation();
287 
288   // Make and enter a lexer object so that we lex and expand the tokens just
289   // like any others.
290   Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
291                                         StrVal.size(), *this);
292 
293   EnterSourceFileWithLexer(TL, nullptr);
294 
295   // With everything set up, lex this as a #pragma directive.
296   HandlePragmaDirective(PragmaLoc, PIK__Pragma);
297 
298   // Finally, return whatever came after the pragma directive.
299   return Lex(Tok);
300 }
301 
302 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
303 /// is not enclosed within a string literal.
304 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
305   // Remember the pragma token location.
306   SourceLocation PragmaLoc = Tok.getLocation();
307 
308   // Read the '('.
309   Lex(Tok);
310   if (Tok.isNot(tok::l_paren)) {
311     Diag(PragmaLoc, diag::err__Pragma_malformed);
312     return;
313   }
314 
315   // Get the tokens enclosed within the __pragma(), as well as the final ')'.
316   SmallVector<Token, 32> PragmaToks;
317   int NumParens = 0;
318   Lex(Tok);
319   while (Tok.isNot(tok::eof)) {
320     PragmaToks.push_back(Tok);
321     if (Tok.is(tok::l_paren))
322       NumParens++;
323     else if (Tok.is(tok::r_paren) && NumParens-- == 0)
324       break;
325     Lex(Tok);
326   }
327 
328   if (Tok.is(tok::eof)) {
329     Diag(PragmaLoc, diag::err_unterminated___pragma);
330     return;
331   }
332 
333   PragmaToks.front().setFlag(Token::LeadingSpace);
334 
335   // Replace the ')' with an EOD to mark the end of the pragma.
336   PragmaToks.back().setKind(tok::eod);
337 
338   Token *TokArray = new Token[PragmaToks.size()];
339   std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
340 
341   // Push the tokens onto the stack.
342   EnterTokenStream(TokArray, PragmaToks.size(), true, true);
343 
344   // With everything set up, lex this as a #pragma directive.
345   HandlePragmaDirective(PragmaLoc, PIK___pragma);
346 
347   // Finally, return whatever came after the pragma directive.
348   return Lex(Tok);
349 }
350 
351 /// HandlePragmaOnce - Handle \#pragma once.  OnceTok is the 'once'.
352 ///
353 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
354   if (isInPrimaryFile()) {
355     Diag(OnceTok, diag::pp_pragma_once_in_main_file);
356     return;
357   }
358 
359   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
360   // Mark the file as a once-only file now.
361   HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
362 }
363 
364 void Preprocessor::HandlePragmaMark() {
365   assert(CurPPLexer && "No current lexer?");
366   if (CurLexer)
367     CurLexer->ReadToEndOfLine();
368   else
369     CurPTHLexer->DiscardToEndOfLine();
370 }
371 
372 
373 /// HandlePragmaPoison - Handle \#pragma GCC poison.  PoisonTok is the 'poison'.
374 ///
375 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
376   Token Tok;
377 
378   while (1) {
379     // Read the next token to poison.  While doing this, pretend that we are
380     // skipping while reading the identifier to poison.
381     // This avoids errors on code like:
382     //   #pragma GCC poison X
383     //   #pragma GCC poison X
384     if (CurPPLexer) CurPPLexer->LexingRawMode = true;
385     LexUnexpandedToken(Tok);
386     if (CurPPLexer) CurPPLexer->LexingRawMode = false;
387 
388     // If we reached the end of line, we're done.
389     if (Tok.is(tok::eod)) return;
390 
391     // Can only poison identifiers.
392     if (Tok.isNot(tok::raw_identifier)) {
393       Diag(Tok, diag::err_pp_invalid_poison);
394       return;
395     }
396 
397     // Look up the identifier info for the token.  We disabled identifier lookup
398     // by saying we're skipping contents, so we need to do this manually.
399     IdentifierInfo *II = LookUpIdentifierInfo(Tok);
400 
401     // Already poisoned.
402     if (II->isPoisoned()) continue;
403 
404     // If this is a macro identifier, emit a warning.
405     if (II->hasMacroDefinition())
406       Diag(Tok, diag::pp_poisoning_existing_macro);
407 
408     // Finally, poison it!
409     II->setIsPoisoned();
410     if (II->isFromAST())
411       II->setChangedSinceDeserialization();
412   }
413 }
414 
415 /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header.  We know
416 /// that the whole directive has been parsed.
417 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
418   if (isInPrimaryFile()) {
419     Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
420     return;
421   }
422 
423   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
424   PreprocessorLexer *TheLexer = getCurrentFileLexer();
425 
426   // Mark the file as a system header.
427   HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
428 
429 
430   PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
431   if (PLoc.isInvalid())
432     return;
433 
434   unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
435 
436   // Notify the client, if desired, that we are in a new source file.
437   if (Callbacks)
438     Callbacks->FileChanged(SysHeaderTok.getLocation(),
439                            PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
440 
441   // Emit a line marker.  This will change any source locations from this point
442   // forward to realize they are in a system header.
443   // Create a line note with this information.
444   SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine()+1,
445                         FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
446                         /*IsSystem=*/true, /*IsExternC=*/false);
447 }
448 
449 /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
450 ///
451 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
452   Token FilenameTok;
453   CurPPLexer->LexIncludeFilename(FilenameTok);
454 
455   // If the token kind is EOD, the error has already been diagnosed.
456   if (FilenameTok.is(tok::eod))
457     return;
458 
459   // Reserve a buffer to get the spelling.
460   SmallString<128> FilenameBuffer;
461   bool Invalid = false;
462   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
463   if (Invalid)
464     return;
465 
466   bool isAngled =
467     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
468   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
469   // error.
470   if (Filename.empty())
471     return;
472 
473   // Search include directories for this file.
474   const DirectoryLookup *CurDir;
475   const FileEntry *File = LookupFile(FilenameTok.getLocation(), Filename,
476                                      isAngled, nullptr, CurDir, nullptr,
477                                      nullptr, nullptr);
478   if (!File) {
479     if (!SuppressIncludeNotFoundError)
480       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
481     return;
482   }
483 
484   const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
485 
486   // If this file is older than the file it depends on, emit a diagnostic.
487   if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
488     // Lex tokens at the end of the message and include them in the message.
489     std::string Message;
490     Lex(DependencyTok);
491     while (DependencyTok.isNot(tok::eod)) {
492       Message += getSpelling(DependencyTok) + " ";
493       Lex(DependencyTok);
494     }
495 
496     // Remove the trailing ' ' if present.
497     if (!Message.empty())
498       Message.erase(Message.end()-1);
499     Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
500   }
501 }
502 
503 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
504 /// Return the IdentifierInfo* associated with the macro to push or pop.
505 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
506   // Remember the pragma token location.
507   Token PragmaTok = Tok;
508 
509   // Read the '('.
510   Lex(Tok);
511   if (Tok.isNot(tok::l_paren)) {
512     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
513       << getSpelling(PragmaTok);
514     return nullptr;
515   }
516 
517   // Read the macro name string.
518   Lex(Tok);
519   if (Tok.isNot(tok::string_literal)) {
520     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
521       << getSpelling(PragmaTok);
522     return nullptr;
523   }
524 
525   if (Tok.hasUDSuffix()) {
526     Diag(Tok, diag::err_invalid_string_udl);
527     return nullptr;
528   }
529 
530   // Remember the macro string.
531   std::string StrVal = getSpelling(Tok);
532 
533   // Read the ')'.
534   Lex(Tok);
535   if (Tok.isNot(tok::r_paren)) {
536     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
537       << getSpelling(PragmaTok);
538     return nullptr;
539   }
540 
541   assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
542          "Invalid string token!");
543 
544   // Create a Token from the string.
545   Token MacroTok;
546   MacroTok.startToken();
547   MacroTok.setKind(tok::raw_identifier);
548   CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
549 
550   // Get the IdentifierInfo of MacroToPushTok.
551   return LookUpIdentifierInfo(MacroTok);
552 }
553 
554 /// \brief Handle \#pragma push_macro.
555 ///
556 /// The syntax is:
557 /// \code
558 ///   #pragma push_macro("macro")
559 /// \endcode
560 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
561   // Parse the pragma directive and get the macro IdentifierInfo*.
562   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
563   if (!IdentInfo) return;
564 
565   // Get the MacroInfo associated with IdentInfo.
566   MacroInfo *MI = getMacroInfo(IdentInfo);
567 
568   if (MI) {
569     // Allow the original MacroInfo to be redefined later.
570     MI->setIsAllowRedefinitionsWithoutWarning(true);
571   }
572 
573   // Push the cloned MacroInfo so we can retrieve it later.
574   PragmaPushMacroInfo[IdentInfo].push_back(MI);
575 }
576 
577 /// \brief Handle \#pragma pop_macro.
578 ///
579 /// The syntax is:
580 /// \code
581 ///   #pragma pop_macro("macro")
582 /// \endcode
583 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
584   SourceLocation MessageLoc = PopMacroTok.getLocation();
585 
586   // Parse the pragma directive and get the macro IdentifierInfo*.
587   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
588   if (!IdentInfo) return;
589 
590   // Find the vector<MacroInfo*> associated with the macro.
591   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
592     PragmaPushMacroInfo.find(IdentInfo);
593   if (iter != PragmaPushMacroInfo.end()) {
594     // Forget the MacroInfo currently associated with IdentInfo.
595     if (MacroDirective *CurrentMD = getMacroDirective(IdentInfo)) {
596       MacroInfo *MI = CurrentMD->getMacroInfo();
597       if (MI->isWarnIfUnused())
598         WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
599       appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
600     }
601 
602     // Get the MacroInfo we want to reinstall.
603     MacroInfo *MacroToReInstall = iter->second.back();
604 
605     if (MacroToReInstall) {
606       // Reinstall the previously pushed macro.
607       appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc,
608                               /*isImported=*/false, /*Overrides*/None);
609     }
610 
611     // Pop PragmaPushMacroInfo stack.
612     iter->second.pop_back();
613     if (iter->second.size() == 0)
614       PragmaPushMacroInfo.erase(iter);
615   } else {
616     Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
617       << IdentInfo->getName();
618   }
619 }
620 
621 void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
622   // We will either get a quoted filename or a bracketed filename, and we
623   // have to track which we got.  The first filename is the source name,
624   // and the second name is the mapped filename.  If the first is quoted,
625   // the second must be as well (cannot mix and match quotes and brackets).
626 
627   // Get the open paren
628   Lex(Tok);
629   if (Tok.isNot(tok::l_paren)) {
630     Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
631     return;
632   }
633 
634   // We expect either a quoted string literal, or a bracketed name
635   Token SourceFilenameTok;
636   CurPPLexer->LexIncludeFilename(SourceFilenameTok);
637   if (SourceFilenameTok.is(tok::eod)) {
638     // The diagnostic has already been handled
639     return;
640   }
641 
642   StringRef SourceFileName;
643   SmallString<128> FileNameBuffer;
644   if (SourceFilenameTok.is(tok::string_literal) ||
645       SourceFilenameTok.is(tok::angle_string_literal)) {
646     SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
647   } else if (SourceFilenameTok.is(tok::less)) {
648     // This could be a path instead of just a name
649     FileNameBuffer.push_back('<');
650     SourceLocation End;
651     if (ConcatenateIncludeName(FileNameBuffer, End))
652       return; // Diagnostic already emitted
653     SourceFileName = FileNameBuffer.str();
654   } else {
655     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
656     return;
657   }
658   FileNameBuffer.clear();
659 
660   // Now we expect a comma, followed by another include name
661   Lex(Tok);
662   if (Tok.isNot(tok::comma)) {
663     Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
664     return;
665   }
666 
667   Token ReplaceFilenameTok;
668   CurPPLexer->LexIncludeFilename(ReplaceFilenameTok);
669   if (ReplaceFilenameTok.is(tok::eod)) {
670     // The diagnostic has already been handled
671     return;
672   }
673 
674   StringRef ReplaceFileName;
675   if (ReplaceFilenameTok.is(tok::string_literal) ||
676       ReplaceFilenameTok.is(tok::angle_string_literal)) {
677     ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
678   } else if (ReplaceFilenameTok.is(tok::less)) {
679     // This could be a path instead of just a name
680     FileNameBuffer.push_back('<');
681     SourceLocation End;
682     if (ConcatenateIncludeName(FileNameBuffer, End))
683       return; // Diagnostic already emitted
684     ReplaceFileName = FileNameBuffer.str();
685   } else {
686     Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
687     return;
688   }
689 
690   // Finally, we expect the closing paren
691   Lex(Tok);
692   if (Tok.isNot(tok::r_paren)) {
693     Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
694     return;
695   }
696 
697   // Now that we have the source and target filenames, we need to make sure
698   // they're both of the same type (angled vs non-angled)
699   StringRef OriginalSource = SourceFileName;
700 
701   bool SourceIsAngled =
702     GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
703                                 SourceFileName);
704   bool ReplaceIsAngled =
705     GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
706                                 ReplaceFileName);
707   if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
708       (SourceIsAngled != ReplaceIsAngled)) {
709     unsigned int DiagID;
710     if (SourceIsAngled)
711       DiagID = diag::warn_pragma_include_alias_mismatch_angle;
712     else
713       DiagID = diag::warn_pragma_include_alias_mismatch_quote;
714 
715     Diag(SourceFilenameTok.getLocation(), DiagID)
716       << SourceFileName
717       << ReplaceFileName;
718 
719     return;
720   }
721 
722   // Now we can let the include handler know about this mapping
723   getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
724 }
725 
726 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
727 /// If 'Namespace' is non-null, then it is a token required to exist on the
728 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
729 void Preprocessor::AddPragmaHandler(StringRef Namespace,
730                                     PragmaHandler *Handler) {
731   PragmaNamespace *InsertNS = PragmaHandlers;
732 
733   // If this is specified to be in a namespace, step down into it.
734   if (!Namespace.empty()) {
735     // If there is already a pragma handler with the name of this namespace,
736     // we either have an error (directive with the same name as a namespace) or
737     // we already have the namespace to insert into.
738     if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
739       InsertNS = Existing->getIfNamespace();
740       assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
741              " handler with the same name!");
742     } else {
743       // Otherwise, this namespace doesn't exist yet, create and insert the
744       // handler for it.
745       InsertNS = new PragmaNamespace(Namespace);
746       PragmaHandlers->AddPragma(InsertNS);
747     }
748   }
749 
750   // Check to make sure we don't already have a pragma for this identifier.
751   assert(!InsertNS->FindHandler(Handler->getName()) &&
752          "Pragma handler already exists for this identifier!");
753   InsertNS->AddPragma(Handler);
754 }
755 
756 /// RemovePragmaHandler - Remove the specific pragma handler from the
757 /// preprocessor. If \arg Namespace is non-null, then it should be the
758 /// namespace that \arg Handler was added to. It is an error to remove
759 /// a handler that has not been registered.
760 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
761                                        PragmaHandler *Handler) {
762   PragmaNamespace *NS = PragmaHandlers;
763 
764   // If this is specified to be in a namespace, step down into it.
765   if (!Namespace.empty()) {
766     PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
767     assert(Existing && "Namespace containing handler does not exist!");
768 
769     NS = Existing->getIfNamespace();
770     assert(NS && "Invalid namespace, registered as a regular pragma handler!");
771   }
772 
773   NS->RemovePragmaHandler(Handler);
774 
775   // If this is a non-default namespace and it is now empty, remove
776   // it.
777   if (NS != PragmaHandlers && NS->IsEmpty()) {
778     PragmaHandlers->RemovePragmaHandler(NS);
779     delete NS;
780   }
781 }
782 
783 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
784   Token Tok;
785   LexUnexpandedToken(Tok);
786 
787   if (Tok.isNot(tok::identifier)) {
788     Diag(Tok, diag::ext_on_off_switch_syntax);
789     return true;
790   }
791   IdentifierInfo *II = Tok.getIdentifierInfo();
792   if (II->isStr("ON"))
793     Result = tok::OOS_ON;
794   else if (II->isStr("OFF"))
795     Result = tok::OOS_OFF;
796   else if (II->isStr("DEFAULT"))
797     Result = tok::OOS_DEFAULT;
798   else {
799     Diag(Tok, diag::ext_on_off_switch_syntax);
800     return true;
801   }
802 
803   // Verify that this is followed by EOD.
804   LexUnexpandedToken(Tok);
805   if (Tok.isNot(tok::eod))
806     Diag(Tok, diag::ext_pragma_syntax_eod);
807   return false;
808 }
809 
810 namespace {
811 /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
812 struct PragmaOnceHandler : public PragmaHandler {
813   PragmaOnceHandler() : PragmaHandler("once") {}
814   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
815                     Token &OnceTok) override {
816     PP.CheckEndOfDirective("pragma once");
817     PP.HandlePragmaOnce(OnceTok);
818   }
819 };
820 
821 /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
822 /// rest of the line is not lexed.
823 struct PragmaMarkHandler : public PragmaHandler {
824   PragmaMarkHandler() : PragmaHandler("mark") {}
825   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
826                     Token &MarkTok) override {
827     PP.HandlePragmaMark();
828   }
829 };
830 
831 /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
832 struct PragmaPoisonHandler : public PragmaHandler {
833   PragmaPoisonHandler() : PragmaHandler("poison") {}
834   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
835                     Token &PoisonTok) override {
836     PP.HandlePragmaPoison(PoisonTok);
837   }
838 };
839 
840 /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
841 /// as a system header, which silences warnings in it.
842 struct PragmaSystemHeaderHandler : public PragmaHandler {
843   PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
844   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
845                     Token &SHToken) override {
846     PP.HandlePragmaSystemHeader(SHToken);
847     PP.CheckEndOfDirective("pragma");
848   }
849 };
850 struct PragmaDependencyHandler : public PragmaHandler {
851   PragmaDependencyHandler() : PragmaHandler("dependency") {}
852   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
853                     Token &DepToken) override {
854     PP.HandlePragmaDependency(DepToken);
855   }
856 };
857 
858 struct PragmaDebugHandler : public PragmaHandler {
859   PragmaDebugHandler() : PragmaHandler("__debug") {}
860   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
861                     Token &DepToken) override {
862     Token Tok;
863     PP.LexUnexpandedToken(Tok);
864     if (Tok.isNot(tok::identifier)) {
865       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
866       return;
867     }
868     IdentifierInfo *II = Tok.getIdentifierInfo();
869 
870     if (II->isStr("assert")) {
871       llvm_unreachable("This is an assertion!");
872     } else if (II->isStr("crash")) {
873       LLVM_BUILTIN_TRAP;
874     } else if (II->isStr("parser_crash")) {
875       Token Crasher;
876       Crasher.setKind(tok::annot_pragma_parser_crash);
877       PP.EnterToken(Crasher);
878     } else if (II->isStr("llvm_fatal_error")) {
879       llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
880     } else if (II->isStr("llvm_unreachable")) {
881       llvm_unreachable("#pragma clang __debug llvm_unreachable");
882     } else if (II->isStr("overflow_stack")) {
883       DebugOverflowStack();
884     } else if (II->isStr("handle_crash")) {
885       llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
886       if (CRC)
887         CRC->HandleCrash();
888     } else if (II->isStr("captured")) {
889       HandleCaptured(PP);
890     } else {
891       PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
892         << II->getName();
893     }
894 
895     PPCallbacks *Callbacks = PP.getPPCallbacks();
896     if (Callbacks)
897       Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
898   }
899 
900   void HandleCaptured(Preprocessor &PP) {
901     // Skip if emitting preprocessed output.
902     if (PP.isPreprocessedOutput())
903       return;
904 
905     Token Tok;
906     PP.LexUnexpandedToken(Tok);
907 
908     if (Tok.isNot(tok::eod)) {
909       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
910         << "pragma clang __debug captured";
911       return;
912     }
913 
914     SourceLocation NameLoc = Tok.getLocation();
915     Token *Toks = PP.getPreprocessorAllocator().Allocate<Token>(1);
916     Toks->startToken();
917     Toks->setKind(tok::annot_pragma_captured);
918     Toks->setLocation(NameLoc);
919 
920     PP.EnterTokenStream(Toks, 1, /*DisableMacroExpansion=*/true,
921                         /*OwnsTokens=*/false);
922   }
923 
924 // Disable MSVC warning about runtime stack overflow.
925 #ifdef _MSC_VER
926     #pragma warning(disable : 4717)
927 #endif
928   static void DebugOverflowStack() {
929     void (*volatile Self)() = DebugOverflowStack;
930     Self();
931   }
932 #ifdef _MSC_VER
933     #pragma warning(default : 4717)
934 #endif
935 
936 };
937 
938 /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
939 struct PragmaDiagnosticHandler : public PragmaHandler {
940 private:
941   const char *Namespace;
942 public:
943   explicit PragmaDiagnosticHandler(const char *NS) :
944     PragmaHandler("diagnostic"), Namespace(NS) {}
945   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
946                     Token &DiagToken) override {
947     SourceLocation DiagLoc = DiagToken.getLocation();
948     Token Tok;
949     PP.LexUnexpandedToken(Tok);
950     if (Tok.isNot(tok::identifier)) {
951       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
952       return;
953     }
954     IdentifierInfo *II = Tok.getIdentifierInfo();
955     PPCallbacks *Callbacks = PP.getPPCallbacks();
956 
957     if (II->isStr("pop")) {
958       if (!PP.getDiagnostics().popMappings(DiagLoc))
959         PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
960       else if (Callbacks)
961         Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
962       return;
963     } else if (II->isStr("push")) {
964       PP.getDiagnostics().pushMappings(DiagLoc);
965       if (Callbacks)
966         Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
967       return;
968     }
969 
970     diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
971                             .Case("ignored", diag::Severity::Ignored)
972                             .Case("warning", diag::Severity::Warning)
973                             .Case("error", diag::Severity::Error)
974                             .Case("fatal", diag::Severity::Fatal)
975                             .Default(diag::Severity());
976 
977     if (SV == diag::Severity()) {
978       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
979       return;
980     }
981 
982     PP.LexUnexpandedToken(Tok);
983     SourceLocation StringLoc = Tok.getLocation();
984 
985     std::string WarningName;
986     if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
987                                    /*MacroExpansion=*/false))
988       return;
989 
990     if (Tok.isNot(tok::eod)) {
991       PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
992       return;
993     }
994 
995     if (WarningName.size() < 3 || WarningName[0] != '-' ||
996         (WarningName[1] != 'W' && WarningName[1] != 'R')) {
997       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
998       return;
999     }
1000 
1001     if (PP.getDiagnostics().setSeverityForGroup(
1002             WarningName[1] == 'W' ? diag::Flavor::WarningOrError
1003                                   : diag::Flavor::Remark,
1004             WarningName.substr(2), SV, DiagLoc))
1005       PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
1006         << WarningName;
1007     else if (Callbacks)
1008       Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
1009   }
1010 };
1011 
1012 /// "\#pragma warning(...)".  MSVC's diagnostics do not map cleanly to clang's
1013 /// diagnostics, so we don't really implement this pragma.  We parse it and
1014 /// ignore it to avoid -Wunknown-pragma warnings.
1015 struct PragmaWarningHandler : public PragmaHandler {
1016   PragmaWarningHandler() : PragmaHandler("warning") {}
1017 
1018   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1019                     Token &Tok) override {
1020     // Parse things like:
1021     // warning(push, 1)
1022     // warning(pop)
1023     // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
1024     SourceLocation DiagLoc = Tok.getLocation();
1025     PPCallbacks *Callbacks = PP.getPPCallbacks();
1026 
1027     PP.Lex(Tok);
1028     if (Tok.isNot(tok::l_paren)) {
1029       PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
1030       return;
1031     }
1032 
1033     PP.Lex(Tok);
1034     IdentifierInfo *II = Tok.getIdentifierInfo();
1035     if (!II) {
1036       PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1037       return;
1038     }
1039 
1040     if (II->isStr("push")) {
1041       // #pragma warning( push[ ,n ] )
1042       int Level = -1;
1043       PP.Lex(Tok);
1044       if (Tok.is(tok::comma)) {
1045         PP.Lex(Tok);
1046         uint64_t Value;
1047         if (Tok.is(tok::numeric_constant) &&
1048             PP.parseSimpleIntegerLiteral(Tok, Value))
1049           Level = int(Value);
1050         if (Level < 0 || Level > 4) {
1051           PP.Diag(Tok, diag::warn_pragma_warning_push_level);
1052           return;
1053         }
1054       }
1055       if (Callbacks)
1056         Callbacks->PragmaWarningPush(DiagLoc, Level);
1057     } else if (II->isStr("pop")) {
1058       // #pragma warning( pop )
1059       PP.Lex(Tok);
1060       if (Callbacks)
1061         Callbacks->PragmaWarningPop(DiagLoc);
1062     } else {
1063       // #pragma warning( warning-specifier : warning-number-list
1064       //                  [; warning-specifier : warning-number-list...] )
1065       while (true) {
1066         II = Tok.getIdentifierInfo();
1067         if (!II) {
1068           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1069           return;
1070         }
1071 
1072         // Figure out which warning specifier this is.
1073         StringRef Specifier = II->getName();
1074         bool SpecifierValid =
1075             llvm::StringSwitch<bool>(Specifier)
1076                 .Cases("1", "2", "3", "4", true)
1077                 .Cases("default", "disable", "error", "once", "suppress", true)
1078                 .Default(false);
1079         if (!SpecifierValid) {
1080           PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
1081           return;
1082         }
1083         PP.Lex(Tok);
1084         if (Tok.isNot(tok::colon)) {
1085           PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
1086           return;
1087         }
1088 
1089         // Collect the warning ids.
1090         SmallVector<int, 4> Ids;
1091         PP.Lex(Tok);
1092         while (Tok.is(tok::numeric_constant)) {
1093           uint64_t Value;
1094           if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
1095               Value > INT_MAX) {
1096             PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
1097             return;
1098           }
1099           Ids.push_back(int(Value));
1100         }
1101         if (Callbacks)
1102           Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
1103 
1104         // Parse the next specifier if there is a semicolon.
1105         if (Tok.isNot(tok::semi))
1106           break;
1107         PP.Lex(Tok);
1108       }
1109     }
1110 
1111     if (Tok.isNot(tok::r_paren)) {
1112       PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
1113       return;
1114     }
1115 
1116     PP.Lex(Tok);
1117     if (Tok.isNot(tok::eod))
1118       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
1119   }
1120 };
1121 
1122 /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
1123 struct PragmaIncludeAliasHandler : public PragmaHandler {
1124   PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
1125   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1126                     Token &IncludeAliasTok) override {
1127     PP.HandlePragmaIncludeAlias(IncludeAliasTok);
1128   }
1129 };
1130 
1131 /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
1132 /// extension.  The syntax is:
1133 /// \code
1134 ///   #pragma message(string)
1135 /// \endcode
1136 /// OR, in GCC mode:
1137 /// \code
1138 ///   #pragma message string
1139 /// \endcode
1140 /// string is a string, which is fully macro expanded, and permits string
1141 /// concatenation, embedded escape characters, etc... See MSDN for more details.
1142 /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
1143 /// form as \#pragma message.
1144 struct PragmaMessageHandler : public PragmaHandler {
1145 private:
1146   const PPCallbacks::PragmaMessageKind Kind;
1147   const StringRef Namespace;
1148 
1149   static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
1150                                 bool PragmaNameOnly = false) {
1151     switch (Kind) {
1152       case PPCallbacks::PMK_Message:
1153         return PragmaNameOnly ? "message" : "pragma message";
1154       case PPCallbacks::PMK_Warning:
1155         return PragmaNameOnly ? "warning" : "pragma warning";
1156       case PPCallbacks::PMK_Error:
1157         return PragmaNameOnly ? "error" : "pragma error";
1158     }
1159     llvm_unreachable("Unknown PragmaMessageKind!");
1160   }
1161 
1162 public:
1163   PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
1164                        StringRef Namespace = StringRef())
1165     : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind), Namespace(Namespace) {}
1166 
1167   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1168                     Token &Tok) override {
1169     SourceLocation MessageLoc = Tok.getLocation();
1170     PP.Lex(Tok);
1171     bool ExpectClosingParen = false;
1172     switch (Tok.getKind()) {
1173     case tok::l_paren:
1174       // We have a MSVC style pragma message.
1175       ExpectClosingParen = true;
1176       // Read the string.
1177       PP.Lex(Tok);
1178       break;
1179     case tok::string_literal:
1180       // We have a GCC style pragma message, and we just read the string.
1181       break;
1182     default:
1183       PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
1184       return;
1185     }
1186 
1187     std::string MessageString;
1188     if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
1189                                    /*MacroExpansion=*/true))
1190       return;
1191 
1192     if (ExpectClosingParen) {
1193       if (Tok.isNot(tok::r_paren)) {
1194         PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1195         return;
1196       }
1197       PP.Lex(Tok);  // eat the r_paren.
1198     }
1199 
1200     if (Tok.isNot(tok::eod)) {
1201       PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
1202       return;
1203     }
1204 
1205     // Output the message.
1206     PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
1207                           ? diag::err_pragma_message
1208                           : diag::warn_pragma_message) << MessageString;
1209 
1210     // If the pragma is lexically sound, notify any interested PPCallbacks.
1211     if (PPCallbacks *Callbacks = PP.getPPCallbacks())
1212       Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
1213   }
1214 };
1215 
1216 /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
1217 /// macro on the top of the stack.
1218 struct PragmaPushMacroHandler : public PragmaHandler {
1219   PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
1220   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1221                     Token &PushMacroTok) override {
1222     PP.HandlePragmaPushMacro(PushMacroTok);
1223   }
1224 };
1225 
1226 
1227 /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
1228 /// macro to the value on the top of the stack.
1229 struct PragmaPopMacroHandler : public PragmaHandler {
1230   PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
1231   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1232                     Token &PopMacroTok) override {
1233     PP.HandlePragmaPopMacro(PopMacroTok);
1234   }
1235 };
1236 
1237 // Pragma STDC implementations.
1238 
1239 /// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
1240 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
1241   PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
1242   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1243                     Token &Tok) override {
1244     tok::OnOffSwitch OOS;
1245     if (PP.LexOnOffSwitch(OOS))
1246      return;
1247     if (OOS == tok::OOS_ON)
1248       PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
1249   }
1250 };
1251 
1252 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
1253 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
1254   PragmaSTDC_CX_LIMITED_RANGEHandler()
1255     : PragmaHandler("CX_LIMITED_RANGE") {}
1256   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1257                     Token &Tok) override {
1258     tok::OnOffSwitch OOS;
1259     PP.LexOnOffSwitch(OOS);
1260   }
1261 };
1262 
1263 /// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
1264 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1265   PragmaSTDC_UnknownHandler() {}
1266   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1267                     Token &UnknownTok) override {
1268     // C99 6.10.6p2, unknown forms are not allowed.
1269     PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1270   }
1271 };
1272 
1273 /// PragmaARCCFCodeAuditedHandler -
1274 ///   \#pragma clang arc_cf_code_audited begin/end
1275 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1276   PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1277   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1278                     Token &NameTok) override {
1279     SourceLocation Loc = NameTok.getLocation();
1280     bool IsBegin;
1281 
1282     Token Tok;
1283 
1284     // Lex the 'begin' or 'end'.
1285     PP.LexUnexpandedToken(Tok);
1286     const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1287     if (BeginEnd && BeginEnd->isStr("begin")) {
1288       IsBegin = true;
1289     } else if (BeginEnd && BeginEnd->isStr("end")) {
1290       IsBegin = false;
1291     } else {
1292       PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1293       return;
1294     }
1295 
1296     // Verify that this is followed by EOD.
1297     PP.LexUnexpandedToken(Tok);
1298     if (Tok.isNot(tok::eod))
1299       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1300 
1301     // The start location of the active audit.
1302     SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1303 
1304     // The start location we want after processing this.
1305     SourceLocation NewLoc;
1306 
1307     if (IsBegin) {
1308       // Complain about attempts to re-enter an audit.
1309       if (BeginLoc.isValid()) {
1310         PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1311         PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1312       }
1313       NewLoc = Loc;
1314     } else {
1315       // Complain about attempts to leave an audit that doesn't exist.
1316       if (!BeginLoc.isValid()) {
1317         PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1318         return;
1319       }
1320       NewLoc = SourceLocation();
1321     }
1322 
1323     PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1324   }
1325 };
1326 
1327 /// \brief Handle "\#pragma region [...]"
1328 ///
1329 /// The syntax is
1330 /// \code
1331 ///   #pragma region [optional name]
1332 ///   #pragma endregion [optional comment]
1333 /// \endcode
1334 ///
1335 /// \note This is
1336 /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
1337 /// pragma, just skipped by compiler.
1338 struct PragmaRegionHandler : public PragmaHandler {
1339   PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) { }
1340 
1341   void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1342                     Token &NameTok) override {
1343     // #pragma region: endregion matches can be verified
1344     // __pragma(region): no sense, but ignored by msvc
1345     // _Pragma is not valid for MSVC, but there isn't any point
1346     // to handle a _Pragma differently.
1347   }
1348 };
1349 
1350 }  // end anonymous namespace
1351 
1352 
1353 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1354 /// \#pragma GCC poison/system_header/dependency and \#pragma once.
1355 void Preprocessor::RegisterBuiltinPragmas() {
1356   AddPragmaHandler(new PragmaOnceHandler());
1357   AddPragmaHandler(new PragmaMarkHandler());
1358   AddPragmaHandler(new PragmaPushMacroHandler());
1359   AddPragmaHandler(new PragmaPopMacroHandler());
1360   AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
1361 
1362   // #pragma GCC ...
1363   AddPragmaHandler("GCC", new PragmaPoisonHandler());
1364   AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1365   AddPragmaHandler("GCC", new PragmaDependencyHandler());
1366   AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1367   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
1368                                                    "GCC"));
1369   AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
1370                                                    "GCC"));
1371   // #pragma clang ...
1372   AddPragmaHandler("clang", new PragmaPoisonHandler());
1373   AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1374   AddPragmaHandler("clang", new PragmaDebugHandler());
1375   AddPragmaHandler("clang", new PragmaDependencyHandler());
1376   AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1377   AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1378 
1379   AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1380   AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1381   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1382 
1383   // MS extensions.
1384   if (LangOpts.MicrosoftExt) {
1385     AddPragmaHandler(new PragmaWarningHandler());
1386     AddPragmaHandler(new PragmaIncludeAliasHandler());
1387     AddPragmaHandler(new PragmaRegionHandler("region"));
1388     AddPragmaHandler(new PragmaRegionHandler("endregion"));
1389   }
1390 }
1391 
1392 /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
1393 /// warn about those pragmas being unknown.
1394 void Preprocessor::IgnorePragmas() {
1395   AddPragmaHandler(new EmptyPragmaHandler());
1396   // Also ignore all pragmas in all namespaces created
1397   // in Preprocessor::RegisterBuiltinPragmas().
1398   AddPragmaHandler("GCC", new EmptyPragmaHandler());
1399   AddPragmaHandler("clang", new EmptyPragmaHandler());
1400   if (PragmaHandler *NS = PragmaHandlers->FindHandler("STDC")) {
1401     // Preprocessor::RegisterBuiltinPragmas() already registers
1402     // PragmaSTDC_UnknownHandler as the empty handler, so remove it first,
1403     // otherwise there will be an assert about a duplicate handler.
1404     PragmaNamespace *STDCNamespace = NS->getIfNamespace();
1405     assert(STDCNamespace &&
1406            "Invalid namespace, registered as a regular pragma handler!");
1407     if (PragmaHandler *Existing = STDCNamespace->FindHandler("", false)) {
1408       RemovePragmaHandler("STDC", Existing);
1409       delete Existing;
1410     }
1411   }
1412   AddPragmaHandler("STDC", new EmptyPragmaHandler());
1413 }
1414