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/Lex/HeaderSearch.h"
17 #include "clang/Lex/LiteralSupport.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "clang/Lex/MacroInfo.h"
20 #include "clang/Lex/LexDiagnostic.h"
21 #include "clang/Basic/FileManager.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include <algorithm>
26 using namespace clang;
27 
28 // Out-of-line destructor to provide a home for the class.
29 PragmaHandler::~PragmaHandler() {
30 }
31 
32 //===----------------------------------------------------------------------===//
33 // EmptyPragmaHandler Implementation.
34 //===----------------------------------------------------------------------===//
35 
36 EmptyPragmaHandler::EmptyPragmaHandler() {}
37 
38 void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
39                                       PragmaIntroducerKind Introducer,
40                                       Token &FirstToken) {}
41 
42 //===----------------------------------------------------------------------===//
43 // PragmaNamespace Implementation.
44 //===----------------------------------------------------------------------===//
45 
46 
47 PragmaNamespace::~PragmaNamespace() {
48   for (llvm::StringMap<PragmaHandler*>::iterator
49          I = Handlers.begin(), E = Handlers.end(); I != E; ++I)
50     delete I->second;
51 }
52 
53 /// FindHandler - Check to see if there is already a handler for the
54 /// specified name.  If not, return the handler for the null identifier if it
55 /// exists, otherwise return null.  If IgnoreNull is true (the default) then
56 /// the null handler isn't returned on failure to match.
57 PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
58                                             bool IgnoreNull) const {
59   if (PragmaHandler *Handler = Handlers.lookup(Name))
60     return Handler;
61   return IgnoreNull ? 0 : Handlers.lookup(StringRef());
62 }
63 
64 void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
65   assert(!Handlers.lookup(Handler->getName()) &&
66          "A handler with this name is already registered in this namespace");
67   llvm::StringMapEntry<PragmaHandler *> &Entry =
68     Handlers.GetOrCreateValue(Handler->getName());
69   Entry.setValue(Handler);
70 }
71 
72 void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
73   assert(Handlers.lookup(Handler->getName()) &&
74          "Handler not registered in this namespace");
75   Handlers.erase(Handler->getName());
76 }
77 
78 void PragmaNamespace::HandlePragma(Preprocessor &PP,
79                                    PragmaIntroducerKind Introducer,
80                                    Token &Tok) {
81   // Read the 'namespace' that the directive is in, e.g. STDC.  Do not macro
82   // expand it, the user can have a STDC #define, that should not affect this.
83   PP.LexUnexpandedToken(Tok);
84 
85   // Get the handler for this token.  If there is no handler, ignore the pragma.
86   PragmaHandler *Handler
87     = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
88                                           : StringRef(),
89                   /*IgnoreNull=*/false);
90   if (Handler == 0) {
91     PP.Diag(Tok, diag::warn_pragma_ignored);
92     return;
93   }
94 
95   // Otherwise, pass it down.
96   Handler->HandlePragma(PP, Introducer, Tok);
97 }
98 
99 //===----------------------------------------------------------------------===//
100 // Preprocessor Pragma Directive Handling.
101 //===----------------------------------------------------------------------===//
102 
103 /// HandlePragmaDirective - The "#pragma" directive has been parsed.  Lex the
104 /// rest of the pragma, passing it to the registered pragma handlers.
105 void Preprocessor::HandlePragmaDirective(unsigned Introducer) {
106   ++NumPragma;
107 
108   // Invoke the first level of pragma handlers which reads the namespace id.
109   Token Tok;
110   PragmaHandlers->HandlePragma(*this, PragmaIntroducerKind(Introducer), Tok);
111 
112   // If the pragma handler didn't read the rest of the line, consume it now.
113   if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
114    || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
115     DiscardUntilEndOfDirective();
116 }
117 
118 /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
119 /// return the first token after the directive.  The _Pragma token has just
120 /// been read into 'Tok'.
121 void Preprocessor::Handle_Pragma(Token &Tok) {
122   // Remember the pragma token location.
123   SourceLocation PragmaLoc = Tok.getLocation();
124 
125   // Read the '('.
126   Lex(Tok);
127   if (Tok.isNot(tok::l_paren)) {
128     Diag(PragmaLoc, diag::err__Pragma_malformed);
129     return;
130   }
131 
132   // Read the '"..."'.
133   Lex(Tok);
134   if (Tok.isNot(tok::string_literal) && Tok.isNot(tok::wide_string_literal)) {
135     Diag(PragmaLoc, diag::err__Pragma_malformed);
136     return;
137   }
138 
139   // Remember the string.
140   std::string StrVal = getSpelling(Tok);
141 
142   // Read the ')'.
143   Lex(Tok);
144   if (Tok.isNot(tok::r_paren)) {
145     Diag(PragmaLoc, diag::err__Pragma_malformed);
146     return;
147   }
148 
149   SourceLocation RParenLoc = Tok.getLocation();
150 
151   // The _Pragma is lexically sound.  Destringize according to C99 6.10.9.1:
152   // "The string literal is destringized by deleting the L prefix, if present,
153   // deleting the leading and trailing double-quotes, replacing each escape
154   // sequence \" by a double-quote, and replacing each escape sequence \\ by a
155   // single backslash."
156   if (StrVal[0] == 'L')  // Remove L prefix.
157     StrVal.erase(StrVal.begin());
158   assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
159          "Invalid string token!");
160 
161   // Remove the front quote, replacing it with a space, so that the pragma
162   // contents appear to have a space before them.
163   StrVal[0] = ' ';
164 
165   // Replace the terminating quote with a \n.
166   StrVal[StrVal.size()-1] = '\n';
167 
168   // Remove escaped quotes and escapes.
169   for (unsigned i = 0, e = StrVal.size(); i != e-1; ++i) {
170     if (StrVal[i] == '\\' &&
171         (StrVal[i+1] == '\\' || StrVal[i+1] == '"')) {
172       // \\ -> '\' and \" -> '"'.
173       StrVal.erase(StrVal.begin()+i);
174       --e;
175     }
176   }
177 
178   // Plop the string (including the newline and trailing null) into a buffer
179   // where we can lex it.
180   Token TmpTok;
181   TmpTok.startToken();
182   CreateString(&StrVal[0], StrVal.size(), TmpTok);
183   SourceLocation TokLoc = TmpTok.getLocation();
184 
185   // Make and enter a lexer object so that we lex and expand the tokens just
186   // like any others.
187   Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
188                                         StrVal.size(), *this);
189 
190   EnterSourceFileWithLexer(TL, 0);
191 
192   // With everything set up, lex this as a #pragma directive.
193   HandlePragmaDirective(PIK__Pragma);
194 
195   // Finally, return whatever came after the pragma directive.
196   return Lex(Tok);
197 }
198 
199 /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
200 /// is not enclosed within a string literal.
201 void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
202   // Remember the pragma token location.
203   SourceLocation PragmaLoc = Tok.getLocation();
204 
205   // Read the '('.
206   Lex(Tok);
207   if (Tok.isNot(tok::l_paren)) {
208     Diag(PragmaLoc, diag::err__Pragma_malformed);
209     return;
210   }
211 
212   // Get the tokens enclosed within the __pragma(), as well as the final ')'.
213   SmallVector<Token, 32> PragmaToks;
214   int NumParens = 0;
215   Lex(Tok);
216   while (Tok.isNot(tok::eof)) {
217     PragmaToks.push_back(Tok);
218     if (Tok.is(tok::l_paren))
219       NumParens++;
220     else if (Tok.is(tok::r_paren) && NumParens-- == 0)
221       break;
222     Lex(Tok);
223   }
224 
225   if (Tok.is(tok::eof)) {
226     Diag(PragmaLoc, diag::err_unterminated___pragma);
227     return;
228   }
229 
230   PragmaToks.front().setFlag(Token::LeadingSpace);
231 
232   // Replace the ')' with an EOD to mark the end of the pragma.
233   PragmaToks.back().setKind(tok::eod);
234 
235   Token *TokArray = new Token[PragmaToks.size()];
236   std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
237 
238   // Push the tokens onto the stack.
239   EnterTokenStream(TokArray, PragmaToks.size(), true, true);
240 
241   // With everything set up, lex this as a #pragma directive.
242   HandlePragmaDirective(PIK___pragma);
243 
244   // Finally, return whatever came after the pragma directive.
245   return Lex(Tok);
246 }
247 
248 /// HandlePragmaOnce - Handle #pragma once.  OnceTok is the 'once'.
249 ///
250 void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
251   if (isInPrimaryFile()) {
252     Diag(OnceTok, diag::pp_pragma_once_in_main_file);
253     return;
254   }
255 
256   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
257   // Mark the file as a once-only file now.
258   HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
259 }
260 
261 void Preprocessor::HandlePragmaMark() {
262   assert(CurPPLexer && "No current lexer?");
263   if (CurLexer)
264     CurLexer->ReadToEndOfLine();
265   else
266     CurPTHLexer->DiscardToEndOfLine();
267 }
268 
269 
270 /// HandlePragmaPoison - Handle #pragma GCC poison.  PoisonTok is the 'poison'.
271 ///
272 void Preprocessor::HandlePragmaPoison(Token &PoisonTok) {
273   Token Tok;
274 
275   while (1) {
276     // Read the next token to poison.  While doing this, pretend that we are
277     // skipping while reading the identifier to poison.
278     // This avoids errors on code like:
279     //   #pragma GCC poison X
280     //   #pragma GCC poison X
281     if (CurPPLexer) CurPPLexer->LexingRawMode = true;
282     LexUnexpandedToken(Tok);
283     if (CurPPLexer) CurPPLexer->LexingRawMode = false;
284 
285     // If we reached the end of line, we're done.
286     if (Tok.is(tok::eod)) return;
287 
288     // Can only poison identifiers.
289     if (Tok.isNot(tok::raw_identifier)) {
290       Diag(Tok, diag::err_pp_invalid_poison);
291       return;
292     }
293 
294     // Look up the identifier info for the token.  We disabled identifier lookup
295     // by saying we're skipping contents, so we need to do this manually.
296     IdentifierInfo *II = LookUpIdentifierInfo(Tok);
297 
298     // Already poisoned.
299     if (II->isPoisoned()) continue;
300 
301     // If this is a macro identifier, emit a warning.
302     if (II->hasMacroDefinition())
303       Diag(Tok, diag::pp_poisoning_existing_macro);
304 
305     // Finally, poison it!
306     II->setIsPoisoned();
307     if (II->isFromAST())
308       II->setChangedSinceDeserialization();
309   }
310 }
311 
312 /// HandlePragmaSystemHeader - Implement #pragma GCC system_header.  We know
313 /// that the whole directive has been parsed.
314 void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
315   if (isInPrimaryFile()) {
316     Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
317     return;
318   }
319 
320   // Get the current file lexer we're looking at.  Ignore _Pragma 'files' etc.
321   PreprocessorLexer *TheLexer = getCurrentFileLexer();
322 
323   // Mark the file as a system header.
324   HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
325 
326 
327   PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
328   if (PLoc.isInvalid())
329     return;
330 
331   unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
332 
333   // Notify the client, if desired, that we are in a new source file.
334   if (Callbacks)
335     Callbacks->FileChanged(SysHeaderTok.getLocation(),
336                            PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
337 
338   // Emit a line marker.  This will change any source locations from this point
339   // forward to realize they are in a system header.
340   // Create a line note with this information.
341   SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine(), FilenameID,
342                         false, false, true, false);
343 }
344 
345 /// HandlePragmaDependency - Handle #pragma GCC dependency "foo" blah.
346 ///
347 void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
348   Token FilenameTok;
349   CurPPLexer->LexIncludeFilename(FilenameTok);
350 
351   // If the token kind is EOD, the error has already been diagnosed.
352   if (FilenameTok.is(tok::eod))
353     return;
354 
355   // Reserve a buffer to get the spelling.
356   llvm::SmallString<128> FilenameBuffer;
357   bool Invalid = false;
358   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
359   if (Invalid)
360     return;
361 
362   bool isAngled =
363     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
364   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
365   // error.
366   if (Filename.empty())
367     return;
368 
369   // Search include directories for this file.
370   const DirectoryLookup *CurDir;
371   const FileEntry *File = LookupFile(Filename, isAngled, 0, CurDir, NULL, NULL,
372                                      NULL);
373   if (File == 0) {
374     if (!SuppressIncludeNotFoundError)
375       Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
376     return;
377   }
378 
379   const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
380 
381   // If this file is older than the file it depends on, emit a diagnostic.
382   if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
383     // Lex tokens at the end of the message and include them in the message.
384     std::string Message;
385     Lex(DependencyTok);
386     while (DependencyTok.isNot(tok::eod)) {
387       Message += getSpelling(DependencyTok) + " ";
388       Lex(DependencyTok);
389     }
390 
391     // Remove the trailing ' ' if present.
392     if (!Message.empty())
393       Message.erase(Message.end()-1);
394     Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
395   }
396 }
397 
398 /// HandlePragmaComment - Handle the microsoft #pragma comment extension.  The
399 /// syntax is:
400 ///   #pragma comment(linker, "foo")
401 /// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
402 /// "foo" is a string, which is fully macro expanded, and permits string
403 /// concatenation, embedded escape characters etc.  See MSDN for more details.
404 void Preprocessor::HandlePragmaComment(Token &Tok) {
405   SourceLocation CommentLoc = Tok.getLocation();
406   Lex(Tok);
407   if (Tok.isNot(tok::l_paren)) {
408     Diag(CommentLoc, diag::err_pragma_comment_malformed);
409     return;
410   }
411 
412   // Read the identifier.
413   Lex(Tok);
414   if (Tok.isNot(tok::identifier)) {
415     Diag(CommentLoc, diag::err_pragma_comment_malformed);
416     return;
417   }
418 
419   // Verify that this is one of the 5 whitelisted options.
420   // FIXME: warn that 'exestr' is deprecated.
421   const IdentifierInfo *II = Tok.getIdentifierInfo();
422   if (!II->isStr("compiler") && !II->isStr("exestr") && !II->isStr("lib") &&
423       !II->isStr("linker") && !II->isStr("user")) {
424     Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
425     return;
426   }
427 
428   // Read the optional string if present.
429   Lex(Tok);
430   std::string ArgumentString;
431   if (Tok.is(tok::comma)) {
432     Lex(Tok); // eat the comma.
433 
434     // We need at least one string.
435     if (Tok.isNot(tok::string_literal)) {
436       Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
437       return;
438     }
439 
440     // String concatenation allows multiple strings, which can even come from
441     // macro expansion.
442     // "foo " "bar" "Baz"
443     SmallVector<Token, 4> StrToks;
444     while (Tok.is(tok::string_literal)) {
445       StrToks.push_back(Tok);
446       Lex(Tok);
447     }
448 
449     // Concatenate and parse the strings.
450     StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
451     assert(Literal.isAscii() && "Didn't allow wide strings in");
452     if (Literal.hadError)
453       return;
454     if (Literal.Pascal) {
455       Diag(StrToks[0].getLocation(), diag::err_pragma_comment_malformed);
456       return;
457     }
458 
459     ArgumentString = Literal.GetString();
460   }
461 
462   // FIXME: If the kind is "compiler" warn if the string is present (it is
463   // ignored).
464   // FIXME: 'lib' requires a comment string.
465   // FIXME: 'linker' requires a comment string, and has a specific list of
466   // things that are allowable.
467 
468   if (Tok.isNot(tok::r_paren)) {
469     Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
470     return;
471   }
472   Lex(Tok);  // eat the r_paren.
473 
474   if (Tok.isNot(tok::eod)) {
475     Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
476     return;
477   }
478 
479   // If the pragma is lexically sound, notify any interested PPCallbacks.
480   if (Callbacks)
481     Callbacks->PragmaComment(CommentLoc, II, ArgumentString);
482 }
483 
484 /// HandlePragmaMessage - Handle the microsoft and gcc #pragma message
485 /// extension.  The syntax is:
486 ///   #pragma message(string)
487 /// OR, in GCC mode:
488 ///   #pragma message string
489 /// string is a string, which is fully macro expanded, and permits string
490 /// concatenation, embedded escape characters, etc... See MSDN for more details.
491 void Preprocessor::HandlePragmaMessage(Token &Tok) {
492   SourceLocation MessageLoc = Tok.getLocation();
493   Lex(Tok);
494   bool ExpectClosingParen = false;
495   switch (Tok.getKind()) {
496   case tok::l_paren:
497     // We have a MSVC style pragma message.
498     ExpectClosingParen = true;
499     // Read the string.
500     Lex(Tok);
501     break;
502   case tok::string_literal:
503     // We have a GCC style pragma message, and we just read the string.
504     break;
505   default:
506     Diag(MessageLoc, diag::err_pragma_message_malformed);
507     return;
508   }
509 
510   // We need at least one string.
511   if (Tok.isNot(tok::string_literal)) {
512     Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
513     return;
514   }
515 
516   // String concatenation allows multiple strings, which can even come from
517   // macro expansion.
518   // "foo " "bar" "Baz"
519   SmallVector<Token, 4> StrToks;
520   while (Tok.is(tok::string_literal)) {
521     StrToks.push_back(Tok);
522     Lex(Tok);
523   }
524 
525   // Concatenate and parse the strings.
526   StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
527   assert(Literal.isAscii() && "Didn't allow wide strings in");
528   if (Literal.hadError)
529     return;
530   if (Literal.Pascal) {
531     Diag(StrToks[0].getLocation(), diag::err_pragma_message_malformed);
532     return;
533   }
534 
535   StringRef MessageString(Literal.GetString());
536 
537   if (ExpectClosingParen) {
538     if (Tok.isNot(tok::r_paren)) {
539       Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
540       return;
541     }
542     Lex(Tok);  // eat the r_paren.
543   }
544 
545   if (Tok.isNot(tok::eod)) {
546     Diag(Tok.getLocation(), diag::err_pragma_message_malformed);
547     return;
548   }
549 
550   // Output the message.
551   Diag(MessageLoc, diag::warn_pragma_message) << MessageString;
552 
553   // If the pragma is lexically sound, notify any interested PPCallbacks.
554   if (Callbacks)
555     Callbacks->PragmaMessage(MessageLoc, MessageString);
556 }
557 
558 /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
559 /// Return the IdentifierInfo* associated with the macro to push or pop.
560 IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
561   // Remember the pragma token location.
562   Token PragmaTok = Tok;
563 
564   // Read the '('.
565   Lex(Tok);
566   if (Tok.isNot(tok::l_paren)) {
567     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
568       << getSpelling(PragmaTok);
569     return 0;
570   }
571 
572   // Read the macro name string.
573   Lex(Tok);
574   if (Tok.isNot(tok::string_literal)) {
575     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
576       << getSpelling(PragmaTok);
577     return 0;
578   }
579 
580   // Remember the macro string.
581   std::string StrVal = getSpelling(Tok);
582 
583   // Read the ')'.
584   Lex(Tok);
585   if (Tok.isNot(tok::r_paren)) {
586     Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
587       << getSpelling(PragmaTok);
588     return 0;
589   }
590 
591   assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
592          "Invalid string token!");
593 
594   // Create a Token from the string.
595   Token MacroTok;
596   MacroTok.startToken();
597   MacroTok.setKind(tok::raw_identifier);
598   CreateString(&StrVal[1], StrVal.size() - 2, MacroTok);
599 
600   // Get the IdentifierInfo of MacroToPushTok.
601   return LookUpIdentifierInfo(MacroTok);
602 }
603 
604 /// HandlePragmaPushMacro - Handle #pragma push_macro.
605 /// The syntax is:
606 ///   #pragma push_macro("macro")
607 void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
608   // Parse the pragma directive and get the macro IdentifierInfo*.
609   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
610   if (!IdentInfo) return;
611 
612   // Get the MacroInfo associated with IdentInfo.
613   MacroInfo *MI = getMacroInfo(IdentInfo);
614 
615   MacroInfo *MacroCopyToPush = 0;
616   if (MI) {
617     // Make a clone of MI.
618     MacroCopyToPush = CloneMacroInfo(*MI);
619 
620     // Allow the original MacroInfo to be redefined later.
621     MI->setIsAllowRedefinitionsWithoutWarning(true);
622   }
623 
624   // Push the cloned MacroInfo so we can retrieve it later.
625   PragmaPushMacroInfo[IdentInfo].push_back(MacroCopyToPush);
626 }
627 
628 /// HandlePragmaPopMacro - Handle #pragma pop_macro.
629 /// The syntax is:
630 ///   #pragma pop_macro("macro")
631 void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
632   SourceLocation MessageLoc = PopMacroTok.getLocation();
633 
634   // Parse the pragma directive and get the macro IdentifierInfo*.
635   IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
636   if (!IdentInfo) return;
637 
638   // Find the vector<MacroInfo*> associated with the macro.
639   llvm::DenseMap<IdentifierInfo*, std::vector<MacroInfo*> >::iterator iter =
640     PragmaPushMacroInfo.find(IdentInfo);
641   if (iter != PragmaPushMacroInfo.end()) {
642     // Release the MacroInfo currently associated with IdentInfo.
643     MacroInfo *CurrentMI = getMacroInfo(IdentInfo);
644     if (CurrentMI) {
645       if (CurrentMI->isWarnIfUnused())
646         WarnUnusedMacroLocs.erase(CurrentMI->getDefinitionLoc());
647       ReleaseMacroInfo(CurrentMI);
648     }
649 
650     // Get the MacroInfo we want to reinstall.
651     MacroInfo *MacroToReInstall = iter->second.back();
652 
653     // Reinstall the previously pushed macro.
654     setMacroInfo(IdentInfo, MacroToReInstall);
655 
656     // Pop PragmaPushMacroInfo stack.
657     iter->second.pop_back();
658     if (iter->second.size() == 0)
659       PragmaPushMacroInfo.erase(iter);
660   } else {
661     Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
662       << IdentInfo->getName();
663   }
664 }
665 
666 /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
667 /// If 'Namespace' is non-null, then it is a token required to exist on the
668 /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
669 void Preprocessor::AddPragmaHandler(StringRef Namespace,
670                                     PragmaHandler *Handler) {
671   PragmaNamespace *InsertNS = PragmaHandlers;
672 
673   // If this is specified to be in a namespace, step down into it.
674   if (!Namespace.empty()) {
675     // If there is already a pragma handler with the name of this namespace,
676     // we either have an error (directive with the same name as a namespace) or
677     // we already have the namespace to insert into.
678     if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
679       InsertNS = Existing->getIfNamespace();
680       assert(InsertNS != 0 && "Cannot have a pragma namespace and pragma"
681              " handler with the same name!");
682     } else {
683       // Otherwise, this namespace doesn't exist yet, create and insert the
684       // handler for it.
685       InsertNS = new PragmaNamespace(Namespace);
686       PragmaHandlers->AddPragma(InsertNS);
687     }
688   }
689 
690   // Check to make sure we don't already have a pragma for this identifier.
691   assert(!InsertNS->FindHandler(Handler->getName()) &&
692          "Pragma handler already exists for this identifier!");
693   InsertNS->AddPragma(Handler);
694 }
695 
696 /// RemovePragmaHandler - Remove the specific pragma handler from the
697 /// preprocessor. If \arg Namespace is non-null, then it should be the
698 /// namespace that \arg Handler was added to. It is an error to remove
699 /// a handler that has not been registered.
700 void Preprocessor::RemovePragmaHandler(StringRef Namespace,
701                                        PragmaHandler *Handler) {
702   PragmaNamespace *NS = PragmaHandlers;
703 
704   // If this is specified to be in a namespace, step down into it.
705   if (!Namespace.empty()) {
706     PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
707     assert(Existing && "Namespace containing handler does not exist!");
708 
709     NS = Existing->getIfNamespace();
710     assert(NS && "Invalid namespace, registered as a regular pragma handler!");
711   }
712 
713   NS->RemovePragmaHandler(Handler);
714 
715   // If this is a non-default namespace and it is now empty, remove
716   // it.
717   if (NS != PragmaHandlers && NS->IsEmpty())
718     PragmaHandlers->RemovePragmaHandler(NS);
719 }
720 
721 bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
722   Token Tok;
723   LexUnexpandedToken(Tok);
724 
725   if (Tok.isNot(tok::identifier)) {
726     Diag(Tok, diag::ext_on_off_switch_syntax);
727     return true;
728   }
729   IdentifierInfo *II = Tok.getIdentifierInfo();
730   if (II->isStr("ON"))
731     Result = tok::OOS_ON;
732   else if (II->isStr("OFF"))
733     Result = tok::OOS_OFF;
734   else if (II->isStr("DEFAULT"))
735     Result = tok::OOS_DEFAULT;
736   else {
737     Diag(Tok, diag::ext_on_off_switch_syntax);
738     return true;
739   }
740 
741   // Verify that this is followed by EOD.
742   LexUnexpandedToken(Tok);
743   if (Tok.isNot(tok::eod))
744     Diag(Tok, diag::ext_pragma_syntax_eod);
745   return false;
746 }
747 
748 namespace {
749 /// PragmaOnceHandler - "#pragma once" marks the file as atomically included.
750 struct PragmaOnceHandler : public PragmaHandler {
751   PragmaOnceHandler() : PragmaHandler("once") {}
752   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
753                             Token &OnceTok) {
754     PP.CheckEndOfDirective("pragma once");
755     PP.HandlePragmaOnce(OnceTok);
756   }
757 };
758 
759 /// PragmaMarkHandler - "#pragma mark ..." is ignored by the compiler, and the
760 /// rest of the line is not lexed.
761 struct PragmaMarkHandler : public PragmaHandler {
762   PragmaMarkHandler() : PragmaHandler("mark") {}
763   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
764                             Token &MarkTok) {
765     PP.HandlePragmaMark();
766   }
767 };
768 
769 /// PragmaPoisonHandler - "#pragma poison x" marks x as not usable.
770 struct PragmaPoisonHandler : public PragmaHandler {
771   PragmaPoisonHandler() : PragmaHandler("poison") {}
772   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
773                             Token &PoisonTok) {
774     PP.HandlePragmaPoison(PoisonTok);
775   }
776 };
777 
778 /// PragmaSystemHeaderHandler - "#pragma system_header" marks the current file
779 /// as a system header, which silences warnings in it.
780 struct PragmaSystemHeaderHandler : public PragmaHandler {
781   PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
782   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
783                             Token &SHToken) {
784     PP.HandlePragmaSystemHeader(SHToken);
785     PP.CheckEndOfDirective("pragma");
786   }
787 };
788 struct PragmaDependencyHandler : public PragmaHandler {
789   PragmaDependencyHandler() : PragmaHandler("dependency") {}
790   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
791                             Token &DepToken) {
792     PP.HandlePragmaDependency(DepToken);
793   }
794 };
795 
796 struct PragmaDebugHandler : public PragmaHandler {
797   PragmaDebugHandler() : PragmaHandler("__debug") {}
798   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
799                             Token &DepToken) {
800     Token Tok;
801     PP.LexUnexpandedToken(Tok);
802     if (Tok.isNot(tok::identifier)) {
803       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
804       return;
805     }
806     IdentifierInfo *II = Tok.getIdentifierInfo();
807 
808     if (II->isStr("assert")) {
809       llvm_unreachable("This is an assertion!");
810     } else if (II->isStr("crash")) {
811       *(volatile int*) 0x11 = 0;
812     } else if (II->isStr("llvm_fatal_error")) {
813       llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
814     } else if (II->isStr("llvm_unreachable")) {
815       llvm_unreachable("#pragma clang __debug llvm_unreachable");
816     } else if (II->isStr("overflow_stack")) {
817       DebugOverflowStack();
818     } else if (II->isStr("handle_crash")) {
819       llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
820       if (CRC)
821         CRC->HandleCrash();
822     } else {
823       PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
824         << II->getName();
825     }
826   }
827 
828 // Disable MSVC warning about runtime stack overflow.
829 #ifdef _MSC_VER
830     #pragma warning(disable : 4717)
831 #endif
832   void DebugOverflowStack() {
833     DebugOverflowStack();
834   }
835 #ifdef _MSC_VER
836     #pragma warning(default : 4717)
837 #endif
838 
839 };
840 
841 /// PragmaDiagnosticHandler - e.g. '#pragma GCC diagnostic ignored "-Wformat"'
842 struct PragmaDiagnosticHandler : public PragmaHandler {
843 private:
844   const char *Namespace;
845 public:
846   explicit PragmaDiagnosticHandler(const char *NS) :
847     PragmaHandler("diagnostic"), Namespace(NS) {}
848   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
849                             Token &DiagToken) {
850     SourceLocation DiagLoc = DiagToken.getLocation();
851     Token Tok;
852     PP.LexUnexpandedToken(Tok);
853     if (Tok.isNot(tok::identifier)) {
854       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
855       return;
856     }
857     IdentifierInfo *II = Tok.getIdentifierInfo();
858     PPCallbacks *Callbacks = PP.getPPCallbacks();
859 
860     diag::Mapping Map;
861     if (II->isStr("warning"))
862       Map = diag::MAP_WARNING;
863     else if (II->isStr("error"))
864       Map = diag::MAP_ERROR;
865     else if (II->isStr("ignored"))
866       Map = diag::MAP_IGNORE;
867     else if (II->isStr("fatal"))
868       Map = diag::MAP_FATAL;
869     else if (II->isStr("pop")) {
870       if (!PP.getDiagnostics().popMappings(DiagLoc))
871         PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
872       else if (Callbacks)
873         Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
874       return;
875     } else if (II->isStr("push")) {
876       PP.getDiagnostics().pushMappings(DiagLoc);
877       if (Callbacks)
878         Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
879       return;
880     } else {
881       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
882       return;
883     }
884 
885     PP.LexUnexpandedToken(Tok);
886 
887     // We need at least one string.
888     if (Tok.isNot(tok::string_literal)) {
889       PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
890       return;
891     }
892 
893     // String concatenation allows multiple strings, which can even come from
894     // macro expansion.
895     // "foo " "bar" "Baz"
896     SmallVector<Token, 4> StrToks;
897     while (Tok.is(tok::string_literal)) {
898       StrToks.push_back(Tok);
899       PP.LexUnexpandedToken(Tok);
900     }
901 
902     if (Tok.isNot(tok::eod)) {
903       PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
904       return;
905     }
906 
907     // Concatenate and parse the strings.
908     StringLiteralParser Literal(&StrToks[0], StrToks.size(), PP);
909     assert(Literal.isAscii() && "Didn't allow wide strings in");
910     if (Literal.hadError)
911       return;
912     if (Literal.Pascal) {
913       PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
914       return;
915     }
916 
917     StringRef WarningName(Literal.GetString());
918 
919     if (WarningName.size() < 3 || WarningName[0] != '-' ||
920         WarningName[1] != 'W') {
921       PP.Diag(StrToks[0].getLocation(),
922               diag::warn_pragma_diagnostic_invalid_option);
923       return;
924     }
925 
926     if (PP.getDiagnostics().setDiagnosticGroupMapping(WarningName.substr(2),
927                                                       Map, DiagLoc))
928       PP.Diag(StrToks[0].getLocation(),
929               diag::warn_pragma_diagnostic_unknown_warning) << WarningName;
930     else if (Callbacks)
931       Callbacks->PragmaDiagnostic(DiagLoc, Namespace, Map, WarningName);
932   }
933 };
934 
935 /// PragmaCommentHandler - "#pragma comment ...".
936 struct PragmaCommentHandler : public PragmaHandler {
937   PragmaCommentHandler() : PragmaHandler("comment") {}
938   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
939                             Token &CommentTok) {
940     PP.HandlePragmaComment(CommentTok);
941   }
942 };
943 
944 /// PragmaMessageHandler - "#pragma message("...")".
945 struct PragmaMessageHandler : public PragmaHandler {
946   PragmaMessageHandler() : PragmaHandler("message") {}
947   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
948                             Token &CommentTok) {
949     PP.HandlePragmaMessage(CommentTok);
950   }
951 };
952 
953 /// PragmaPushMacroHandler - "#pragma push_macro" saves the value of the
954 /// macro on the top of the stack.
955 struct PragmaPushMacroHandler : public PragmaHandler {
956   PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
957   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
958                             Token &PushMacroTok) {
959     PP.HandlePragmaPushMacro(PushMacroTok);
960   }
961 };
962 
963 
964 /// PragmaPopMacroHandler - "#pragma pop_macro" sets the value of the
965 /// macro to the value on the top of the stack.
966 struct PragmaPopMacroHandler : public PragmaHandler {
967   PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
968   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
969                             Token &PopMacroTok) {
970     PP.HandlePragmaPopMacro(PopMacroTok);
971   }
972 };
973 
974 // Pragma STDC implementations.
975 
976 /// PragmaSTDC_FENV_ACCESSHandler - "#pragma STDC FENV_ACCESS ...".
977 struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
978   PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
979   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
980                             Token &Tok) {
981     tok::OnOffSwitch OOS;
982     if (PP.LexOnOffSwitch(OOS))
983      return;
984     if (OOS == tok::OOS_ON)
985       PP.Diag(Tok, diag::warn_stdc_fenv_access_not_supported);
986   }
987 };
988 
989 /// PragmaSTDC_CX_LIMITED_RANGEHandler - "#pragma STDC CX_LIMITED_RANGE ...".
990 struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
991   PragmaSTDC_CX_LIMITED_RANGEHandler()
992     : PragmaHandler("CX_LIMITED_RANGE") {}
993   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
994                             Token &Tok) {
995     tok::OnOffSwitch OOS;
996     PP.LexOnOffSwitch(OOS);
997   }
998 };
999 
1000 /// PragmaSTDC_UnknownHandler - "#pragma STDC ...".
1001 struct PragmaSTDC_UnknownHandler : public PragmaHandler {
1002   PragmaSTDC_UnknownHandler() {}
1003   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1004                             Token &UnknownTok) {
1005     // C99 6.10.6p2, unknown forms are not allowed.
1006     PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
1007   }
1008 };
1009 
1010 /// PragmaARCCFCodeAuditedHandler -
1011 ///   #pragma clang arc_cf_code_audited begin/end
1012 struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
1013   PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
1014   virtual void HandlePragma(Preprocessor &PP, PragmaIntroducerKind Introducer,
1015                             Token &NameTok) {
1016     SourceLocation Loc = NameTok.getLocation();
1017     bool IsBegin;
1018 
1019     Token Tok;
1020 
1021     // Lex the 'begin' or 'end'.
1022     PP.LexUnexpandedToken(Tok);
1023     const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
1024     if (BeginEnd && BeginEnd->isStr("begin")) {
1025       IsBegin = true;
1026     } else if (BeginEnd && BeginEnd->isStr("end")) {
1027       IsBegin = false;
1028     } else {
1029       PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
1030       return;
1031     }
1032 
1033     // Verify that this is followed by EOD.
1034     PP.LexUnexpandedToken(Tok);
1035     if (Tok.isNot(tok::eod))
1036       PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
1037 
1038     // The start location of the active audit.
1039     SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedLoc();
1040 
1041     // The start location we want after processing this.
1042     SourceLocation NewLoc;
1043 
1044     if (IsBegin) {
1045       // Complain about attempts to re-enter an audit.
1046       if (BeginLoc.isValid()) {
1047         PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
1048         PP.Diag(BeginLoc, diag::note_pragma_entered_here);
1049       }
1050       NewLoc = Loc;
1051     } else {
1052       // Complain about attempts to leave an audit that doesn't exist.
1053       if (!BeginLoc.isValid()) {
1054         PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
1055         return;
1056       }
1057       NewLoc = SourceLocation();
1058     }
1059 
1060     PP.setPragmaARCCFCodeAuditedLoc(NewLoc);
1061   }
1062 };
1063 
1064 }  // end anonymous namespace
1065 
1066 
1067 /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
1068 /// #pragma GCC poison/system_header/dependency and #pragma once.
1069 void Preprocessor::RegisterBuiltinPragmas() {
1070   AddPragmaHandler(new PragmaOnceHandler());
1071   AddPragmaHandler(new PragmaMarkHandler());
1072   AddPragmaHandler(new PragmaPushMacroHandler());
1073   AddPragmaHandler(new PragmaPopMacroHandler());
1074   AddPragmaHandler(new PragmaMessageHandler());
1075 
1076   // #pragma GCC ...
1077   AddPragmaHandler("GCC", new PragmaPoisonHandler());
1078   AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
1079   AddPragmaHandler("GCC", new PragmaDependencyHandler());
1080   AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
1081   // #pragma clang ...
1082   AddPragmaHandler("clang", new PragmaPoisonHandler());
1083   AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
1084   AddPragmaHandler("clang", new PragmaDebugHandler());
1085   AddPragmaHandler("clang", new PragmaDependencyHandler());
1086   AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
1087   AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
1088 
1089   AddPragmaHandler("STDC", new PragmaSTDC_FENV_ACCESSHandler());
1090   AddPragmaHandler("STDC", new PragmaSTDC_CX_LIMITED_RANGEHandler());
1091   AddPragmaHandler("STDC", new PragmaSTDC_UnknownHandler());
1092 
1093   // MS extensions.
1094   if (Features.MicrosoftExt) {
1095     AddPragmaHandler(new PragmaCommentHandler());
1096   }
1097 }
1098