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