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