blob: 3566c3429fea4011f9ef3473885dbb359306ce89 [file] [log] [blame]
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001//===--- 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//
James Dennett32740042013-12-02 17:39:27 +000010// This file implements the top level handling of macro expansion for the
Joao Matosc0d4c1b2012-08-31 21:34:27 +000011// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
Aaron Ballman2fbf9942014-03-31 13:14:44 +000015#include "clang/Basic/Attributes.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000016#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000017#include "clang/Lex/CodeCompletionHandler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000018#include "clang/Lex/DirectoryLookup.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000019#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000021#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/MacroInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "llvm/ADT/STLExtras.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000025#include "llvm/ADT/SmallString.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000026#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000027#include "llvm/Config/llvm-config.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000028#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000029#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "llvm/Support/raw_ostream.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000031#include <cstdio>
32#include <ctime>
33using namespace clang;
34
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000035MacroDirective *
Richard Smith20e883e2015-04-29 23:20:19 +000036Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
37 if (!II->hadMacroDefinition())
38 return nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +000039 auto Pos = CurSubmoduleState->Macros.find(II);
40 return Pos == CurSubmoduleState->Macros.end() ? nullptr
41 : Pos->second.getLatest();
Joao Matosc0d4c1b2012-08-31 21:34:27 +000042}
43
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000044void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000045 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000046 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000047
Richard Smith04765ae2015-05-21 01:20:10 +000048 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000049 auto *OldMD = StoredMD.getLatest();
50 MD->setPrevious(OldMD);
51 StoredMD.setLatest(MD);
Richard Smith753e0072015-04-27 23:21:38 +000052 StoredMD.overrideActiveModuleMacros(*this, II);
Richard Smithb8b2ed62015-04-23 18:18:26 +000053
Richard Smith802182f2016-02-23 23:20:51 +000054 if (needModuleMacros()) {
55 // Track that we created a new macro directive, so we know we should
56 // consider building a ModuleMacro for it when we get to the end of
57 // the module.
58 PendingModuleMacroNames.push_back(II);
59 }
60
Richard Smithb8b2ed62015-04-23 18:18:26 +000061 // Set up the identifier as having associated macro history.
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000062 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000063 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000064 II->setHasMacroDefinition(false);
Richard Smith3981b172015-04-30 02:16:23 +000065 if (II->isFromAST())
Joao Matosc0d4c1b2012-08-31 21:34:27 +000066 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000067}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000068
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000069void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
70 MacroDirective *MD) {
71 assert(II && MD);
Richard Smith04765ae2015-05-21 01:20:10 +000072 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000073 assert(!StoredMD.getLatest() &&
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000074 "the macro history was modified before initializing it from a pch");
75 StoredMD = MD;
76 // Setup the identifier as having associated macro history.
77 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000078 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000079 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000080}
81
Richard Smithb8b2ed62015-04-23 18:18:26 +000082ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
Richard Smithe56c8bc2015-04-22 00:26:11 +000083 MacroInfo *Macro,
84 ArrayRef<ModuleMacro *> Overrides,
85 bool &New) {
86 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +000087 ModuleMacro::Profile(ID, Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +000088
89 void *InsertPos;
90 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
91 New = false;
92 return MM;
93 }
94
Richard Smithb8b2ed62015-04-23 18:18:26 +000095 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
Richard Smithe56c8bc2015-04-22 00:26:11 +000096 ModuleMacros.InsertNode(MM, InsertPos);
97
98 // Each overridden macro is now overridden by one more macro.
99 bool HidAny = false;
100 for (auto *O : Overrides) {
101 HidAny |= (O->NumOverriddenBy == 0);
102 ++O->NumOverriddenBy;
103 }
104
105 // If we were the first overrider for any macro, it's no longer a leaf.
106 auto &LeafMacros = LeafModuleMacros[II];
107 if (HidAny) {
108 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
109 [](ModuleMacro *MM) {
110 return MM->NumOverriddenBy != 0;
111 }),
112 LeafMacros.end());
113 }
114
115 // The new macro is always a leaf macro.
116 LeafMacros.push_back(MM);
Richard Smith20e883e2015-04-29 23:20:19 +0000117 // The identifier now has defined macros (that may or may not be visible).
118 II->setHasMacroDefinition(true);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000119
120 New = true;
121 return MM;
122}
123
Richard Smithb8b2ed62015-04-23 18:18:26 +0000124ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) {
Richard Smith5dbef922015-04-22 02:09:43 +0000125 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000126 ModuleMacro::Profile(ID, Mod, II);
Richard Smith5dbef922015-04-22 02:09:43 +0000127
128 void *InsertPos;
129 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
130}
131
Richard Smith20e883e2015-04-29 23:20:19 +0000132void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
Richard Smith753e0072015-04-27 23:21:38 +0000133 ModuleMacroInfo &Info) {
Richard Smith04765ae2015-05-21 01:20:10 +0000134 assert(Info.ActiveModuleMacrosGeneration !=
135 CurSubmoduleState->VisibleModules.getGeneration() &&
Richard Smith753e0072015-04-27 23:21:38 +0000136 "don't need to update this macro name info");
Richard Smith04765ae2015-05-21 01:20:10 +0000137 Info.ActiveModuleMacrosGeneration =
138 CurSubmoduleState->VisibleModules.getGeneration();
Richard Smith753e0072015-04-27 23:21:38 +0000139
140 auto Leaf = LeafModuleMacros.find(II);
141 if (Leaf == LeafModuleMacros.end()) {
142 // No imported macros at all: nothing to do.
143 return;
144 }
145
146 Info.ActiveModuleMacros.clear();
147
148 // Every macro that's locally overridden is overridden by a visible macro.
149 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
150 for (auto *O : Info.OverriddenMacros)
151 NumHiddenOverrides[O] = -1;
152
153 // Collect all macros that are not overridden by a visible macro.
Richard Smith938d7012015-09-16 00:55:50 +0000154 llvm::SmallVector<ModuleMacro *, 16> Worklist;
155 for (auto *LeafMM : Leaf->second) {
156 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
157 if (NumHiddenOverrides.lookup(LeafMM) == 0)
158 Worklist.push_back(LeafMM);
159 }
Richard Smith753e0072015-04-27 23:21:38 +0000160 while (!Worklist.empty()) {
161 auto *MM = Worklist.pop_back_val();
Richard Smith04765ae2015-05-21 01:20:10 +0000162 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
Richard Smith753e0072015-04-27 23:21:38 +0000163 // We only care about collecting definitions; undefinitions only act
164 // to override other definitions.
165 if (MM->getMacroInfo())
166 Info.ActiveModuleMacros.push_back(MM);
167 } else {
168 for (auto *O : MM->overrides())
169 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
170 Worklist.push_back(O);
171 }
172 }
Richard Smith20e883e2015-04-29 23:20:19 +0000173 // Our reverse postorder walk found the macros in reverse order.
174 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
Richard Smith753e0072015-04-27 23:21:38 +0000175
176 // Determine whether the macro name is ambiguous.
Richard Smith753e0072015-04-27 23:21:38 +0000177 MacroInfo *MI = nullptr;
Richard Smith20e883e2015-04-29 23:20:19 +0000178 bool IsSystemMacro = true;
179 bool IsAmbiguous = false;
180 if (auto *MD = Info.MD) {
181 while (MD && isa<VisibilityMacroDirective>(MD))
182 MD = MD->getPrevious();
183 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
184 MI = DMD->getInfo();
185 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
186 }
Richard Smith753e0072015-04-27 23:21:38 +0000187 }
188 for (auto *Active : Info.ActiveModuleMacros) {
189 auto *NewMI = Active->getMacroInfo();
190
191 // Before marking the macro as ambiguous, check if this is a case where
192 // both macros are in system headers. If so, we trust that the system
193 // did not get it wrong. This also handles cases where Clang's own
194 // headers have a different spelling of certain system macros:
195 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
196 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
197 //
198 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
199 // overrides the system limits.h's macros, so there's no conflict here.
Richard Smith20e883e2015-04-29 23:20:19 +0000200 if (MI && NewMI != MI &&
201 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
202 IsAmbiguous = true;
203 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
204 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
205 MI = NewMI;
Richard Smith753e0072015-04-27 23:21:38 +0000206 }
Richard Smith20e883e2015-04-29 23:20:19 +0000207 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
Richard Smith753e0072015-04-27 23:21:38 +0000208}
209
Richard Smith3ffa61d2015-04-30 23:10:40 +0000210void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
211 ArrayRef<ModuleMacro*> Leaf;
212 auto LeafIt = LeafModuleMacros.find(II);
213 if (LeafIt != LeafModuleMacros.end())
214 Leaf = LeafIt->second;
215 const MacroState *State = nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +0000216 auto Pos = CurSubmoduleState->Macros.find(II);
217 if (Pos != CurSubmoduleState->Macros.end())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000218 State = &Pos->second;
219
220 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
221 if (State && State->isAmbiguous(*this, II))
222 llvm::errs() << " ambiguous";
Richard Smithd0014bf2015-04-30 23:42:10 +0000223 if (State && !State->getOverriddenMacros().empty()) {
Richard Smith3ffa61d2015-04-30 23:10:40 +0000224 llvm::errs() << " overrides";
225 for (auto *O : State->getOverriddenMacros())
226 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
227 }
228 llvm::errs() << "\n";
229
230 // Dump local macro directives.
231 for (auto *MD = State ? State->getLatest() : nullptr; MD;
232 MD = MD->getPrevious()) {
233 llvm::errs() << " ";
234 MD->dump();
235 }
236
237 // Dump module macros.
238 llvm::DenseSet<ModuleMacro*> Active;
239 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
240 Active.insert(MM);
241 llvm::DenseSet<ModuleMacro*> Visited;
242 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
243 while (!Worklist.empty()) {
244 auto *MM = Worklist.pop_back_val();
245 llvm::errs() << " ModuleMacro " << MM << " "
246 << MM->getOwningModule()->getFullModuleName();
247 if (!MM->getMacroInfo())
248 llvm::errs() << " undef";
249
250 if (Active.count(MM))
251 llvm::errs() << " active";
Richard Smith04765ae2015-05-21 01:20:10 +0000252 else if (!CurSubmoduleState->VisibleModules.isVisible(
253 MM->getOwningModule()))
Richard Smith3ffa61d2015-04-30 23:10:40 +0000254 llvm::errs() << " hidden";
Richard Smith42413142015-05-15 20:05:43 +0000255 else if (MM->getMacroInfo())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000256 llvm::errs() << " overridden";
257
258 if (!MM->overrides().empty()) {
259 llvm::errs() << " overrides";
260 for (auto *O : MM->overrides()) {
261 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
262 if (Visited.insert(O).second)
263 Worklist.push_back(O);
264 }
265 }
266 llvm::errs() << "\n";
267 if (auto *MI = MM->getMacroInfo()) {
268 llvm::errs() << " ";
269 MI->dump();
270 llvm::errs() << "\n";
271 }
272 }
273}
274
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000275/// RegisterBuiltinMacro - Register the specified identifier in the identifier
276/// table and mark it as a builtin macro to be expanded.
277static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
278 // Get the identifier.
279 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
280
281 // Mark it as being a macro that is builtin.
282 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
283 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000284 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000285 return Id;
286}
287
288
289/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
290/// identifier table.
291void Preprocessor::RegisterBuiltinMacros() {
292 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
293 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
294 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
295 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
296 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
297 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
298
Aaron Ballmana0344c52014-11-14 13:44:02 +0000299 // C++ Standing Document Extensions.
Aaron Ballman416b1272015-05-11 14:09:50 +0000300 if (LangOpts.CPlusPlus)
301 Ident__has_cpp_attribute =
302 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
303 else
304 Ident__has_cpp_attribute = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +0000305
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000306 // GCC Extensions.
307 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
308 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
309 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
310
Richard Smithae385082014-03-15 00:06:08 +0000311 // Microsoft Extensions.
312 if (LangOpts.MicrosoftExt) {
313 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
314 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
315 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000316 Ident__identifier = nullptr;
317 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000318 }
319
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000320 // Clang Extensions.
321 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
322 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
323 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
324 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000325 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000326 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
327 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
328 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000329 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000330
Douglas Gregorc83de302012-09-25 15:44:52 +0000331 // Modules.
Richard Smithe0fa4c82016-04-21 01:46:37 +0000332 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
333 if (!LangOpts.CurrentModule.empty())
334 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
335 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000336 Ident__MODULE__ = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000337}
338
339/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
340/// in its expansion, currently expands to that token literally.
341static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
342 const IdentifierInfo *MacroIdent,
343 Preprocessor &PP) {
344 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
345
346 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000347 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000348
349 // If the information about this identifier is out of date, update it from
350 // the external source.
351 if (II->isOutOfDate())
352 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
353
354 // If the identifier is a macro, and if that macro is enabled, it may be
355 // expanded so it's not a trivial expansion.
Richard Smith20e883e2015-04-29 23:20:19 +0000356 if (auto *ExpansionMI = PP.getMacroInfo(II))
Richard Smith3d5925b2015-04-29 23:26:13 +0000357 if (ExpansionMI->isEnabled() &&
Richard Smith20e883e2015-04-29 23:20:19 +0000358 // Fast expanding "#define X X" is ok, because X would be disabled.
359 II != MacroIdent)
360 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000361
362 // If this is an object-like macro invocation, it is safe to trivially expand
363 // it.
364 if (MI->isObjectLike()) return true;
365
366 // If this is a function-like macro invocation, it's safe to trivially expand
367 // as long as the identifier is not a macro argument.
Daniel Marjamakie4770da2015-05-29 09:15:24 +0000368 return std::find(MI->arg_begin(), MI->arg_end(), II) == MI->arg_end();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000369
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000370}
371
372
373/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
374/// lexed is a '('. If so, consume the token and return true, if not, this
375/// method should have no observable side-effect on the lexed tokens.
376bool Preprocessor::isNextPPTokenLParen() {
377 // Do some quick tests for rejection cases.
378 unsigned Val;
379 if (CurLexer)
380 Val = CurLexer->isNextPPTokenLParen();
381 else if (CurPTHLexer)
382 Val = CurPTHLexer->isNextPPTokenLParen();
383 else
384 Val = CurTokenLexer->isNextTokenLParen();
385
386 if (Val == 2) {
387 // We have run off the end. If it's a source file we don't
388 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
389 // macro stack.
390 if (CurPPLexer)
391 return false;
392 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
393 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
394 if (Entry.TheLexer)
395 Val = Entry.TheLexer->isNextPPTokenLParen();
396 else if (Entry.ThePTHLexer)
397 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
398 else
399 Val = Entry.TheTokenLexer->isNextTokenLParen();
400
401 if (Val != 2)
402 break;
403
404 // Ran off the end of a source file?
405 if (Entry.ThePPLexer)
406 return false;
407 }
408 }
409
410 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
411 // have found something that isn't a '(' or we found the end of the
412 // translation unit. In either case, return false.
413 return Val == 1;
414}
415
416/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
417/// expanded as a macro, handle it and return the next token as 'Identifier'.
418bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000419 const MacroDefinition &M) {
420 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000421
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000422 // If this is a macro expansion in the "#if !defined(x)" line for the file,
423 // then the macro could expand to different things in other contexts, we need
424 // to disable the optimization in this case.
425 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
426
427 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
428 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000429 if (Callbacks)
430 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
431 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000432 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000433 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000434 }
435
436 /// Args - If this is a function-like macro expansion, this contains,
437 /// for each macro argument, the list of tokens that were provided to the
438 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000439 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000440
441 // Remember where the end of the expansion occurred. For an object-like
442 // macro, this is the identifier. For a function-like macro, this is the ')'.
443 SourceLocation ExpansionEnd = Identifier.getLocation();
444
445 // If this is a function-like macro, read the arguments.
446 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000447 // Remember that we are now parsing the arguments to a macro invocation.
448 // Preprocessor directives used inside macro arguments are not portable, and
449 // this enables the warning.
450 InMacroArgs = true;
451 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
452
453 // Finished parsing args.
454 InMacroArgs = false;
455
456 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000457 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000458
459 ++NumFnMacroExpanded;
460 } else {
461 ++NumMacroExpanded;
462 }
463
464 // Notice that this macro has been used.
465 markMacroAsUsed(MI);
466
467 // Remember where the token is expanded.
468 SourceLocation ExpandLoc = Identifier.getLocation();
469 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
470
471 if (Callbacks) {
472 if (InMacroArgs) {
473 // We can have macro expansion inside a conditional directive while
474 // reading the function macro arguments. To ensure, in that case, that
475 // MacroExpands callbacks still happen in source order, queue this
476 // callback to have it happen after the function macro callback.
477 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000478 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000479 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000480 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000481 if (!DelayedMacroExpandsCallbacks.empty()) {
482 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
483 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000484 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000485 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
486 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000487 }
488 DelayedMacroExpandsCallbacks.clear();
489 }
490 }
491 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000492
493 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000494 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000495 Diag(Identifier, diag::warn_pp_ambiguous_macro)
496 << Identifier.getIdentifierInfo();
497 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
498 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000499 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
500 if (OtherMI != MI)
501 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
502 << Identifier.getIdentifierInfo();
503 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000504 }
505
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000506 // If we started lexing a macro, enter the macro expansion body.
507
508 // If this macro expands to no tokens, don't bother to push it onto the
509 // expansion stack, only to take it right back off.
510 if (MI->getNumTokens() == 0) {
511 // No need for arg info.
512 if (Args) Args->destroy(*this);
513
Eli Friedman0834a4b2013-09-19 00:41:32 +0000514 // Propagate whitespace info as if we had pushed, then popped,
515 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000516 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000517 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000518 ++NumFastMacroExpanded;
519 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000520 } else if (MI->getNumTokens() == 1 &&
521 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
522 *this)) {
523 // Otherwise, if this macro expands into a single trivially-expanded
524 // token: expand it now. This handles common cases like
525 // "#define VAL 42".
526
527 // No need for arg info.
528 if (Args) Args->destroy(*this);
529
530 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
531 // identifier to the expanded token.
532 bool isAtStartOfLine = Identifier.isAtStartOfLine();
533 bool hasLeadingSpace = Identifier.hasLeadingSpace();
534
535 // Replace the result token.
536 Identifier = MI->getReplacementToken(0);
537
538 // Restore the StartOfLine/LeadingSpace markers.
539 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
540 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
541
542 // Update the tokens location to include both its expansion and physical
543 // locations.
544 SourceLocation Loc =
545 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
546 ExpansionEnd,Identifier.getLength());
547 Identifier.setLocation(Loc);
548
549 // If this is a disabled macro or #define X X, we must mark the result as
550 // unexpandable.
551 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
552 if (MacroInfo *NewMI = getMacroInfo(NewII))
553 if (!NewMI->isEnabled() || NewMI == MI) {
554 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000555 // Don't warn for "#define X X" like "#define bool bool" from
556 // stdbool.h.
557 if (NewMI != MI || MI->isFunctionLike())
558 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000559 }
560 }
561
562 // Since this is not an identifier token, it can't be macro expanded, so
563 // we're done.
564 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000565 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000566 }
567
568 // Start expanding the macro.
569 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000570 return false;
571}
572
Richard Trieu79b45382013-07-23 18:01:49 +0000573enum Bracket {
574 Brace,
575 Paren
576};
577
578/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
579/// token vector are properly nested.
580static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
581 SmallVector<Bracket, 8> Brackets;
582 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
583 E = Tokens.end();
584 I != E; ++I) {
585 if (I->is(tok::l_paren)) {
586 Brackets.push_back(Paren);
587 } else if (I->is(tok::r_paren)) {
588 if (Brackets.empty() || Brackets.back() == Brace)
589 return false;
590 Brackets.pop_back();
591 } else if (I->is(tok::l_brace)) {
592 Brackets.push_back(Brace);
593 } else if (I->is(tok::r_brace)) {
594 if (Brackets.empty() || Brackets.back() == Paren)
595 return false;
596 Brackets.pop_back();
597 }
598 }
Alexander Kornienkoa26c4952015-12-28 15:30:42 +0000599 return Brackets.empty();
Richard Trieu79b45382013-07-23 18:01:49 +0000600}
601
602/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
603/// vector of tokens in NewTokens. The new number of arguments will be placed
604/// in NumArgs and the ranges which need to surrounded in parentheses will be
605/// in ParenHints.
606/// Returns false if the token stream cannot be changed. If this is because
607/// of an initializer list starting a macro argument, the range of those
608/// initializer lists will be place in InitLists.
609static bool GenerateNewArgTokens(Preprocessor &PP,
610 SmallVectorImpl<Token> &OldTokens,
611 SmallVectorImpl<Token> &NewTokens,
612 unsigned &NumArgs,
613 SmallVectorImpl<SourceRange> &ParenHints,
614 SmallVectorImpl<SourceRange> &InitLists) {
615 if (!CheckMatchedBrackets(OldTokens))
616 return false;
617
618 // Once it is known that the brackets are matched, only a simple count of the
619 // braces is needed.
620 unsigned Braces = 0;
621
622 // First token of a new macro argument.
623 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
624
625 // First closing brace in a new macro argument. Used to generate
626 // SourceRanges for InitLists.
627 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
628 NumArgs = 0;
629 Token TempToken;
630 // Set to true when a macro separator token is found inside a braced list.
631 // If true, the fixed argument spans multiple old arguments and ParenHints
632 // will be updated.
633 bool FoundSeparatorToken = false;
634 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
635 E = OldTokens.end();
636 I != E; ++I) {
637 if (I->is(tok::l_brace)) {
638 ++Braces;
639 } else if (I->is(tok::r_brace)) {
640 --Braces;
641 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
642 ClosingBrace = I;
643 } else if (I->is(tok::eof)) {
644 // EOF token is used to separate macro arguments
645 if (Braces != 0) {
646 // Assume comma separator is actually braced list separator and change
647 // it back to a comma.
648 FoundSeparatorToken = true;
649 I->setKind(tok::comma);
650 I->setLength(1);
651 } else { // Braces == 0
652 // Separator token still separates arguments.
653 ++NumArgs;
654
655 // If the argument starts with a brace, it can't be fixed with
656 // parentheses. A different diagnostic will be given.
657 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
658 InitLists.push_back(
659 SourceRange(ArgStartIterator->getLocation(),
660 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
661 ClosingBrace = E;
662 }
663
664 // Add left paren
665 if (FoundSeparatorToken) {
666 TempToken.startToken();
667 TempToken.setKind(tok::l_paren);
668 TempToken.setLocation(ArgStartIterator->getLocation());
669 TempToken.setLength(0);
670 NewTokens.push_back(TempToken);
671 }
672
673 // Copy over argument tokens
674 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
675
676 // Add right paren and store the paren locations in ParenHints
677 if (FoundSeparatorToken) {
678 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
679 TempToken.startToken();
680 TempToken.setKind(tok::r_paren);
681 TempToken.setLocation(Loc);
682 TempToken.setLength(0);
683 NewTokens.push_back(TempToken);
684 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
685 Loc));
686 }
687
688 // Copy separator token
689 NewTokens.push_back(*I);
690
691 // Reset values
692 ArgStartIterator = I + 1;
693 FoundSeparatorToken = false;
694 }
695 }
696 }
697
698 return !ParenHints.empty() && InitLists.empty();
699}
700
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000701/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
702/// token is the '(' of the macro, this method is invoked to read all of the
703/// actual arguments specified for the macro invocation. This returns null on
704/// error.
705MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
706 MacroInfo *MI,
707 SourceLocation &MacroEnd) {
708 // The number of fixed arguments to parse.
709 unsigned NumFixedArgsLeft = MI->getNumArgs();
710 bool isVariadic = MI->isVariadic();
711
712 // Outer loop, while there are more arguments, keep reading them.
713 Token Tok;
714
715 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
716 // an argument value in a macro could expand to ',' or '(' or ')'.
717 LexUnexpandedToken(Tok);
718 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
719
720 // ArgTokens - Build up a list of tokens that make up each argument. Each
721 // argument is separated by an EOF token. Use a SmallVector so we can avoid
722 // heap allocations in the common case.
723 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000724 bool ContainsCodeCompletionTok = false;
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000725 bool FoundElidedComma = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000726
Richard Trieu79b45382013-07-23 18:01:49 +0000727 SourceLocation TooManyArgsLoc;
728
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000729 unsigned NumActuals = 0;
730 while (Tok.isNot(tok::r_paren)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000731 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000732 break;
733
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000734 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000735 "only expect argument separators here");
736
737 unsigned ArgTokenStart = ArgTokens.size();
738 SourceLocation ArgStartLoc = Tok.getLocation();
739
740 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
741 // that we already consumed the first one.
742 unsigned NumParens = 0;
743
744 while (1) {
745 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
746 // an argument value in a macro could expand to ',' or '(' or ')'.
747 LexUnexpandedToken(Tok);
748
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000749 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000750 if (!ContainsCodeCompletionTok) {
751 Diag(MacroName, diag::err_unterm_macro_invoc);
752 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
753 << MacroName.getIdentifierInfo();
754 // Do not lose the EOF/EOD. Return it to the client.
755 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000756 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000757 }
David Blaikie2eabcc92016-02-09 18:52:09 +0000758 // Do not lose the EOF/EOD.
759 auto Toks = llvm::make_unique<Token[]>(1);
760 Toks[0] = Tok;
761 EnterTokenStream(std::move(Toks), 1, true);
762 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000763 } else if (Tok.is(tok::r_paren)) {
764 // If we found the ) token, the macro arg list is done.
765 if (NumParens-- == 0) {
766 MacroEnd = Tok.getLocation();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000767 if (!ArgTokens.empty() &&
768 ArgTokens.back().commaAfterElided()) {
769 FoundElidedComma = true;
770 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000771 break;
772 }
773 } else if (Tok.is(tok::l_paren)) {
774 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000775 } else if (Tok.is(tok::comma) && NumParens == 0 &&
776 !(Tok.getFlags() & Token::IgnoredComma)) {
777 // In Microsoft-compatibility mode, single commas from nested macro
778 // expansions should not be considered as argument separators. We test
779 // for this with the IgnoredComma token flag above.
780
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000781 // Comma ends this argument if there are more fixed arguments expected.
782 // However, if this is a variadic macro, and this is part of the
783 // variadic part, then the comma is just an argument token.
784 if (!isVariadic) break;
785 if (NumFixedArgsLeft > 1)
786 break;
787 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
788 // If this is a comment token in the argument list and we're just in
789 // -C mode (not -CC mode), discard the comment.
790 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000791 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000792 // Reading macro arguments can cause macros that we are currently
793 // expanding from to be popped off the expansion stack. Doing so causes
794 // them to be reenabled for expansion. Here we record whether any
795 // identifiers we lex as macro arguments correspond to disabled macros.
796 // If so, we mark the token as noexpand. This is a subtle aspect of
797 // C99 6.10.3.4p2.
798 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
799 if (!MI->isEnabled())
800 Tok.setFlag(Token::DisableExpand);
801 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000802 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000803 if (CodeComplete)
804 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
805 MI, NumActuals);
806 // Don't mark that we reached the code-completion point because the
807 // parser is going to handle the token and there will be another
808 // code-completion callback.
809 }
810
811 ArgTokens.push_back(Tok);
812 }
813
814 // If this was an empty argument list foo(), don't add this as an empty
815 // argument.
816 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
817 break;
818
819 // If this is not a variadic macro, and too many args were specified, emit
820 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000821 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000822 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000823 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
824 else
825 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000826 }
827
Richard Trieu79b45382013-07-23 18:01:49 +0000828 // Empty arguments are standard in C99 and C++0x, and are supported as an
829 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000830 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000831 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000832 diag::warn_cxx98_compat_empty_fnmacro_arg :
833 diag::ext_empty_fnmacro_arg);
834
835 // Add a marker EOF token to the end of the token list for this argument.
836 Token EOFTok;
837 EOFTok.startToken();
838 EOFTok.setKind(tok::eof);
839 EOFTok.setLocation(Tok.getLocation());
840 EOFTok.setLength(0);
841 ArgTokens.push_back(EOFTok);
842 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000843 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000844 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000845 }
846
847 // Okay, we either found the r_paren. Check to see if we parsed too few
848 // arguments.
849 unsigned MinArgsExpected = MI->getNumArgs();
850
Richard Trieu79b45382013-07-23 18:01:49 +0000851 // If this is not a variadic macro, and too many args were specified, emit
852 // an error.
853 if (!isVariadic && NumActuals > MinArgsExpected &&
854 !ContainsCodeCompletionTok) {
855 // Emit the diagnostic at the macro name in case there is a missing ).
856 // Emitting it at the , could be far away from the macro name.
857 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
858 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
859 << MacroName.getIdentifierInfo();
860
861 // Commas from braced initializer lists will be treated as argument
862 // separators inside macros. Attempt to correct for this with parentheses.
863 // TODO: See if this can be generalized to angle brackets for templates
864 // inside macro arguments.
865
Bob Wilson57217352013-07-27 21:59:57 +0000866 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000867 unsigned FixedNumArgs = 0;
868 SmallVector<SourceRange, 4> ParenHints, InitLists;
869 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
870 ParenHints, InitLists)) {
871 if (!InitLists.empty()) {
872 DiagnosticBuilder DB =
873 Diag(MacroName,
874 diag::note_init_list_at_beginning_of_macro_argument);
Craig Toppere335f252015-10-04 04:53:55 +0000875 for (SourceRange Range : InitLists)
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000876 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000877 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000878 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000879 }
880 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000881 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000882
883 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Craig Toppere335f252015-10-04 04:53:55 +0000884 for (SourceRange ParenLocation : ParenHints) {
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000885 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
886 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000887 }
888 ArgTokens.swap(FixedArgTokens);
889 NumActuals = FixedNumArgs;
890 }
891
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000892 // See MacroArgs instance var for description of this.
893 bool isVarargsElided = false;
894
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000895 if (ContainsCodeCompletionTok) {
896 // Recover from not-fully-formed macro invocation during code-completion.
897 Token EOFTok;
898 EOFTok.startToken();
899 EOFTok.setKind(tok::eof);
900 EOFTok.setLocation(Tok.getLocation());
901 EOFTok.setLength(0);
902 for (; NumActuals < MinArgsExpected; ++NumActuals)
903 ArgTokens.push_back(EOFTok);
904 }
905
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000906 if (NumActuals < MinArgsExpected) {
907 // There are several cases where too few arguments is ok, handle them now.
908 if (NumActuals == 0 && MinArgsExpected == 1) {
909 // #define A(X) or #define A(...) ---> A()
910
911 // If there is exactly one argument, and that argument is missing,
912 // then we have an empty "()" argument empty list. This is fine, even if
913 // the macro expects one argument (the argument is just empty).
914 isVarargsElided = MI->isVariadic();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000915 } else if ((FoundElidedComma || MI->isVariadic()) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000916 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
917 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
918 // Varargs where the named vararg parameter is missing: OK as extension.
919 // #define A(x, ...)
920 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000921 //
922 // If the macro contains the comma pasting extension, the diagnostic
923 // is suppressed; we know we'll get another diagnostic later.
924 if (!MI->hasCommaPasting()) {
925 Diag(Tok, diag::ext_missing_varargs_arg);
926 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
927 << MacroName.getIdentifierInfo();
928 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000929
930 // Remember this occurred, allowing us to elide the comma when used for
931 // cases like:
932 // #define A(x, foo...) blah(a, ## foo)
933 // #define B(x, ...) blah(a, ## __VA_ARGS__)
934 // #define C(...) blah(a, ## __VA_ARGS__)
935 // A(x) B(x) C()
936 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000937 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000938 // Otherwise, emit the error.
939 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000940 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
941 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000942 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000943 }
944
945 // Add a marker EOF token to the end of the token list for this argument.
946 SourceLocation EndLoc = Tok.getLocation();
947 Tok.startToken();
948 Tok.setKind(tok::eof);
949 Tok.setLocation(EndLoc);
950 Tok.setLength(0);
951 ArgTokens.push_back(Tok);
952
953 // If we expect two arguments, add both as empty.
954 if (NumActuals == 0 && MinArgsExpected == 2)
955 ArgTokens.push_back(Tok);
956
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000957 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
958 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000959 // Emit the diagnostic at the macro name in case there is a missing ).
960 // Emitting it at the , could be far away from the macro name.
961 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000962 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
963 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000964 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000965 }
966
967 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
968}
969
970/// \brief Keeps macro expanded tokens for TokenLexers.
971//
972/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
973/// going to lex in the cache and when it finishes the tokens are removed
974/// from the end of the cache.
975Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
976 ArrayRef<Token> tokens) {
977 assert(tokLexer);
978 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000979 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000980
981 size_t newIndex = MacroExpandedTokens.size();
982 bool cacheNeedsToGrow = tokens.size() >
983 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
984 MacroExpandedTokens.append(tokens.begin(), tokens.end());
985
986 if (cacheNeedsToGrow) {
987 // Go through all the TokenLexers whose 'Tokens' pointer points in the
988 // buffer and update the pointers to the (potential) new buffer array.
989 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
990 TokenLexer *prevLexer;
991 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000992 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000993 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
994 }
995 }
996
997 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
998 return MacroExpandedTokens.data() + newIndex;
999}
1000
1001void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1002 assert(!MacroExpandingLexersStack.empty());
1003 size_t tokIndex = MacroExpandingLexersStack.back().second;
1004 assert(tokIndex < MacroExpandedTokens.size());
1005 // Pop the cached macro expanded tokens from the end.
1006 MacroExpandedTokens.resize(tokIndex);
1007 MacroExpandingLexersStack.pop_back();
1008}
1009
1010/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1011/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1012/// the identifier tokens inserted.
1013static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1014 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001015 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001016 struct tm *TM = localtime(&TT);
1017
1018 static const char * const Months[] = {
1019 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1020 };
1021
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001022 {
1023 SmallString<32> TmpBuffer;
1024 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1025 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1026 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001027 Token TmpTok;
1028 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001029 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001030 DATELoc = TmpTok.getLocation();
1031 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001032
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001033 {
1034 SmallString<32> TmpBuffer;
1035 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1036 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1037 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001038 Token TmpTok;
1039 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001040 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001041 TIMELoc = TmpTok.getLocation();
1042 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001043}
1044
1045
1046/// HasFeature - Return true if we recognize and implement the feature
1047/// specified by the identifier as a standard language feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001048static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001049 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001050
1051 // Normalize the feature name, __foo__ becomes foo.
1052 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1053 Feature = Feature.substr(2, Feature.size() - 4);
1054
1055 return llvm::StringSwitch<bool>(Feature)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001056 .Case("address_sanitizer",
1057 LangOpts.Sanitize.hasOneOf(SanitizerKind::Address |
1058 SanitizerKind::KernelAddress))
Douglas Gregor4c27d102015-06-29 18:11:42 +00001059 .Case("assume_nonnull", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001060 .Case("attribute_analyzer_noreturn", true)
1061 .Case("attribute_availability", true)
1062 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001063 .Case("attribute_availability_app_extension", true)
Jordan Rose7e5de9c2015-07-16 22:30:10 +00001064 .Case("attribute_availability_with_version_underscores", true)
Tim Northover7a73cc72015-10-30 16:30:49 +00001065 .Case("attribute_availability_tvos", true)
1066 .Case("attribute_availability_watchos", true)
Manman Ren6731d732016-02-22 18:24:30 +00001067 .Case("attribute_availability_with_strict", true)
Manman Ren75bc6762016-03-21 17:30:55 +00001068 .Case("attribute_availability_with_replacement", true)
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +00001069 .Case("attribute_availability_in_templates", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001070 .Case("attribute_cf_returns_not_retained", true)
1071 .Case("attribute_cf_returns_retained", true)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001072 .Case("attribute_cf_returns_on_parameters", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001073 .Case("attribute_deprecated_with_message", true)
Manman Renc7890fe2016-03-16 18:50:49 +00001074 .Case("attribute_deprecated_with_replacement", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001075 .Case("attribute_ext_vector_type", true)
1076 .Case("attribute_ns_returns_not_retained", true)
1077 .Case("attribute_ns_returns_retained", true)
1078 .Case("attribute_ns_consumes_self", true)
1079 .Case("attribute_ns_consumed", true)
1080 .Case("attribute_cf_consumed", true)
1081 .Case("attribute_objc_ivar_unused", true)
1082 .Case("attribute_objc_method_family", true)
1083 .Case("attribute_overloadable", true)
1084 .Case("attribute_unavailable_with_message", true)
1085 .Case("attribute_unused_on_fields", true)
1086 .Case("blocks", LangOpts.Blocks)
1087 .Case("c_thread_safety_attributes", true)
1088 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Reid Kleckner6cf4a6b2015-08-13 17:56:49 +00001089 .Case("cxx_rtti", LangOpts.RTTI && LangOpts.RTTIData)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001090 .Case("enumerator_attributes", true)
Douglas Gregor4c27d102015-06-29 18:11:42 +00001091 .Case("nullability", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001092 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1093 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1094 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
Derek Bruening256c2e12016-04-21 21:32:04 +00001095 .Case("efficiency_sanitizer",
1096 LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001097 // Objective-C features
1098 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1099 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00001100 .Case("objc_arc_weak", LangOpts.ObjCWeak)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001101 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1102 .Case("objc_fixed_enum", LangOpts.ObjC2)
1103 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorab209d82015-07-07 03:58:42 +00001104 .Case("objc_kindof", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001105 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1106 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1107 .Case("objc_property_explicit_atomic",
1108 true) // Does clang support explicit "atomic" keyword?
1109 .Case("objc_protocol_qualifier_mangling", true)
1110 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1111 .Case("ownership_holds", true)
1112 .Case("ownership_returns", true)
1113 .Case("ownership_takes", true)
1114 .Case("objc_bool", true)
1115 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1116 .Case("objc_array_literals", LangOpts.ObjC2)
1117 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1118 .Case("objc_boxed_expressions", LangOpts.ObjC2)
Alex Denisovfde64952015-06-26 05:28:36 +00001119 .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001120 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001121 .Case("objc_bridge_id", true)
1122 .Case("objc_bridge_id_on_typedefs", true)
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001123 .Case("objc_generics", LangOpts.ObjC2)
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001124 .Case("objc_generics_variance", LangOpts.ObjC2)
Manman Ren515758e2016-03-10 23:51:03 +00001125 .Case("objc_class_property", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001126 // C11 features
1127 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001128 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001129 .Case("c_atomic", LangOpts.C11)
1130 .Case("c_generic_selections", LangOpts.C11)
1131 .Case("c_static_assert", LangOpts.C11)
1132 .Case("c_thread_local",
1133 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1134 // C++11 features
1135 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1136 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1137 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001138 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001139 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1140 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1141 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1142 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
1143 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1144 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1145 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1146 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1147 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1148 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1149 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1150 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1151 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1152 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1153 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1154 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1155 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1156 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1157 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1158 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1159 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1160 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1161 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1162 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1163 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1164 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1165 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1166 .Case("cxx_thread_local",
1167 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1168 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1169 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1170 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1171 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1172 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
1173 // C++1y features
1174 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1175 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1176 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1177 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1178 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1179 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1180 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1181 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1182 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
1183 // C++ TSes
1184 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1185 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1186 // FIXME: Should this be __has_feature or __has_extension?
1187 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1188 // Type traits
David Majnemer3e5e05a2016-05-24 17:21:42 +00001189 // N.B. Additional type traits should not be added to the following list.
1190 // Instead, they should be detected by has_extension.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001191 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1192 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1193 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1194 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1195 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1196 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1197 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1198 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1199 .Case("is_abstract", LangOpts.CPlusPlus)
1200 .Case("is_base_of", LangOpts.CPlusPlus)
1201 .Case("is_class", LangOpts.CPlusPlus)
1202 .Case("is_constructible", LangOpts.CPlusPlus)
1203 .Case("is_convertible_to", LangOpts.CPlusPlus)
1204 .Case("is_empty", LangOpts.CPlusPlus)
1205 .Case("is_enum", LangOpts.CPlusPlus)
1206 .Case("is_final", LangOpts.CPlusPlus)
1207 .Case("is_literal", LangOpts.CPlusPlus)
David Majnemer3e5e05a2016-05-24 17:21:42 +00001208 .Case("is_standard_layout", LangOpts.CPlusPlus)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001209 .Case("is_pod", LangOpts.CPlusPlus)
1210 .Case("is_polymorphic", LangOpts.CPlusPlus)
David Majnemer3e5e05a2016-05-24 17:21:42 +00001211 .Case("is_sealed", LangOpts.CPlusPlus && LangOpts.MicrosoftExt)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001212 .Case("is_trivial", LangOpts.CPlusPlus)
1213 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1214 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1215 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1216 .Case("is_union", LangOpts.CPlusPlus)
1217 .Case("modules", LangOpts.Modules)
Peter Collingbournec4122c12015-06-15 21:08:13 +00001218 .Case("safe_stack", LangOpts.Sanitize.has(SanitizerKind::SafeStack))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001219 .Case("tls", PP.getTargetInfo().isTLSSupported())
1220 .Case("underlying_type", LangOpts.CPlusPlus)
1221 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001222}
1223
1224/// HasExtension - Return true if we recognize and implement the feature
1225/// specified by the identifier, either as an extension or a standard language
1226/// feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001227static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1228 if (HasFeature(PP, Extension))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001229 return true;
1230
1231 // If the use of an extension results in an error diagnostic, extensions are
1232 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001233 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1234 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001235 return false;
1236
1237 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001238
1239 // Normalize the extension name, __foo__ becomes foo.
1240 if (Extension.startswith("__") && Extension.endswith("__") &&
1241 Extension.size() >= 4)
1242 Extension = Extension.substr(2, Extension.size() - 4);
1243
1244 // Because we inherit the feature list from HasFeature, this string switch
1245 // must be less restrictive than HasFeature's.
1246 return llvm::StringSwitch<bool>(Extension)
1247 // C11 features supported by other languages as extensions.
1248 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001249 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001250 .Case("c_atomic", true)
1251 .Case("c_generic_selections", true)
1252 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001253 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001254 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001255 .Case("cxx_atomic", LangOpts.CPlusPlus)
1256 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1257 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1258 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1259 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1260 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1261 .Case("cxx_override_control", LangOpts.CPlusPlus)
1262 .Case("cxx_range_for", LangOpts.CPlusPlus)
1263 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1264 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Eric Fiselier7aa0d4a2015-05-12 22:37:23 +00001265 .Case("cxx_variadic_templates", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001266 // C++1y features supported by other languages as extensions.
1267 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001268 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001269 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001270 .Default(false);
1271}
1272
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001273/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1274/// or '__has_include_next("path")' expression.
1275/// Returns true if successful.
1276static bool EvaluateHasIncludeCommon(Token &Tok,
1277 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001278 const DirectoryLookup *LookupFrom,
1279 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001280 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001281 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001282 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001283
Aaron Ballman6ce00002013-01-16 19:32:21 +00001284 // These expressions are only allowed within a preprocessor directive.
1285 if (!PP.isParsingIfOrElifDirective()) {
1286 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001287 // Return a valid identifier token.
1288 assert(Tok.is(tok::identifier));
1289 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001290 return false;
1291 }
1292
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001293 // Get '('.
1294 PP.LexNonComment(Tok);
1295
1296 // Ensure we have a '('.
1297 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001298 // No '(', use end of last token.
1299 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001300 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001301 // If the next token looks like a filename or the start of one,
1302 // assume it is and process it as such.
1303 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1304 !Tok.is(tok::less))
1305 return false;
1306 } else {
1307 // Save '(' location for possible missing ')' message.
1308 LParenLoc = Tok.getLocation();
1309
Eli Friedmanec94b612013-01-09 02:20:00 +00001310 if (PP.getCurrentLexer()) {
1311 // Get the file name.
1312 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1313 } else {
1314 // We're in a macro, so we can't use LexIncludeFilename; just
1315 // grab the next token.
1316 PP.Lex(Tok);
1317 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001318 }
1319
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001320 // Reserve a buffer to get the spelling.
1321 SmallString<128> FilenameBuffer;
1322 StringRef Filename;
1323 SourceLocation EndLoc;
1324
1325 switch (Tok.getKind()) {
1326 case tok::eod:
1327 // If the token kind is EOD, the error has already been diagnosed.
1328 return false;
1329
1330 case tok::angle_string_literal:
1331 case tok::string_literal: {
1332 bool Invalid = false;
1333 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1334 if (Invalid)
1335 return false;
1336 break;
1337 }
1338
1339 case tok::less:
1340 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1341 // case, glue the tokens together into FilenameBuffer and interpret those.
1342 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001343 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1344 // Let the caller know a <eod> was found by changing the Token kind.
1345 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001346 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001347 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001348 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001349 break;
1350 default:
1351 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1352 return false;
1353 }
1354
Richard Trieuda031982012-10-22 20:28:48 +00001355 SourceLocation FilenameLoc = Tok.getLocation();
1356
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001357 // Get ')'.
1358 PP.LexNonComment(Tok);
1359
1360 // Ensure we have a trailing ).
1361 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001362 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1363 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001364 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001365 return false;
1366 }
1367
1368 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1369 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1370 // error.
1371 if (Filename.empty())
1372 return false;
1373
1374 // Search include directories.
1375 const DirectoryLookup *CurDir;
1376 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001377 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1378 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001379
1380 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001381 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001382}
1383
1384/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1385/// Returns true if successful.
1386static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1387 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001388 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001389}
1390
1391/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1392/// Returns true if successful.
1393static bool EvaluateHasIncludeNext(Token &Tok,
1394 IdentifierInfo *II, Preprocessor &PP) {
1395 // __has_include_next is like __has_include, except that we start
1396 // searching after the current found directory. If we can't do this,
1397 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001398 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001399 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001400 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001401 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001402 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001403 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001404 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001405 } else if (PP.getCurrentSubmodule()) {
1406 // Start looking up in the directory *after* the one in which the current
1407 // file would be found, if any.
1408 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1409 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1410 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001411 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001412 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1413 } else {
1414 // Start looking up in the next directory.
1415 ++Lookup;
1416 }
1417
Richard Smith25d50752014-10-20 00:15:49 +00001418 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001419}
1420
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001421/// \brief Process single-argument builtin feature-like macros that return
1422/// integer values.
1423static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1424 Token &Tok, IdentifierInfo *II,
1425 Preprocessor &PP,
1426 llvm::function_ref<
1427 int(Token &Tok,
1428 bool &HasLexedNextTok)> Op) {
1429 // Parse the initial '('.
1430 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001431 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001432 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1433 << tok::l_paren;
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001434
1435 // Provide a dummy '0' value on output stream to elide further errors.
1436 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1437 OS << 0;
1438 Tok.setKind(tok::numeric_constant);
1439 }
1440 return;
Douglas Gregorc83de302012-09-25 15:44:52 +00001441 }
1442
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001443 unsigned ParenDepth = 1;
Douglas Gregorc83de302012-09-25 15:44:52 +00001444 SourceLocation LParenLoc = Tok.getLocation();
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001445 llvm::Optional<int> Result;
Douglas Gregorc83de302012-09-25 15:44:52 +00001446
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001447 Token ResultTok;
1448 bool SuppressDiagnostic = false;
1449 while (true) {
1450 // Parse next token.
1451 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001452
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001453already_lexed:
1454 switch (Tok.getKind()) {
1455 case tok::eof:
1456 case tok::eod:
1457 // Don't provide even a dummy value if the eod or eof marker is
1458 // reached. Simply provide a diagnostic.
1459 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1460 return;
1461
1462 case tok::comma:
1463 if (!SuppressDiagnostic) {
1464 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1465 SuppressDiagnostic = true;
1466 }
1467 continue;
1468
1469 case tok::l_paren:
1470 ++ParenDepth;
1471 if (Result.hasValue())
1472 break;
1473 if (!SuppressDiagnostic) {
1474 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1475 SuppressDiagnostic = true;
1476 }
1477 continue;
1478
1479 case tok::r_paren:
1480 if (--ParenDepth > 0)
1481 continue;
1482
1483 // The last ')' has been reached; return the value if one found or
1484 // a diagnostic and a dummy value.
1485 if (Result.hasValue())
1486 OS << Result.getValue();
1487 else {
1488 OS << 0;
1489 if (!SuppressDiagnostic)
1490 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1491 }
1492 Tok.setKind(tok::numeric_constant);
1493 return;
1494
1495 default: {
1496 // Parse the macro argument, if one not found so far.
1497 if (Result.hasValue())
1498 break;
1499
1500 bool HasLexedNextToken = false;
1501 Result = Op(Tok, HasLexedNextToken);
1502 ResultTok = Tok;
1503 if (HasLexedNextToken)
1504 goto already_lexed;
1505 continue;
1506 }
1507 }
1508
1509 // Diagnose missing ')'.
1510 if (!SuppressDiagnostic) {
1511 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1512 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1513 Diag << LastII;
1514 else
1515 Diag << ResultTok.getKind();
1516 Diag << tok::r_paren << ResultTok.getLocation();
1517 }
1518 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1519 SuppressDiagnostic = true;
1520 }
Douglas Gregorc83de302012-09-25 15:44:52 +00001521 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001522}
Douglas Gregorc83de302012-09-25 15:44:52 +00001523
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001524/// \brief Helper function to return the IdentifierInfo structure of a Token
1525/// or generate a diagnostic if none available.
1526static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
1527 Preprocessor &PP,
1528 signed DiagID) {
1529 IdentifierInfo *II;
1530 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1531 return II;
Douglas Gregorc83de302012-09-25 15:44:52 +00001532
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001533 PP.Diag(Tok.getLocation(), DiagID);
1534 return nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +00001535}
1536
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001537/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1538/// as a builtin macro, handle it and return the next token as 'Tok'.
1539void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1540 // Figure out which token this is.
1541 IdentifierInfo *II = Tok.getIdentifierInfo();
1542 assert(II && "Can't be a macro without id info!");
1543
1544 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1545 // invoke the pragma handler, then lex the token after it.
1546 if (II == Ident_Pragma)
1547 return Handle_Pragma(Tok);
1548 else if (II == Ident__pragma) // in non-MS mode this is null
1549 return HandleMicrosoft__pragma(Tok);
1550
1551 ++NumBuiltinMacroExpanded;
1552
1553 SmallString<128> TmpBuffer;
1554 llvm::raw_svector_ostream OS(TmpBuffer);
1555
1556 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001557 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001558 Tok.clearFlag(Token::NeedsCleaning);
1559
1560 if (II == Ident__LINE__) {
1561 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1562 // source file) of the current source line (an integer constant)". This can
1563 // be affected by #line.
1564 SourceLocation Loc = Tok.getLocation();
1565
1566 // Advance to the location of the first _, this might not be the first byte
1567 // of the token if it starts with an escaped newline.
1568 Loc = AdvanceToTokenCharacter(Loc, 0);
1569
1570 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1571 // a macro expansion. This doesn't matter for object-like macros, but
1572 // can matter for a function-like macro that expands to contain __LINE__.
1573 // Skip down through expansion points until we find a file loc for the
1574 // end of the expansion history.
1575 Loc = SourceMgr.getExpansionRange(Loc).second;
1576 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1577
1578 // __LINE__ expands to a simple numeric value.
1579 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1580 Tok.setKind(tok::numeric_constant);
1581 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1582 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1583 // character string literal)". This can be affected by #line.
1584 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1585
1586 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1587 // #include stack instead of the current file.
1588 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1589 SourceLocation NextLoc = PLoc.getIncludeLoc();
1590 while (NextLoc.isValid()) {
1591 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1592 if (PLoc.isInvalid())
1593 break;
1594
1595 NextLoc = PLoc.getIncludeLoc();
1596 }
1597 }
1598
1599 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1600 SmallString<128> FN;
1601 if (PLoc.isValid()) {
1602 FN += PLoc.getFilename();
1603 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001604 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001605 }
1606 Tok.setKind(tok::string_literal);
1607 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001608 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001609 if (!DATELoc.isValid())
1610 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1611 Tok.setKind(tok::string_literal);
1612 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1613 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1614 Tok.getLocation(),
1615 Tok.getLength()));
1616 return;
1617 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001618 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001619 if (!TIMELoc.isValid())
1620 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1621 Tok.setKind(tok::string_literal);
1622 Tok.setLength(strlen("\"hh:mm:ss\""));
1623 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1624 Tok.getLocation(),
1625 Tok.getLength()));
1626 return;
1627 } else if (II == Ident__INCLUDE_LEVEL__) {
1628 // Compute the presumed include depth of this token. This can be affected
1629 // by GNU line markers.
1630 unsigned Depth = 0;
1631
1632 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1633 if (PLoc.isValid()) {
1634 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1635 for (; PLoc.isValid(); ++Depth)
1636 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1637 }
1638
1639 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1640 OS << Depth;
1641 Tok.setKind(tok::numeric_constant);
1642 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001643 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001644 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1645 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1646
1647 // Get the file that we are lexing out of. If we're currently lexing from
1648 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001649 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001650 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1651
1652 if (TheLexer)
1653 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1654
1655 const char *Result;
1656 if (CurFile) {
1657 time_t TT = CurFile->getModificationTime();
1658 struct tm *TM = localtime(&TT);
1659 Result = asctime(TM);
1660 } else {
1661 Result = "??? ??? ?? ??:??:?? ????\n";
1662 }
1663 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001664 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001665 Tok.setKind(tok::string_literal);
1666 } else if (II == Ident__COUNTER__) {
1667 // __COUNTER__ expands to a simple numeric value.
1668 OS << CounterValue++;
1669 Tok.setKind(tok::numeric_constant);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001670 } else if (II == Ident__has_feature) {
1671 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1672 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1673 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1674 diag::err_feature_check_malformed);
1675 return II && HasFeature(*this, II->getName());
1676 });
1677 } else if (II == Ident__has_extension) {
1678 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1679 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1680 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1681 diag::err_feature_check_malformed);
1682 return II && HasExtension(*this, II->getName());
1683 });
1684 } else if (II == Ident__has_builtin) {
1685 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1686 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1687 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1688 diag::err_feature_check_malformed);
1689 if (!II)
1690 return false;
1691 else if (II->getBuiltinID() != 0)
1692 return true;
1693 else {
1694 const LangOptions &LangOpts = getLangOpts();
1695 return llvm::StringSwitch<bool>(II->getName())
1696 .Case("__make_integer_seq", LangOpts.CPlusPlus)
Eric Fiselier6ad68552016-07-01 01:24:09 +00001697 .Case("__type_pack_element", LangOpts.CPlusPlus)
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001698 .Default(false);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001699 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001700 });
1701 } else if (II == Ident__is_identifier) {
1702 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1703 [](Token &Tok, bool &HasLexedNextToken) -> int {
1704 return Tok.is(tok::identifier);
1705 });
1706 } else if (II == Ident__has_attribute) {
1707 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1708 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1709 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1710 diag::err_feature_check_malformed);
1711 return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1712 getTargetInfo(), getLangOpts()) : 0;
1713 });
1714 } else if (II == Ident__has_declspec) {
1715 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1716 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1717 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1718 diag::err_feature_check_malformed);
1719 return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II,
1720 getTargetInfo(), getLangOpts()) : 0;
1721 });
1722 } else if (II == Ident__has_cpp_attribute) {
1723 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1724 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1725 IdentifierInfo *ScopeII = nullptr;
1726 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1727 diag::err_feature_check_malformed);
1728 if (!II)
1729 return false;
1730
1731 // It is possible to receive a scope token. Read the "::", if it is
1732 // available, and the subsequent identifier.
David Majnemerd6163622014-12-15 09:03:58 +00001733 LexUnexpandedToken(Tok);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001734 if (Tok.isNot(tok::coloncolon))
1735 HasLexedNextToken = true;
1736 else {
1737 ScopeII = II;
1738 LexUnexpandedToken(Tok);
1739 II = ExpectFeatureIdentifierInfo(Tok, *this,
1740 diag::err_feature_check_malformed);
1741 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001742
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001743 return II ? hasAttribute(AttrSyntax::CXX, ScopeII, II,
1744 getTargetInfo(), getLangOpts()) : 0;
1745 });
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001746 } else if (II == Ident__has_include ||
1747 II == Ident__has_include_next) {
1748 // The argument to these two builtins should be a parenthesized
1749 // file name string literal using angle brackets (<>) or
1750 // double-quotes ("").
1751 bool Value;
1752 if (II == Ident__has_include)
1753 Value = EvaluateHasInclude(Tok, II, *this);
1754 else
1755 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001756
1757 if (Tok.isNot(tok::r_paren))
1758 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001759 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001760 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001761 } else if (II == Ident__has_warning) {
1762 // The argument should be a parenthesized string literal.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001763 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1764 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1765 std::string WarningName;
1766 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs58905d22012-11-17 19:15:38 +00001767
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001768 HasLexedNextToken = Tok.is(tok::string_literal);
1769 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1770 /*MacroExpansion=*/false))
1771 return false;
Andy Gibbs58905d22012-11-17 19:15:38 +00001772
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001773 // FIXME: Should we accept "-R..." flags here, or should that be
1774 // handled by a separate __has_remark?
1775 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1776 WarningName[1] != 'W') {
1777 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1778 return false;
1779 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001780
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001781 // Finally, check if the warning flags maps to a diagnostic group.
1782 // We construct a SmallVector here to talk to getDiagnosticIDs().
1783 // Although we don't use the result, this isn't a hot path, and not
1784 // worth special casing.
1785 SmallVector<diag::kind, 10> Diags;
1786 return !getDiagnostics().getDiagnosticIDs()->
1787 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1788 WarningName.substr(2), Diags);
1789 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001790 } else if (II == Ident__building_module) {
1791 // The argument to this builtin should be an identifier. The
1792 // builtin evaluates to 1 when that identifier names the module we are
1793 // currently building.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001794 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1795 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1796 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1797 diag::err_expected_id_building_module);
Richard Smithbbcc9f02016-08-26 00:14:38 +00001798 return getLangOpts().isCompilingModule() && II &&
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001799 (II->getName() == getLangOpts().CurrentModule);
1800 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001801 } else if (II == Ident__MODULE__) {
1802 // The current module as an identifier.
1803 OS << getLangOpts().CurrentModule;
1804 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1805 Tok.setIdentifierInfo(ModuleII);
1806 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001807 } else if (II == Ident__identifier) {
1808 SourceLocation Loc = Tok.getLocation();
1809
1810 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1811 // if the parens are missing.
1812 LexNonComment(Tok);
1813 if (Tok.isNot(tok::l_paren)) {
1814 // No '(', use end of last token.
1815 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1816 << II << tok::l_paren;
1817 // If the next token isn't valid as our argument, we can't recover.
1818 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1819 Tok.setKind(tok::identifier);
1820 return;
1821 }
1822
1823 SourceLocation LParenLoc = Tok.getLocation();
1824 LexNonComment(Tok);
1825
1826 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1827 Tok.setKind(tok::identifier);
1828 else {
1829 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1830 << Tok.getKind();
1831 // Don't walk past anything that's not a real token.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001832 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
Richard Smithae385082014-03-15 00:06:08 +00001833 return;
1834 }
1835
1836 // Discard the ')', preserving 'Tok' as our result.
1837 Token RParen;
1838 LexNonComment(RParen);
1839 if (RParen.isNot(tok::r_paren)) {
1840 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1841 << Tok.getKind() << tok::r_paren;
1842 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1843 }
1844 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001845 } else {
1846 llvm_unreachable("Unknown identifier!");
1847 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001848 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001849}
1850
1851void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1852 // If the 'used' status changed, and the macro requires 'unused' warning,
1853 // remove its SourceLocation from the warn-for-unused-macro locations.
1854 if (MI->isWarnIfUnused() && !MI->isUsed())
1855 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1856 MI->setIsUsed(true);
1857}