1 //===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===// 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 top level handling of macro expansion for the 11 // preprocessor. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/Preprocessor.h" 16 #include "clang/Basic/Attributes.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Basic/TargetInfo.h" 20 #include "clang/Lex/CodeCompletionHandler.h" 21 #include "clang/Lex/ExternalPreprocessorSource.h" 22 #include "clang/Lex/LexDiagnostic.h" 23 #include "clang/Lex/MacroArgs.h" 24 #include "clang/Lex/MacroInfo.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallString.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/Config/llvm-config.h" 29 #include "llvm/Support/ErrorHandling.h" 30 #include "llvm/Support/Format.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <cstdio> 33 #include <ctime> 34 using namespace clang; 35 36 MacroDirective * 37 Preprocessor::getMacroDirectiveHistory(const IdentifierInfo *II) const { 38 assert(II->hadMacroDefinition() && "Identifier has not been not a macro!"); 39 40 macro_iterator Pos = Macros.find(II); 41 assert(Pos != Macros.end() && "Identifier macro info is missing!"); 42 return Pos->second; 43 } 44 45 void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){ 46 assert(MD && "MacroDirective should be non-zero!"); 47 assert(!MD->getPrevious() && "Already attached to a MacroDirective history."); 48 49 MacroDirective *&StoredMD = Macros[II]; 50 MD->setPrevious(StoredMD); 51 StoredMD = MD; 52 // Setup the identifier as having associated macro history. 53 II->setHasMacroDefinition(true); 54 if (!MD->isDefined()) 55 II->setHasMacroDefinition(false); 56 bool isImportedMacro = isa<DefMacroDirective>(MD) && 57 cast<DefMacroDirective>(MD)->isImported(); 58 if (II->isFromAST() && !isImportedMacro) 59 II->setChangedSinceDeserialization(); 60 } 61 62 void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II, 63 MacroDirective *MD) { 64 assert(II && MD); 65 MacroDirective *&StoredMD = Macros[II]; 66 assert(!StoredMD && 67 "the macro history was modified before initializing it from a pch"); 68 StoredMD = MD; 69 // Setup the identifier as having associated macro history. 70 II->setHasMacroDefinition(true); 71 if (!MD->isDefined()) 72 II->setHasMacroDefinition(false); 73 } 74 75 /// RegisterBuiltinMacro - Register the specified identifier in the identifier 76 /// table and mark it as a builtin macro to be expanded. 77 static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){ 78 // Get the identifier. 79 IdentifierInfo *Id = PP.getIdentifierInfo(Name); 80 81 // Mark it as being a macro that is builtin. 82 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation()); 83 MI->setIsBuiltinMacro(); 84 PP.appendDefMacroDirective(Id, MI); 85 return Id; 86 } 87 88 89 /// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the 90 /// identifier table. 91 void Preprocessor::RegisterBuiltinMacros() { 92 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__"); 93 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__"); 94 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__"); 95 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__"); 96 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__"); 97 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma"); 98 99 // GCC Extensions. 100 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__"); 101 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__"); 102 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__"); 103 104 // Microsoft Extensions. 105 if (LangOpts.MicrosoftExt) { 106 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier"); 107 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma"); 108 } else { 109 Ident__identifier = nullptr; 110 Ident__pragma = nullptr; 111 } 112 113 // Clang Extensions. 114 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature"); 115 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension"); 116 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin"); 117 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute"); 118 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include"); 119 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next"); 120 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning"); 121 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier"); 122 123 // Modules. 124 if (LangOpts.Modules) { 125 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module"); 126 127 // __MODULE__ 128 if (!LangOpts.CurrentModule.empty()) 129 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__"); 130 else 131 Ident__MODULE__ = nullptr; 132 } else { 133 Ident__building_module = nullptr; 134 Ident__MODULE__ = nullptr; 135 } 136 } 137 138 /// isTrivialSingleTokenExpansion - Return true if MI, which has a single token 139 /// in its expansion, currently expands to that token literally. 140 static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, 141 const IdentifierInfo *MacroIdent, 142 Preprocessor &PP) { 143 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo(); 144 145 // If the token isn't an identifier, it's always literally expanded. 146 if (!II) return true; 147 148 // If the information about this identifier is out of date, update it from 149 // the external source. 150 if (II->isOutOfDate()) 151 PP.getExternalSource()->updateOutOfDateIdentifier(*II); 152 153 // If the identifier is a macro, and if that macro is enabled, it may be 154 // expanded so it's not a trivial expansion. 155 if (II->hasMacroDefinition() && PP.getMacroInfo(II)->isEnabled() && 156 // Fast expanding "#define X X" is ok, because X would be disabled. 157 II != MacroIdent) 158 return false; 159 160 // If this is an object-like macro invocation, it is safe to trivially expand 161 // it. 162 if (MI->isObjectLike()) return true; 163 164 // If this is a function-like macro invocation, it's safe to trivially expand 165 // as long as the identifier is not a macro argument. 166 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end(); 167 I != E; ++I) 168 if (*I == II) 169 return false; // Identifier is a macro argument. 170 171 return true; 172 } 173 174 175 /// isNextPPTokenLParen - Determine whether the next preprocessor token to be 176 /// lexed is a '('. If so, consume the token and return true, if not, this 177 /// method should have no observable side-effect on the lexed tokens. 178 bool Preprocessor::isNextPPTokenLParen() { 179 // Do some quick tests for rejection cases. 180 unsigned Val; 181 if (CurLexer) 182 Val = CurLexer->isNextPPTokenLParen(); 183 else if (CurPTHLexer) 184 Val = CurPTHLexer->isNextPPTokenLParen(); 185 else 186 Val = CurTokenLexer->isNextTokenLParen(); 187 188 if (Val == 2) { 189 // We have run off the end. If it's a source file we don't 190 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the 191 // macro stack. 192 if (CurPPLexer) 193 return false; 194 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) { 195 IncludeStackInfo &Entry = IncludeMacroStack[i-1]; 196 if (Entry.TheLexer) 197 Val = Entry.TheLexer->isNextPPTokenLParen(); 198 else if (Entry.ThePTHLexer) 199 Val = Entry.ThePTHLexer->isNextPPTokenLParen(); 200 else 201 Val = Entry.TheTokenLexer->isNextTokenLParen(); 202 203 if (Val != 2) 204 break; 205 206 // Ran off the end of a source file? 207 if (Entry.ThePPLexer) 208 return false; 209 } 210 } 211 212 // Okay, if we know that the token is a '(', lex it and return. Otherwise we 213 // have found something that isn't a '(' or we found the end of the 214 // translation unit. In either case, return false. 215 return Val == 1; 216 } 217 218 /// HandleMacroExpandedIdentifier - If an identifier token is read that is to be 219 /// expanded as a macro, handle it and return the next token as 'Identifier'. 220 bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier, 221 MacroDirective *MD) { 222 MacroDirective::DefInfo Def = MD->getDefinition(); 223 assert(Def.isValid()); 224 MacroInfo *MI = Def.getMacroInfo(); 225 226 // If this is a macro expansion in the "#if !defined(x)" line for the file, 227 // then the macro could expand to different things in other contexts, we need 228 // to disable the optimization in this case. 229 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro(); 230 231 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially. 232 if (MI->isBuiltinMacro()) { 233 if (Callbacks) Callbacks->MacroExpands(Identifier, MD, 234 Identifier.getLocation(), 235 /*Args=*/nullptr); 236 ExpandBuiltinMacro(Identifier); 237 return true; 238 } 239 240 /// Args - If this is a function-like macro expansion, this contains, 241 /// for each macro argument, the list of tokens that were provided to the 242 /// invocation. 243 MacroArgs *Args = nullptr; 244 245 // Remember where the end of the expansion occurred. For an object-like 246 // macro, this is the identifier. For a function-like macro, this is the ')'. 247 SourceLocation ExpansionEnd = Identifier.getLocation(); 248 249 // If this is a function-like macro, read the arguments. 250 if (MI->isFunctionLike()) { 251 // Remember that we are now parsing the arguments to a macro invocation. 252 // Preprocessor directives used inside macro arguments are not portable, and 253 // this enables the warning. 254 InMacroArgs = true; 255 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd); 256 257 // Finished parsing args. 258 InMacroArgs = false; 259 260 // If there was an error parsing the arguments, bail out. 261 if (!Args) return true; 262 263 ++NumFnMacroExpanded; 264 } else { 265 ++NumMacroExpanded; 266 } 267 268 // Notice that this macro has been used. 269 markMacroAsUsed(MI); 270 271 // Remember where the token is expanded. 272 SourceLocation ExpandLoc = Identifier.getLocation(); 273 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd); 274 275 if (Callbacks) { 276 if (InMacroArgs) { 277 // We can have macro expansion inside a conditional directive while 278 // reading the function macro arguments. To ensure, in that case, that 279 // MacroExpands callbacks still happen in source order, queue this 280 // callback to have it happen after the function macro callback. 281 DelayedMacroExpandsCallbacks.push_back( 282 MacroExpandsInfo(Identifier, MD, ExpansionRange)); 283 } else { 284 Callbacks->MacroExpands(Identifier, MD, ExpansionRange, Args); 285 if (!DelayedMacroExpandsCallbacks.empty()) { 286 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) { 287 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i]; 288 // FIXME: We lose macro args info with delayed callback. 289 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range, 290 /*Args=*/nullptr); 291 } 292 DelayedMacroExpandsCallbacks.clear(); 293 } 294 } 295 } 296 297 // If the macro definition is ambiguous, complain. 298 if (Def.getDirective()->isAmbiguous()) { 299 Diag(Identifier, diag::warn_pp_ambiguous_macro) 300 << Identifier.getIdentifierInfo(); 301 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen) 302 << Identifier.getIdentifierInfo(); 303 for (MacroDirective::DefInfo PrevDef = Def.getPreviousDefinition(); 304 PrevDef && !PrevDef.isUndefined(); 305 PrevDef = PrevDef.getPreviousDefinition()) { 306 Diag(PrevDef.getMacroInfo()->getDefinitionLoc(), 307 diag::note_pp_ambiguous_macro_other) 308 << Identifier.getIdentifierInfo(); 309 if (!PrevDef.getDirective()->isAmbiguous()) 310 break; 311 } 312 } 313 314 // If we started lexing a macro, enter the macro expansion body. 315 316 // If this macro expands to no tokens, don't bother to push it onto the 317 // expansion stack, only to take it right back off. 318 if (MI->getNumTokens() == 0) { 319 // No need for arg info. 320 if (Args) Args->destroy(*this); 321 322 // Propagate whitespace info as if we had pushed, then popped, 323 // a macro context. 324 Identifier.setFlag(Token::LeadingEmptyMacro); 325 PropagateLineStartLeadingSpaceInfo(Identifier); 326 ++NumFastMacroExpanded; 327 return false; 328 } else if (MI->getNumTokens() == 1 && 329 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(), 330 *this)) { 331 // Otherwise, if this macro expands into a single trivially-expanded 332 // token: expand it now. This handles common cases like 333 // "#define VAL 42". 334 335 // No need for arg info. 336 if (Args) Args->destroy(*this); 337 338 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro 339 // identifier to the expanded token. 340 bool isAtStartOfLine = Identifier.isAtStartOfLine(); 341 bool hasLeadingSpace = Identifier.hasLeadingSpace(); 342 343 // Replace the result token. 344 Identifier = MI->getReplacementToken(0); 345 346 // Restore the StartOfLine/LeadingSpace markers. 347 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine); 348 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace); 349 350 // Update the tokens location to include both its expansion and physical 351 // locations. 352 SourceLocation Loc = 353 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc, 354 ExpansionEnd,Identifier.getLength()); 355 Identifier.setLocation(Loc); 356 357 // If this is a disabled macro or #define X X, we must mark the result as 358 // unexpandable. 359 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) { 360 if (MacroInfo *NewMI = getMacroInfo(NewII)) 361 if (!NewMI->isEnabled() || NewMI == MI) { 362 Identifier.setFlag(Token::DisableExpand); 363 // Don't warn for "#define X X" like "#define bool bool" from 364 // stdbool.h. 365 if (NewMI != MI || MI->isFunctionLike()) 366 Diag(Identifier, diag::pp_disabled_macro_expansion); 367 } 368 } 369 370 // Since this is not an identifier token, it can't be macro expanded, so 371 // we're done. 372 ++NumFastMacroExpanded; 373 return true; 374 } 375 376 // Start expanding the macro. 377 EnterMacro(Identifier, ExpansionEnd, MI, Args); 378 return false; 379 } 380 381 enum Bracket { 382 Brace, 383 Paren 384 }; 385 386 /// CheckMatchedBrackets - Returns true if the braces and parentheses in the 387 /// token vector are properly nested. 388 static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) { 389 SmallVector<Bracket, 8> Brackets; 390 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(), 391 E = Tokens.end(); 392 I != E; ++I) { 393 if (I->is(tok::l_paren)) { 394 Brackets.push_back(Paren); 395 } else if (I->is(tok::r_paren)) { 396 if (Brackets.empty() || Brackets.back() == Brace) 397 return false; 398 Brackets.pop_back(); 399 } else if (I->is(tok::l_brace)) { 400 Brackets.push_back(Brace); 401 } else if (I->is(tok::r_brace)) { 402 if (Brackets.empty() || Brackets.back() == Paren) 403 return false; 404 Brackets.pop_back(); 405 } 406 } 407 if (!Brackets.empty()) 408 return false; 409 return true; 410 } 411 412 /// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new 413 /// vector of tokens in NewTokens. The new number of arguments will be placed 414 /// in NumArgs and the ranges which need to surrounded in parentheses will be 415 /// in ParenHints. 416 /// Returns false if the token stream cannot be changed. If this is because 417 /// of an initializer list starting a macro argument, the range of those 418 /// initializer lists will be place in InitLists. 419 static bool GenerateNewArgTokens(Preprocessor &PP, 420 SmallVectorImpl<Token> &OldTokens, 421 SmallVectorImpl<Token> &NewTokens, 422 unsigned &NumArgs, 423 SmallVectorImpl<SourceRange> &ParenHints, 424 SmallVectorImpl<SourceRange> &InitLists) { 425 if (!CheckMatchedBrackets(OldTokens)) 426 return false; 427 428 // Once it is known that the brackets are matched, only a simple count of the 429 // braces is needed. 430 unsigned Braces = 0; 431 432 // First token of a new macro argument. 433 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin(); 434 435 // First closing brace in a new macro argument. Used to generate 436 // SourceRanges for InitLists. 437 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end(); 438 NumArgs = 0; 439 Token TempToken; 440 // Set to true when a macro separator token is found inside a braced list. 441 // If true, the fixed argument spans multiple old arguments and ParenHints 442 // will be updated. 443 bool FoundSeparatorToken = false; 444 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(), 445 E = OldTokens.end(); 446 I != E; ++I) { 447 if (I->is(tok::l_brace)) { 448 ++Braces; 449 } else if (I->is(tok::r_brace)) { 450 --Braces; 451 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken) 452 ClosingBrace = I; 453 } else if (I->is(tok::eof)) { 454 // EOF token is used to separate macro arguments 455 if (Braces != 0) { 456 // Assume comma separator is actually braced list separator and change 457 // it back to a comma. 458 FoundSeparatorToken = true; 459 I->setKind(tok::comma); 460 I->setLength(1); 461 } else { // Braces == 0 462 // Separator token still separates arguments. 463 ++NumArgs; 464 465 // If the argument starts with a brace, it can't be fixed with 466 // parentheses. A different diagnostic will be given. 467 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) { 468 InitLists.push_back( 469 SourceRange(ArgStartIterator->getLocation(), 470 PP.getLocForEndOfToken(ClosingBrace->getLocation()))); 471 ClosingBrace = E; 472 } 473 474 // Add left paren 475 if (FoundSeparatorToken) { 476 TempToken.startToken(); 477 TempToken.setKind(tok::l_paren); 478 TempToken.setLocation(ArgStartIterator->getLocation()); 479 TempToken.setLength(0); 480 NewTokens.push_back(TempToken); 481 } 482 483 // Copy over argument tokens 484 NewTokens.insert(NewTokens.end(), ArgStartIterator, I); 485 486 // Add right paren and store the paren locations in ParenHints 487 if (FoundSeparatorToken) { 488 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation()); 489 TempToken.startToken(); 490 TempToken.setKind(tok::r_paren); 491 TempToken.setLocation(Loc); 492 TempToken.setLength(0); 493 NewTokens.push_back(TempToken); 494 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(), 495 Loc)); 496 } 497 498 // Copy separator token 499 NewTokens.push_back(*I); 500 501 // Reset values 502 ArgStartIterator = I + 1; 503 FoundSeparatorToken = false; 504 } 505 } 506 } 507 508 return !ParenHints.empty() && InitLists.empty(); 509 } 510 511 /// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next 512 /// token is the '(' of the macro, this method is invoked to read all of the 513 /// actual arguments specified for the macro invocation. This returns null on 514 /// error. 515 MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName, 516 MacroInfo *MI, 517 SourceLocation &MacroEnd) { 518 // The number of fixed arguments to parse. 519 unsigned NumFixedArgsLeft = MI->getNumArgs(); 520 bool isVariadic = MI->isVariadic(); 521 522 // Outer loop, while there are more arguments, keep reading them. 523 Token Tok; 524 525 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 526 // an argument value in a macro could expand to ',' or '(' or ')'. 527 LexUnexpandedToken(Tok); 528 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?"); 529 530 // ArgTokens - Build up a list of tokens that make up each argument. Each 531 // argument is separated by an EOF token. Use a SmallVector so we can avoid 532 // heap allocations in the common case. 533 SmallVector<Token, 64> ArgTokens; 534 bool ContainsCodeCompletionTok = false; 535 536 SourceLocation TooManyArgsLoc; 537 538 unsigned NumActuals = 0; 539 while (Tok.isNot(tok::r_paren)) { 540 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod))) 541 break; 542 543 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) && 544 "only expect argument separators here"); 545 546 unsigned ArgTokenStart = ArgTokens.size(); 547 SourceLocation ArgStartLoc = Tok.getLocation(); 548 549 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note 550 // that we already consumed the first one. 551 unsigned NumParens = 0; 552 553 while (1) { 554 // Read arguments as unexpanded tokens. This avoids issues, e.g., where 555 // an argument value in a macro could expand to ',' or '(' or ')'. 556 LexUnexpandedToken(Tok); 557 558 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n" 559 if (!ContainsCodeCompletionTok) { 560 Diag(MacroName, diag::err_unterm_macro_invoc); 561 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 562 << MacroName.getIdentifierInfo(); 563 // Do not lose the EOF/EOD. Return it to the client. 564 MacroName = Tok; 565 return nullptr; 566 } else { 567 // Do not lose the EOF/EOD. 568 Token *Toks = new Token[1]; 569 Toks[0] = Tok; 570 EnterTokenStream(Toks, 1, true, true); 571 break; 572 } 573 } else if (Tok.is(tok::r_paren)) { 574 // If we found the ) token, the macro arg list is done. 575 if (NumParens-- == 0) { 576 MacroEnd = Tok.getLocation(); 577 break; 578 } 579 } else if (Tok.is(tok::l_paren)) { 580 ++NumParens; 581 } else if (Tok.is(tok::comma) && NumParens == 0 && 582 !(Tok.getFlags() & Token::IgnoredComma)) { 583 // In Microsoft-compatibility mode, single commas from nested macro 584 // expansions should not be considered as argument separators. We test 585 // for this with the IgnoredComma token flag above. 586 587 // Comma ends this argument if there are more fixed arguments expected. 588 // However, if this is a variadic macro, and this is part of the 589 // variadic part, then the comma is just an argument token. 590 if (!isVariadic) break; 591 if (NumFixedArgsLeft > 1) 592 break; 593 } else if (Tok.is(tok::comment) && !KeepMacroComments) { 594 // If this is a comment token in the argument list and we're just in 595 // -C mode (not -CC mode), discard the comment. 596 continue; 597 } else if (Tok.getIdentifierInfo() != nullptr) { 598 // Reading macro arguments can cause macros that we are currently 599 // expanding from to be popped off the expansion stack. Doing so causes 600 // them to be reenabled for expansion. Here we record whether any 601 // identifiers we lex as macro arguments correspond to disabled macros. 602 // If so, we mark the token as noexpand. This is a subtle aspect of 603 // C99 6.10.3.4p2. 604 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo())) 605 if (!MI->isEnabled()) 606 Tok.setFlag(Token::DisableExpand); 607 } else if (Tok.is(tok::code_completion)) { 608 ContainsCodeCompletionTok = true; 609 if (CodeComplete) 610 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(), 611 MI, NumActuals); 612 // Don't mark that we reached the code-completion point because the 613 // parser is going to handle the token and there will be another 614 // code-completion callback. 615 } 616 617 ArgTokens.push_back(Tok); 618 } 619 620 // If this was an empty argument list foo(), don't add this as an empty 621 // argument. 622 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren) 623 break; 624 625 // If this is not a variadic macro, and too many args were specified, emit 626 // an error. 627 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) { 628 if (ArgTokens.size() != ArgTokenStart) 629 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation(); 630 else 631 TooManyArgsLoc = ArgStartLoc; 632 } 633 634 // Empty arguments are standard in C99 and C++0x, and are supported as an 635 // extension in other modes. 636 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99) 637 Diag(Tok, LangOpts.CPlusPlus11 ? 638 diag::warn_cxx98_compat_empty_fnmacro_arg : 639 diag::ext_empty_fnmacro_arg); 640 641 // Add a marker EOF token to the end of the token list for this argument. 642 Token EOFTok; 643 EOFTok.startToken(); 644 EOFTok.setKind(tok::eof); 645 EOFTok.setLocation(Tok.getLocation()); 646 EOFTok.setLength(0); 647 ArgTokens.push_back(EOFTok); 648 ++NumActuals; 649 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0) 650 --NumFixedArgsLeft; 651 } 652 653 // Okay, we either found the r_paren. Check to see if we parsed too few 654 // arguments. 655 unsigned MinArgsExpected = MI->getNumArgs(); 656 657 // If this is not a variadic macro, and too many args were specified, emit 658 // an error. 659 if (!isVariadic && NumActuals > MinArgsExpected && 660 !ContainsCodeCompletionTok) { 661 // Emit the diagnostic at the macro name in case there is a missing ). 662 // Emitting it at the , could be far away from the macro name. 663 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc); 664 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 665 << MacroName.getIdentifierInfo(); 666 667 // Commas from braced initializer lists will be treated as argument 668 // separators inside macros. Attempt to correct for this with parentheses. 669 // TODO: See if this can be generalized to angle brackets for templates 670 // inside macro arguments. 671 672 SmallVector<Token, 4> FixedArgTokens; 673 unsigned FixedNumArgs = 0; 674 SmallVector<SourceRange, 4> ParenHints, InitLists; 675 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs, 676 ParenHints, InitLists)) { 677 if (!InitLists.empty()) { 678 DiagnosticBuilder DB = 679 Diag(MacroName, 680 diag::note_init_list_at_beginning_of_macro_argument); 681 for (const SourceRange &Range : InitLists) 682 DB << Range; 683 } 684 return nullptr; 685 } 686 if (FixedNumArgs != MinArgsExpected) 687 return nullptr; 688 689 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro); 690 for (const SourceRange &ParenLocation : ParenHints) { 691 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "("); 692 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")"); 693 } 694 ArgTokens.swap(FixedArgTokens); 695 NumActuals = FixedNumArgs; 696 } 697 698 // See MacroArgs instance var for description of this. 699 bool isVarargsElided = false; 700 701 if (ContainsCodeCompletionTok) { 702 // Recover from not-fully-formed macro invocation during code-completion. 703 Token EOFTok; 704 EOFTok.startToken(); 705 EOFTok.setKind(tok::eof); 706 EOFTok.setLocation(Tok.getLocation()); 707 EOFTok.setLength(0); 708 for (; NumActuals < MinArgsExpected; ++NumActuals) 709 ArgTokens.push_back(EOFTok); 710 } 711 712 if (NumActuals < MinArgsExpected) { 713 // There are several cases where too few arguments is ok, handle them now. 714 if (NumActuals == 0 && MinArgsExpected == 1) { 715 // #define A(X) or #define A(...) ---> A() 716 717 // If there is exactly one argument, and that argument is missing, 718 // then we have an empty "()" argument empty list. This is fine, even if 719 // the macro expects one argument (the argument is just empty). 720 isVarargsElided = MI->isVariadic(); 721 } else if (MI->isVariadic() && 722 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X) 723 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A() 724 // Varargs where the named vararg parameter is missing: OK as extension. 725 // #define A(x, ...) 726 // A("blah") 727 // 728 // If the macro contains the comma pasting extension, the diagnostic 729 // is suppressed; we know we'll get another diagnostic later. 730 if (!MI->hasCommaPasting()) { 731 Diag(Tok, diag::ext_missing_varargs_arg); 732 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 733 << MacroName.getIdentifierInfo(); 734 } 735 736 // Remember this occurred, allowing us to elide the comma when used for 737 // cases like: 738 // #define A(x, foo...) blah(a, ## foo) 739 // #define B(x, ...) blah(a, ## __VA_ARGS__) 740 // #define C(...) blah(a, ## __VA_ARGS__) 741 // A(x) B(x) C() 742 isVarargsElided = true; 743 } else if (!ContainsCodeCompletionTok) { 744 // Otherwise, emit the error. 745 Diag(Tok, diag::err_too_few_args_in_macro_invoc); 746 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 747 << MacroName.getIdentifierInfo(); 748 return nullptr; 749 } 750 751 // Add a marker EOF token to the end of the token list for this argument. 752 SourceLocation EndLoc = Tok.getLocation(); 753 Tok.startToken(); 754 Tok.setKind(tok::eof); 755 Tok.setLocation(EndLoc); 756 Tok.setLength(0); 757 ArgTokens.push_back(Tok); 758 759 // If we expect two arguments, add both as empty. 760 if (NumActuals == 0 && MinArgsExpected == 2) 761 ArgTokens.push_back(Tok); 762 763 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() && 764 !ContainsCodeCompletionTok) { 765 // Emit the diagnostic at the macro name in case there is a missing ). 766 // Emitting it at the , could be far away from the macro name. 767 Diag(MacroName, diag::err_too_many_args_in_macro_invoc); 768 Diag(MI->getDefinitionLoc(), diag::note_macro_here) 769 << MacroName.getIdentifierInfo(); 770 return nullptr; 771 } 772 773 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this); 774 } 775 776 /// \brief Keeps macro expanded tokens for TokenLexers. 777 // 778 /// Works like a stack; a TokenLexer adds the macro expanded tokens that is 779 /// going to lex in the cache and when it finishes the tokens are removed 780 /// from the end of the cache. 781 Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer, 782 ArrayRef<Token> tokens) { 783 assert(tokLexer); 784 if (tokens.empty()) 785 return nullptr; 786 787 size_t newIndex = MacroExpandedTokens.size(); 788 bool cacheNeedsToGrow = tokens.size() > 789 MacroExpandedTokens.capacity()-MacroExpandedTokens.size(); 790 MacroExpandedTokens.append(tokens.begin(), tokens.end()); 791 792 if (cacheNeedsToGrow) { 793 // Go through all the TokenLexers whose 'Tokens' pointer points in the 794 // buffer and update the pointers to the (potential) new buffer array. 795 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) { 796 TokenLexer *prevLexer; 797 size_t tokIndex; 798 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i]; 799 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex; 800 } 801 } 802 803 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex)); 804 return MacroExpandedTokens.data() + newIndex; 805 } 806 807 void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() { 808 assert(!MacroExpandingLexersStack.empty()); 809 size_t tokIndex = MacroExpandingLexersStack.back().second; 810 assert(tokIndex < MacroExpandedTokens.size()); 811 // Pop the cached macro expanded tokens from the end. 812 MacroExpandedTokens.resize(tokIndex); 813 MacroExpandingLexersStack.pop_back(); 814 } 815 816 /// ComputeDATE_TIME - Compute the current time, enter it into the specified 817 /// scratch buffer, then return DATELoc/TIMELoc locations with the position of 818 /// the identifier tokens inserted. 819 static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, 820 Preprocessor &PP) { 821 time_t TT = time(nullptr); 822 struct tm *TM = localtime(&TT); 823 824 static const char * const Months[] = { 825 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" 826 }; 827 828 { 829 SmallString<32> TmpBuffer; 830 llvm::raw_svector_ostream TmpStream(TmpBuffer); 831 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon], 832 TM->tm_mday, TM->tm_year + 1900); 833 Token TmpTok; 834 TmpTok.startToken(); 835 PP.CreateString(TmpStream.str(), TmpTok); 836 DATELoc = TmpTok.getLocation(); 837 } 838 839 { 840 SmallString<32> TmpBuffer; 841 llvm::raw_svector_ostream TmpStream(TmpBuffer); 842 TmpStream << llvm::format("\"%02d:%02d:%02d\"", 843 TM->tm_hour, TM->tm_min, TM->tm_sec); 844 Token TmpTok; 845 TmpTok.startToken(); 846 PP.CreateString(TmpStream.str(), TmpTok); 847 TIMELoc = TmpTok.getLocation(); 848 } 849 } 850 851 852 /// HasFeature - Return true if we recognize and implement the feature 853 /// specified by the identifier as a standard language feature. 854 static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) { 855 const LangOptions &LangOpts = PP.getLangOpts(); 856 StringRef Feature = II->getName(); 857 858 // Normalize the feature name, __foo__ becomes foo. 859 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4) 860 Feature = Feature.substr(2, Feature.size() - 4); 861 862 return llvm::StringSwitch<bool>(Feature) 863 .Case("address_sanitizer", LangOpts.Sanitize.Address) 864 .Case("attribute_analyzer_noreturn", true) 865 .Case("attribute_availability", true) 866 .Case("attribute_availability_with_message", true) 867 .Case("attribute_cf_returns_not_retained", true) 868 .Case("attribute_cf_returns_retained", true) 869 .Case("attribute_deprecated_with_message", true) 870 .Case("attribute_ext_vector_type", true) 871 .Case("attribute_ns_returns_not_retained", true) 872 .Case("attribute_ns_returns_retained", true) 873 .Case("attribute_ns_consumes_self", true) 874 .Case("attribute_ns_consumed", true) 875 .Case("attribute_cf_consumed", true) 876 .Case("attribute_objc_ivar_unused", true) 877 .Case("attribute_objc_method_family", true) 878 .Case("attribute_overloadable", true) 879 .Case("attribute_unavailable_with_message", true) 880 .Case("attribute_unused_on_fields", true) 881 .Case("blocks", LangOpts.Blocks) 882 .Case("c_thread_safety_attributes", true) 883 .Case("cxx_exceptions", LangOpts.CXXExceptions) 884 .Case("cxx_rtti", LangOpts.RTTI) 885 .Case("enumerator_attributes", true) 886 .Case("memory_sanitizer", LangOpts.Sanitize.Memory) 887 .Case("thread_sanitizer", LangOpts.Sanitize.Thread) 888 .Case("dataflow_sanitizer", LangOpts.Sanitize.DataFlow) 889 // Objective-C features 890 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE? 891 .Case("objc_arc", LangOpts.ObjCAutoRefCount) 892 .Case("objc_arc_weak", LangOpts.ObjCARCWeak) 893 .Case("objc_default_synthesize_properties", LangOpts.ObjC2) 894 .Case("objc_fixed_enum", LangOpts.ObjC2) 895 .Case("objc_instancetype", LangOpts.ObjC2) 896 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules) 897 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile()) 898 .Case("objc_property_explicit_atomic", true) // Does clang support explicit "atomic" keyword? 899 .Case("objc_protocol_qualifier_mangling", true) 900 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport()) 901 .Case("ownership_holds", true) 902 .Case("ownership_returns", true) 903 .Case("ownership_takes", true) 904 .Case("objc_bool", true) 905 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile()) 906 .Case("objc_array_literals", LangOpts.ObjC2) 907 .Case("objc_dictionary_literals", LangOpts.ObjC2) 908 .Case("objc_boxed_expressions", LangOpts.ObjC2) 909 .Case("arc_cf_code_audited", true) 910 // C11 features 911 .Case("c_alignas", LangOpts.C11) 912 .Case("c_atomic", LangOpts.C11) 913 .Case("c_generic_selections", LangOpts.C11) 914 .Case("c_static_assert", LangOpts.C11) 915 .Case("c_thread_local", 916 LangOpts.C11 && PP.getTargetInfo().isTLSSupported()) 917 // C++11 features 918 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11) 919 .Case("cxx_alias_templates", LangOpts.CPlusPlus11) 920 .Case("cxx_alignas", LangOpts.CPlusPlus11) 921 .Case("cxx_atomic", LangOpts.CPlusPlus11) 922 .Case("cxx_attributes", LangOpts.CPlusPlus11) 923 .Case("cxx_auto_type", LangOpts.CPlusPlus11) 924 .Case("cxx_constexpr", LangOpts.CPlusPlus11) 925 .Case("cxx_decltype", LangOpts.CPlusPlus11) 926 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11) 927 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11) 928 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11) 929 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11) 930 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11) 931 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11) 932 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11) 933 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11) 934 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11) 935 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11) 936 .Case("cxx_lambdas", LangOpts.CPlusPlus11) 937 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11) 938 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11) 939 .Case("cxx_noexcept", LangOpts.CPlusPlus11) 940 .Case("cxx_nullptr", LangOpts.CPlusPlus11) 941 .Case("cxx_override_control", LangOpts.CPlusPlus11) 942 .Case("cxx_range_for", LangOpts.CPlusPlus11) 943 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11) 944 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11) 945 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11) 946 .Case("cxx_strong_enums", LangOpts.CPlusPlus11) 947 .Case("cxx_static_assert", LangOpts.CPlusPlus11) 948 .Case("cxx_thread_local", 949 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported()) 950 .Case("cxx_trailing_return", LangOpts.CPlusPlus11) 951 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11) 952 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11) 953 .Case("cxx_user_literals", LangOpts.CPlusPlus11) 954 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11) 955 // C++1y features 956 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14) 957 .Case("cxx_binary_literals", LangOpts.CPlusPlus14) 958 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14) 959 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14) 960 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14) 961 .Case("cxx_init_captures", LangOpts.CPlusPlus14) 962 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14) 963 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14) 964 .Case("cxx_variable_templates", LangOpts.CPlusPlus14) 965 // C++ TSes 966 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays) 967 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts) 968 // FIXME: Should this be __has_feature or __has_extension? 969 //.Case("raw_invocation_type", LangOpts.CPlusPlus) 970 // Type traits 971 .Case("has_nothrow_assign", LangOpts.CPlusPlus) 972 .Case("has_nothrow_copy", LangOpts.CPlusPlus) 973 .Case("has_nothrow_constructor", LangOpts.CPlusPlus) 974 .Case("has_trivial_assign", LangOpts.CPlusPlus) 975 .Case("has_trivial_copy", LangOpts.CPlusPlus) 976 .Case("has_trivial_constructor", LangOpts.CPlusPlus) 977 .Case("has_trivial_destructor", LangOpts.CPlusPlus) 978 .Case("has_virtual_destructor", LangOpts.CPlusPlus) 979 .Case("is_abstract", LangOpts.CPlusPlus) 980 .Case("is_base_of", LangOpts.CPlusPlus) 981 .Case("is_class", LangOpts.CPlusPlus) 982 .Case("is_constructible", LangOpts.CPlusPlus) 983 .Case("is_convertible_to", LangOpts.CPlusPlus) 984 .Case("is_empty", LangOpts.CPlusPlus) 985 .Case("is_enum", LangOpts.CPlusPlus) 986 .Case("is_final", LangOpts.CPlusPlus) 987 .Case("is_literal", LangOpts.CPlusPlus) 988 .Case("is_standard_layout", LangOpts.CPlusPlus) 989 .Case("is_pod", LangOpts.CPlusPlus) 990 .Case("is_polymorphic", LangOpts.CPlusPlus) 991 .Case("is_sealed", LangOpts.MicrosoftExt) 992 .Case("is_trivial", LangOpts.CPlusPlus) 993 .Case("is_trivially_assignable", LangOpts.CPlusPlus) 994 .Case("is_trivially_constructible", LangOpts.CPlusPlus) 995 .Case("is_trivially_copyable", LangOpts.CPlusPlus) 996 .Case("is_union", LangOpts.CPlusPlus) 997 .Case("modules", LangOpts.Modules) 998 .Case("tls", PP.getTargetInfo().isTLSSupported()) 999 .Case("underlying_type", LangOpts.CPlusPlus) 1000 .Default(false); 1001 } 1002 1003 /// HasExtension - Return true if we recognize and implement the feature 1004 /// specified by the identifier, either as an extension or a standard language 1005 /// feature. 1006 static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) { 1007 if (HasFeature(PP, II)) 1008 return true; 1009 1010 // If the use of an extension results in an error diagnostic, extensions are 1011 // effectively unavailable, so just return false here. 1012 if (PP.getDiagnostics().getExtensionHandlingBehavior() >= 1013 diag::Severity::Error) 1014 return false; 1015 1016 const LangOptions &LangOpts = PP.getLangOpts(); 1017 StringRef Extension = II->getName(); 1018 1019 // Normalize the extension name, __foo__ becomes foo. 1020 if (Extension.startswith("__") && Extension.endswith("__") && 1021 Extension.size() >= 4) 1022 Extension = Extension.substr(2, Extension.size() - 4); 1023 1024 // Because we inherit the feature list from HasFeature, this string switch 1025 // must be less restrictive than HasFeature's. 1026 return llvm::StringSwitch<bool>(Extension) 1027 // C11 features supported by other languages as extensions. 1028 .Case("c_alignas", true) 1029 .Case("c_atomic", true) 1030 .Case("c_generic_selections", true) 1031 .Case("c_static_assert", true) 1032 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported()) 1033 // C++11 features supported by other languages as extensions. 1034 .Case("cxx_atomic", LangOpts.CPlusPlus) 1035 .Case("cxx_deleted_functions", LangOpts.CPlusPlus) 1036 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus) 1037 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus) 1038 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus) 1039 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus) 1040 .Case("cxx_override_control", LangOpts.CPlusPlus) 1041 .Case("cxx_range_for", LangOpts.CPlusPlus) 1042 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus) 1043 .Case("cxx_rvalue_references", LangOpts.CPlusPlus) 1044 // C++1y features supported by other languages as extensions. 1045 .Case("cxx_binary_literals", true) 1046 .Case("cxx_init_captures", LangOpts.CPlusPlus11) 1047 .Case("cxx_variable_templates", LangOpts.CPlusPlus) 1048 .Default(false); 1049 } 1050 1051 /// EvaluateHasIncludeCommon - Process a '__has_include("path")' 1052 /// or '__has_include_next("path")' expression. 1053 /// Returns true if successful. 1054 static bool EvaluateHasIncludeCommon(Token &Tok, 1055 IdentifierInfo *II, Preprocessor &PP, 1056 const DirectoryLookup *LookupFrom, 1057 const FileEntry *LookupFromFile) { 1058 // Save the location of the current token. If a '(' is later found, use 1059 // that location. If not, use the end of this location instead. 1060 SourceLocation LParenLoc = Tok.getLocation(); 1061 1062 // These expressions are only allowed within a preprocessor directive. 1063 if (!PP.isParsingIfOrElifDirective()) { 1064 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName(); 1065 return false; 1066 } 1067 1068 // Get '('. 1069 PP.LexNonComment(Tok); 1070 1071 // Ensure we have a '('. 1072 if (Tok.isNot(tok::l_paren)) { 1073 // No '(', use end of last token. 1074 LParenLoc = PP.getLocForEndOfToken(LParenLoc); 1075 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren; 1076 // If the next token looks like a filename or the start of one, 1077 // assume it is and process it as such. 1078 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) && 1079 !Tok.is(tok::less)) 1080 return false; 1081 } else { 1082 // Save '(' location for possible missing ')' message. 1083 LParenLoc = Tok.getLocation(); 1084 1085 if (PP.getCurrentLexer()) { 1086 // Get the file name. 1087 PP.getCurrentLexer()->LexIncludeFilename(Tok); 1088 } else { 1089 // We're in a macro, so we can't use LexIncludeFilename; just 1090 // grab the next token. 1091 PP.Lex(Tok); 1092 } 1093 } 1094 1095 // Reserve a buffer to get the spelling. 1096 SmallString<128> FilenameBuffer; 1097 StringRef Filename; 1098 SourceLocation EndLoc; 1099 1100 switch (Tok.getKind()) { 1101 case tok::eod: 1102 // If the token kind is EOD, the error has already been diagnosed. 1103 return false; 1104 1105 case tok::angle_string_literal: 1106 case tok::string_literal: { 1107 bool Invalid = false; 1108 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid); 1109 if (Invalid) 1110 return false; 1111 break; 1112 } 1113 1114 case tok::less: 1115 // This could be a <foo/bar.h> file coming from a macro expansion. In this 1116 // case, glue the tokens together into FilenameBuffer and interpret those. 1117 FilenameBuffer.push_back('<'); 1118 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) { 1119 // Let the caller know a <eod> was found by changing the Token kind. 1120 Tok.setKind(tok::eod); 1121 return false; // Found <eod> but no ">"? Diagnostic already emitted. 1122 } 1123 Filename = FilenameBuffer.str(); 1124 break; 1125 default: 1126 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename); 1127 return false; 1128 } 1129 1130 SourceLocation FilenameLoc = Tok.getLocation(); 1131 1132 // Get ')'. 1133 PP.LexNonComment(Tok); 1134 1135 // Ensure we have a trailing ). 1136 if (Tok.isNot(tok::r_paren)) { 1137 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after) 1138 << II << tok::r_paren; 1139 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1140 return false; 1141 } 1142 1143 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename); 1144 // If GetIncludeFilenameSpelling set the start ptr to null, there was an 1145 // error. 1146 if (Filename.empty()) 1147 return false; 1148 1149 // Search include directories. 1150 const DirectoryLookup *CurDir; 1151 const FileEntry *File = 1152 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile, 1153 CurDir, nullptr, nullptr, nullptr); 1154 1155 // Get the result value. A result of true means the file exists. 1156 return File != nullptr; 1157 } 1158 1159 /// EvaluateHasInclude - Process a '__has_include("path")' expression. 1160 /// Returns true if successful. 1161 static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II, 1162 Preprocessor &PP) { 1163 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr); 1164 } 1165 1166 /// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression. 1167 /// Returns true if successful. 1168 static bool EvaluateHasIncludeNext(Token &Tok, 1169 IdentifierInfo *II, Preprocessor &PP) { 1170 // __has_include_next is like __has_include, except that we start 1171 // searching after the current found directory. If we can't do this, 1172 // issue a diagnostic. 1173 // FIXME: Factor out duplication wiht 1174 // Preprocessor::HandleIncludeNextDirective. 1175 const DirectoryLookup *Lookup = PP.GetCurDirLookup(); 1176 const FileEntry *LookupFromFile = nullptr; 1177 if (PP.isInPrimaryFile()) { 1178 Lookup = nullptr; 1179 PP.Diag(Tok, diag::pp_include_next_in_primary); 1180 } else if (PP.getCurrentSubmodule()) { 1181 // Start looking up in the directory *after* the one in which the current 1182 // file would be found, if any. 1183 assert(PP.getCurrentLexer() && "#include_next directive in macro?"); 1184 LookupFromFile = PP.getCurrentLexer()->getFileEntry(); 1185 Lookup = nullptr; 1186 } else if (!Lookup) { 1187 PP.Diag(Tok, diag::pp_include_next_absolute_path); 1188 } else { 1189 // Start looking up in the next directory. 1190 ++Lookup; 1191 } 1192 1193 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile); 1194 } 1195 1196 /// \brief Process __building_module(identifier) expression. 1197 /// \returns true if we are building the named module, false otherwise. 1198 static bool EvaluateBuildingModule(Token &Tok, 1199 IdentifierInfo *II, Preprocessor &PP) { 1200 // Get '('. 1201 PP.LexNonComment(Tok); 1202 1203 // Ensure we have a '('. 1204 if (Tok.isNot(tok::l_paren)) { 1205 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II 1206 << tok::l_paren; 1207 return false; 1208 } 1209 1210 // Save '(' location for possible missing ')' message. 1211 SourceLocation LParenLoc = Tok.getLocation(); 1212 1213 // Get the module name. 1214 PP.LexNonComment(Tok); 1215 1216 // Ensure that we have an identifier. 1217 if (Tok.isNot(tok::identifier)) { 1218 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module); 1219 return false; 1220 } 1221 1222 bool Result 1223 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule; 1224 1225 // Get ')'. 1226 PP.LexNonComment(Tok); 1227 1228 // Ensure we have a trailing ). 1229 if (Tok.isNot(tok::r_paren)) { 1230 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II 1231 << tok::r_paren; 1232 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1233 return false; 1234 } 1235 1236 return Result; 1237 } 1238 1239 /// ExpandBuiltinMacro - If an identifier token is read that is to be expanded 1240 /// as a builtin macro, handle it and return the next token as 'Tok'. 1241 void Preprocessor::ExpandBuiltinMacro(Token &Tok) { 1242 // Figure out which token this is. 1243 IdentifierInfo *II = Tok.getIdentifierInfo(); 1244 assert(II && "Can't be a macro without id info!"); 1245 1246 // If this is an _Pragma or Microsoft __pragma directive, expand it, 1247 // invoke the pragma handler, then lex the token after it. 1248 if (II == Ident_Pragma) 1249 return Handle_Pragma(Tok); 1250 else if (II == Ident__pragma) // in non-MS mode this is null 1251 return HandleMicrosoft__pragma(Tok); 1252 1253 ++NumBuiltinMacroExpanded; 1254 1255 SmallString<128> TmpBuffer; 1256 llvm::raw_svector_ostream OS(TmpBuffer); 1257 1258 // Set up the return result. 1259 Tok.setIdentifierInfo(nullptr); 1260 Tok.clearFlag(Token::NeedsCleaning); 1261 1262 if (II == Ident__LINE__) { 1263 // C99 6.10.8: "__LINE__: The presumed line number (within the current 1264 // source file) of the current source line (an integer constant)". This can 1265 // be affected by #line. 1266 SourceLocation Loc = Tok.getLocation(); 1267 1268 // Advance to the location of the first _, this might not be the first byte 1269 // of the token if it starts with an escaped newline. 1270 Loc = AdvanceToTokenCharacter(Loc, 0); 1271 1272 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of 1273 // a macro expansion. This doesn't matter for object-like macros, but 1274 // can matter for a function-like macro that expands to contain __LINE__. 1275 // Skip down through expansion points until we find a file loc for the 1276 // end of the expansion history. 1277 Loc = SourceMgr.getExpansionRange(Loc).second; 1278 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc); 1279 1280 // __LINE__ expands to a simple numeric value. 1281 OS << (PLoc.isValid()? PLoc.getLine() : 1); 1282 Tok.setKind(tok::numeric_constant); 1283 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) { 1284 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a 1285 // character string literal)". This can be affected by #line. 1286 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 1287 1288 // __BASE_FILE__ is a GNU extension that returns the top of the presumed 1289 // #include stack instead of the current file. 1290 if (II == Ident__BASE_FILE__ && PLoc.isValid()) { 1291 SourceLocation NextLoc = PLoc.getIncludeLoc(); 1292 while (NextLoc.isValid()) { 1293 PLoc = SourceMgr.getPresumedLoc(NextLoc); 1294 if (PLoc.isInvalid()) 1295 break; 1296 1297 NextLoc = PLoc.getIncludeLoc(); 1298 } 1299 } 1300 1301 // Escape this filename. Turn '\' -> '\\' '"' -> '\"' 1302 SmallString<128> FN; 1303 if (PLoc.isValid()) { 1304 FN += PLoc.getFilename(); 1305 Lexer::Stringify(FN); 1306 OS << '"' << FN.str() << '"'; 1307 } 1308 Tok.setKind(tok::string_literal); 1309 } else if (II == Ident__DATE__) { 1310 Diag(Tok.getLocation(), diag::warn_pp_date_time); 1311 if (!DATELoc.isValid()) 1312 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 1313 Tok.setKind(tok::string_literal); 1314 Tok.setLength(strlen("\"Mmm dd yyyy\"")); 1315 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(), 1316 Tok.getLocation(), 1317 Tok.getLength())); 1318 return; 1319 } else if (II == Ident__TIME__) { 1320 Diag(Tok.getLocation(), diag::warn_pp_date_time); 1321 if (!TIMELoc.isValid()) 1322 ComputeDATE_TIME(DATELoc, TIMELoc, *this); 1323 Tok.setKind(tok::string_literal); 1324 Tok.setLength(strlen("\"hh:mm:ss\"")); 1325 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(), 1326 Tok.getLocation(), 1327 Tok.getLength())); 1328 return; 1329 } else if (II == Ident__INCLUDE_LEVEL__) { 1330 // Compute the presumed include depth of this token. This can be affected 1331 // by GNU line markers. 1332 unsigned Depth = 0; 1333 1334 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation()); 1335 if (PLoc.isValid()) { 1336 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 1337 for (; PLoc.isValid(); ++Depth) 1338 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc()); 1339 } 1340 1341 // __INCLUDE_LEVEL__ expands to a simple numeric value. 1342 OS << Depth; 1343 Tok.setKind(tok::numeric_constant); 1344 } else if (II == Ident__TIMESTAMP__) { 1345 Diag(Tok.getLocation(), diag::warn_pp_date_time); 1346 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be 1347 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime. 1348 1349 // Get the file that we are lexing out of. If we're currently lexing from 1350 // a macro, dig into the include stack. 1351 const FileEntry *CurFile = nullptr; 1352 PreprocessorLexer *TheLexer = getCurrentFileLexer(); 1353 1354 if (TheLexer) 1355 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID()); 1356 1357 const char *Result; 1358 if (CurFile) { 1359 time_t TT = CurFile->getModificationTime(); 1360 struct tm *TM = localtime(&TT); 1361 Result = asctime(TM); 1362 } else { 1363 Result = "??? ??? ?? ??:??:?? ????\n"; 1364 } 1365 // Surround the string with " and strip the trailing newline. 1366 OS << '"' << StringRef(Result).drop_back() << '"'; 1367 Tok.setKind(tok::string_literal); 1368 } else if (II == Ident__COUNTER__) { 1369 // __COUNTER__ expands to a simple numeric value. 1370 OS << CounterValue++; 1371 Tok.setKind(tok::numeric_constant); 1372 } else if (II == Ident__has_feature || 1373 II == Ident__has_extension || 1374 II == Ident__has_builtin || 1375 II == Ident__is_identifier || 1376 II == Ident__has_attribute) { 1377 // The argument to these builtins should be a parenthesized identifier. 1378 SourceLocation StartLoc = Tok.getLocation(); 1379 1380 bool IsValid = false; 1381 IdentifierInfo *FeatureII = nullptr; 1382 1383 // Read the '('. 1384 LexUnexpandedToken(Tok); 1385 if (Tok.is(tok::l_paren)) { 1386 // Read the identifier 1387 LexUnexpandedToken(Tok); 1388 if ((FeatureII = Tok.getIdentifierInfo())) { 1389 // Read the ')'. 1390 LexUnexpandedToken(Tok); 1391 if (Tok.is(tok::r_paren)) 1392 IsValid = true; 1393 } 1394 } 1395 1396 bool Value = false; 1397 if (!IsValid) 1398 Diag(StartLoc, diag::err_feature_check_malformed); 1399 else if (II == Ident__is_identifier) 1400 Value = FeatureII->getTokenID() == tok::identifier; 1401 else if (II == Ident__has_builtin) { 1402 // Check for a builtin is trivial. 1403 Value = FeatureII->getBuiltinID() != 0; 1404 } else if (II == Ident__has_attribute) 1405 Value = hasAttribute(AttrSyntax::Generic, nullptr, FeatureII, 1406 getTargetInfo().getTriple(), getLangOpts()); 1407 else if (II == Ident__has_extension) 1408 Value = HasExtension(*this, FeatureII); 1409 else { 1410 assert(II == Ident__has_feature && "Must be feature check"); 1411 Value = HasFeature(*this, FeatureII); 1412 } 1413 1414 OS << (int)Value; 1415 if (IsValid) 1416 Tok.setKind(tok::numeric_constant); 1417 } else if (II == Ident__has_include || 1418 II == Ident__has_include_next) { 1419 // The argument to these two builtins should be a parenthesized 1420 // file name string literal using angle brackets (<>) or 1421 // double-quotes (""). 1422 bool Value; 1423 if (II == Ident__has_include) 1424 Value = EvaluateHasInclude(Tok, II, *this); 1425 else 1426 Value = EvaluateHasIncludeNext(Tok, II, *this); 1427 OS << (int)Value; 1428 if (Tok.is(tok::r_paren)) 1429 Tok.setKind(tok::numeric_constant); 1430 } else if (II == Ident__has_warning) { 1431 // The argument should be a parenthesized string literal. 1432 // The argument to these builtins should be a parenthesized identifier. 1433 SourceLocation StartLoc = Tok.getLocation(); 1434 bool IsValid = false; 1435 bool Value = false; 1436 // Read the '('. 1437 LexUnexpandedToken(Tok); 1438 do { 1439 if (Tok.isNot(tok::l_paren)) { 1440 Diag(StartLoc, diag::err_warning_check_malformed); 1441 break; 1442 } 1443 1444 LexUnexpandedToken(Tok); 1445 std::string WarningName; 1446 SourceLocation StrStartLoc = Tok.getLocation(); 1447 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'", 1448 /*MacroExpansion=*/false)) { 1449 // Eat tokens until ')'. 1450 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) && 1451 Tok.isNot(tok::eof)) 1452 LexUnexpandedToken(Tok); 1453 break; 1454 } 1455 1456 // Is the end a ')'? 1457 if (!(IsValid = Tok.is(tok::r_paren))) { 1458 Diag(StartLoc, diag::err_warning_check_malformed); 1459 break; 1460 } 1461 1462 // FIXME: Should we accept "-R..." flags here, or should that be handled 1463 // by a separate __has_remark? 1464 if (WarningName.size() < 3 || WarningName[0] != '-' || 1465 WarningName[1] != 'W') { 1466 Diag(StrStartLoc, diag::warn_has_warning_invalid_option); 1467 break; 1468 } 1469 1470 // Finally, check if the warning flags maps to a diagnostic group. 1471 // We construct a SmallVector here to talk to getDiagnosticIDs(). 1472 // Although we don't use the result, this isn't a hot path, and not 1473 // worth special casing. 1474 SmallVector<diag::kind, 10> Diags; 1475 Value = !getDiagnostics().getDiagnosticIDs()-> 1476 getDiagnosticsInGroup(diag::Flavor::WarningOrError, 1477 WarningName.substr(2), Diags); 1478 } while (false); 1479 1480 OS << (int)Value; 1481 if (IsValid) 1482 Tok.setKind(tok::numeric_constant); 1483 } else if (II == Ident__building_module) { 1484 // The argument to this builtin should be an identifier. The 1485 // builtin evaluates to 1 when that identifier names the module we are 1486 // currently building. 1487 OS << (int)EvaluateBuildingModule(Tok, II, *this); 1488 Tok.setKind(tok::numeric_constant); 1489 } else if (II == Ident__MODULE__) { 1490 // The current module as an identifier. 1491 OS << getLangOpts().CurrentModule; 1492 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule); 1493 Tok.setIdentifierInfo(ModuleII); 1494 Tok.setKind(ModuleII->getTokenID()); 1495 } else if (II == Ident__identifier) { 1496 SourceLocation Loc = Tok.getLocation(); 1497 1498 // We're expecting '__identifier' '(' identifier ')'. Try to recover 1499 // if the parens are missing. 1500 LexNonComment(Tok); 1501 if (Tok.isNot(tok::l_paren)) { 1502 // No '(', use end of last token. 1503 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after) 1504 << II << tok::l_paren; 1505 // If the next token isn't valid as our argument, we can't recover. 1506 if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) 1507 Tok.setKind(tok::identifier); 1508 return; 1509 } 1510 1511 SourceLocation LParenLoc = Tok.getLocation(); 1512 LexNonComment(Tok); 1513 1514 if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) 1515 Tok.setKind(tok::identifier); 1516 else { 1517 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier) 1518 << Tok.getKind(); 1519 // Don't walk past anything that's not a real token. 1520 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation()) 1521 return; 1522 } 1523 1524 // Discard the ')', preserving 'Tok' as our result. 1525 Token RParen; 1526 LexNonComment(RParen); 1527 if (RParen.isNot(tok::r_paren)) { 1528 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after) 1529 << Tok.getKind() << tok::r_paren; 1530 Diag(LParenLoc, diag::note_matching) << tok::l_paren; 1531 } 1532 return; 1533 } else { 1534 llvm_unreachable("Unknown identifier!"); 1535 } 1536 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation()); 1537 } 1538 1539 void Preprocessor::markMacroAsUsed(MacroInfo *MI) { 1540 // If the 'used' status changed, and the macro requires 'unused' warning, 1541 // remove its SourceLocation from the warn-for-unused-macro locations. 1542 if (MI->isWarnIfUnused() && !MI->isUsed()) 1543 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc()); 1544 MI->setIsUsed(true); 1545 } 1546