blob: 9046ad51c14ae0208c3c41ba94918b777aab4d30 [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
15#include "clang/Lex/Preprocessor.h"
Aaron Ballman2fbf9942014-03-31 13:14:44 +000016#include "clang/Basic/Attributes.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000017#include "clang/Basic/FileManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Basic/SourceManager.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000019#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000020#include "clang/Lex/CodeCompletionHandler.h"
21#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000023#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Lex/MacroInfo.h"
25#include "llvm/ADT/STLExtras.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000026#include "llvm/ADT/SmallString.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000027#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000028#include "llvm/Config/llvm-config.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000029#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000030#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "llvm/Support/raw_ostream.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000032#include <cstdio>
33#include <ctime>
34using namespace clang;
35
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000036MacroDirective *
Richard Smith20e883e2015-04-29 23:20:19 +000037Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
38 if (!II->hadMacroDefinition())
39 return nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +000040 auto Pos = CurSubmoduleState->Macros.find(II);
41 return Pos == CurSubmoduleState->Macros.end() ? nullptr
42 : Pos->second.getLatest();
Joao Matosc0d4c1b2012-08-31 21:34:27 +000043}
44
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000045void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000046 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000047 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000048
Richard Smith04765ae2015-05-21 01:20:10 +000049 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000050 auto *OldMD = StoredMD.getLatest();
51 MD->setPrevious(OldMD);
52 StoredMD.setLatest(MD);
Richard Smith753e0072015-04-27 23:21:38 +000053 StoredMD.overrideActiveModuleMacros(*this, II);
Richard Smithb8b2ed62015-04-23 18:18:26 +000054
55 // Set up the identifier as having associated macro history.
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000056 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000057 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000058 II->setHasMacroDefinition(false);
Richard Smith3981b172015-04-30 02:16:23 +000059 if (II->isFromAST())
Joao Matosc0d4c1b2012-08-31 21:34:27 +000060 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000061}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000062
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000063void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
64 MacroDirective *MD) {
65 assert(II && MD);
Richard Smith04765ae2015-05-21 01:20:10 +000066 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000067 assert(!StoredMD.getLatest() &&
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000068 "the macro history was modified before initializing it from a pch");
69 StoredMD = MD;
70 // Setup the identifier as having associated macro history.
71 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000072 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000073 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000074}
75
Richard Smithb8b2ed62015-04-23 18:18:26 +000076ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
Richard Smithe56c8bc2015-04-22 00:26:11 +000077 MacroInfo *Macro,
78 ArrayRef<ModuleMacro *> Overrides,
79 bool &New) {
80 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +000081 ModuleMacro::Profile(ID, Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +000082
83 void *InsertPos;
84 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
85 New = false;
86 return MM;
87 }
88
Richard Smithb8b2ed62015-04-23 18:18:26 +000089 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
Richard Smithe56c8bc2015-04-22 00:26:11 +000090 ModuleMacros.InsertNode(MM, InsertPos);
91
92 // Each overridden macro is now overridden by one more macro.
93 bool HidAny = false;
94 for (auto *O : Overrides) {
95 HidAny |= (O->NumOverriddenBy == 0);
96 ++O->NumOverriddenBy;
97 }
98
99 // If we were the first overrider for any macro, it's no longer a leaf.
100 auto &LeafMacros = LeafModuleMacros[II];
101 if (HidAny) {
102 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
103 [](ModuleMacro *MM) {
104 return MM->NumOverriddenBy != 0;
105 }),
106 LeafMacros.end());
107 }
108
109 // The new macro is always a leaf macro.
110 LeafMacros.push_back(MM);
Richard Smith20e883e2015-04-29 23:20:19 +0000111 // The identifier now has defined macros (that may or may not be visible).
112 II->setHasMacroDefinition(true);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000113
114 New = true;
115 return MM;
116}
117
Richard Smithb8b2ed62015-04-23 18:18:26 +0000118ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) {
Richard Smith5dbef922015-04-22 02:09:43 +0000119 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000120 ModuleMacro::Profile(ID, Mod, II);
Richard Smith5dbef922015-04-22 02:09:43 +0000121
122 void *InsertPos;
123 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
124}
125
Richard Smith20e883e2015-04-29 23:20:19 +0000126void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
Richard Smith753e0072015-04-27 23:21:38 +0000127 ModuleMacroInfo &Info) {
Richard Smith04765ae2015-05-21 01:20:10 +0000128 assert(Info.ActiveModuleMacrosGeneration !=
129 CurSubmoduleState->VisibleModules.getGeneration() &&
Richard Smith753e0072015-04-27 23:21:38 +0000130 "don't need to update this macro name info");
Richard Smith04765ae2015-05-21 01:20:10 +0000131 Info.ActiveModuleMacrosGeneration =
132 CurSubmoduleState->VisibleModules.getGeneration();
Richard Smith753e0072015-04-27 23:21:38 +0000133
134 auto Leaf = LeafModuleMacros.find(II);
135 if (Leaf == LeafModuleMacros.end()) {
136 // No imported macros at all: nothing to do.
137 return;
138 }
139
140 Info.ActiveModuleMacros.clear();
141
142 // Every macro that's locally overridden is overridden by a visible macro.
143 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
144 for (auto *O : Info.OverriddenMacros)
145 NumHiddenOverrides[O] = -1;
146
147 // Collect all macros that are not overridden by a visible macro.
148 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf->second.begin(),
149 Leaf->second.end());
150 while (!Worklist.empty()) {
151 auto *MM = Worklist.pop_back_val();
Richard Smith04765ae2015-05-21 01:20:10 +0000152 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
Richard Smith753e0072015-04-27 23:21:38 +0000153 // We only care about collecting definitions; undefinitions only act
154 // to override other definitions.
155 if (MM->getMacroInfo())
156 Info.ActiveModuleMacros.push_back(MM);
157 } else {
158 for (auto *O : MM->overrides())
159 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
160 Worklist.push_back(O);
161 }
162 }
Richard Smith20e883e2015-04-29 23:20:19 +0000163 // Our reverse postorder walk found the macros in reverse order.
164 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
Richard Smith753e0072015-04-27 23:21:38 +0000165
166 // Determine whether the macro name is ambiguous.
Richard Smith753e0072015-04-27 23:21:38 +0000167 MacroInfo *MI = nullptr;
Richard Smith20e883e2015-04-29 23:20:19 +0000168 bool IsSystemMacro = true;
169 bool IsAmbiguous = false;
170 if (auto *MD = Info.MD) {
171 while (MD && isa<VisibilityMacroDirective>(MD))
172 MD = MD->getPrevious();
173 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
174 MI = DMD->getInfo();
175 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
176 }
Richard Smith753e0072015-04-27 23:21:38 +0000177 }
178 for (auto *Active : Info.ActiveModuleMacros) {
179 auto *NewMI = Active->getMacroInfo();
180
181 // Before marking the macro as ambiguous, check if this is a case where
182 // both macros are in system headers. If so, we trust that the system
183 // did not get it wrong. This also handles cases where Clang's own
184 // headers have a different spelling of certain system macros:
185 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
186 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
187 //
188 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
189 // overrides the system limits.h's macros, so there's no conflict here.
Richard Smith20e883e2015-04-29 23:20:19 +0000190 if (MI && NewMI != MI &&
191 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
192 IsAmbiguous = true;
193 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
194 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
195 MI = NewMI;
Richard Smith753e0072015-04-27 23:21:38 +0000196 }
Richard Smith20e883e2015-04-29 23:20:19 +0000197 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
Richard Smith753e0072015-04-27 23:21:38 +0000198}
199
Richard Smith3ffa61d2015-04-30 23:10:40 +0000200void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
201 ArrayRef<ModuleMacro*> Leaf;
202 auto LeafIt = LeafModuleMacros.find(II);
203 if (LeafIt != LeafModuleMacros.end())
204 Leaf = LeafIt->second;
205 const MacroState *State = nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +0000206 auto Pos = CurSubmoduleState->Macros.find(II);
207 if (Pos != CurSubmoduleState->Macros.end())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000208 State = &Pos->second;
209
210 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
211 if (State && State->isAmbiguous(*this, II))
212 llvm::errs() << " ambiguous";
Richard Smithd0014bf2015-04-30 23:42:10 +0000213 if (State && !State->getOverriddenMacros().empty()) {
Richard Smith3ffa61d2015-04-30 23:10:40 +0000214 llvm::errs() << " overrides";
215 for (auto *O : State->getOverriddenMacros())
216 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
217 }
218 llvm::errs() << "\n";
219
220 // Dump local macro directives.
221 for (auto *MD = State ? State->getLatest() : nullptr; MD;
222 MD = MD->getPrevious()) {
223 llvm::errs() << " ";
224 MD->dump();
225 }
226
227 // Dump module macros.
228 llvm::DenseSet<ModuleMacro*> Active;
229 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
230 Active.insert(MM);
231 llvm::DenseSet<ModuleMacro*> Visited;
232 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
233 while (!Worklist.empty()) {
234 auto *MM = Worklist.pop_back_val();
235 llvm::errs() << " ModuleMacro " << MM << " "
236 << MM->getOwningModule()->getFullModuleName();
237 if (!MM->getMacroInfo())
238 llvm::errs() << " undef";
239
240 if (Active.count(MM))
241 llvm::errs() << " active";
Richard Smith04765ae2015-05-21 01:20:10 +0000242 else if (!CurSubmoduleState->VisibleModules.isVisible(
243 MM->getOwningModule()))
Richard Smith3ffa61d2015-04-30 23:10:40 +0000244 llvm::errs() << " hidden";
Richard Smith42413142015-05-15 20:05:43 +0000245 else if (MM->getMacroInfo())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000246 llvm::errs() << " overridden";
247
248 if (!MM->overrides().empty()) {
249 llvm::errs() << " overrides";
250 for (auto *O : MM->overrides()) {
251 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
252 if (Visited.insert(O).second)
253 Worklist.push_back(O);
254 }
255 }
256 llvm::errs() << "\n";
257 if (auto *MI = MM->getMacroInfo()) {
258 llvm::errs() << " ";
259 MI->dump();
260 llvm::errs() << "\n";
261 }
262 }
263}
264
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000265/// RegisterBuiltinMacro - Register the specified identifier in the identifier
266/// table and mark it as a builtin macro to be expanded.
267static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
268 // Get the identifier.
269 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
270
271 // Mark it as being a macro that is builtin.
272 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
273 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000274 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000275 return Id;
276}
277
278
279/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
280/// identifier table.
281void Preprocessor::RegisterBuiltinMacros() {
282 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
283 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
284 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
285 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
286 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
287 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
288
Aaron Ballmana0344c52014-11-14 13:44:02 +0000289 // C++ Standing Document Extensions.
Aaron Ballman416b1272015-05-11 14:09:50 +0000290 if (LangOpts.CPlusPlus)
291 Ident__has_cpp_attribute =
292 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
293 else
294 Ident__has_cpp_attribute = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +0000295
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000296 // GCC Extensions.
297 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
298 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
299 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
300
Richard Smithae385082014-03-15 00:06:08 +0000301 // Microsoft Extensions.
302 if (LangOpts.MicrosoftExt) {
303 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
304 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
305 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000306 Ident__identifier = nullptr;
307 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000308 }
309
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000310 // Clang Extensions.
311 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
312 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
313 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
314 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000315 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000316 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
317 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
318 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000319 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000320
Douglas Gregorc83de302012-09-25 15:44:52 +0000321 // Modules.
322 if (LangOpts.Modules) {
323 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
324
325 // __MODULE__
326 if (!LangOpts.CurrentModule.empty())
327 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
328 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000329 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000330 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000331 Ident__building_module = nullptr;
332 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000333 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000334}
335
336/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
337/// in its expansion, currently expands to that token literally.
338static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
339 const IdentifierInfo *MacroIdent,
340 Preprocessor &PP) {
341 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
342
343 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000344 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000345
346 // If the information about this identifier is out of date, update it from
347 // the external source.
348 if (II->isOutOfDate())
349 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
350
351 // If the identifier is a macro, and if that macro is enabled, it may be
352 // expanded so it's not a trivial expansion.
Richard Smith20e883e2015-04-29 23:20:19 +0000353 if (auto *ExpansionMI = PP.getMacroInfo(II))
Richard Smith3d5925b2015-04-29 23:26:13 +0000354 if (ExpansionMI->isEnabled() &&
Richard Smith20e883e2015-04-29 23:20:19 +0000355 // Fast expanding "#define X X" is ok, because X would be disabled.
356 II != MacroIdent)
357 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000358
359 // If this is an object-like macro invocation, it is safe to trivially expand
360 // it.
361 if (MI->isObjectLike()) return true;
362
363 // If this is a function-like macro invocation, it's safe to trivially expand
364 // as long as the identifier is not a macro argument.
365 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
366 I != E; ++I)
367 if (*I == II)
368 return false; // Identifier is a macro argument.
369
370 return true;
371}
372
373
374/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
375/// lexed is a '('. If so, consume the token and return true, if not, this
376/// method should have no observable side-effect on the lexed tokens.
377bool Preprocessor::isNextPPTokenLParen() {
378 // Do some quick tests for rejection cases.
379 unsigned Val;
380 if (CurLexer)
381 Val = CurLexer->isNextPPTokenLParen();
382 else if (CurPTHLexer)
383 Val = CurPTHLexer->isNextPPTokenLParen();
384 else
385 Val = CurTokenLexer->isNextTokenLParen();
386
387 if (Val == 2) {
388 // We have run off the end. If it's a source file we don't
389 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
390 // macro stack.
391 if (CurPPLexer)
392 return false;
393 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
394 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
395 if (Entry.TheLexer)
396 Val = Entry.TheLexer->isNextPPTokenLParen();
397 else if (Entry.ThePTHLexer)
398 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
399 else
400 Val = Entry.TheTokenLexer->isNextTokenLParen();
401
402 if (Val != 2)
403 break;
404
405 // Ran off the end of a source file?
406 if (Entry.ThePPLexer)
407 return false;
408 }
409 }
410
411 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
412 // have found something that isn't a '(' or we found the end of the
413 // translation unit. In either case, return false.
414 return Val == 1;
415}
416
417/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
418/// expanded as a macro, handle it and return the next token as 'Identifier'.
419bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000420 const MacroDefinition &M) {
421 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000422
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000423 // If this is a macro expansion in the "#if !defined(x)" line for the file,
424 // then the macro could expand to different things in other contexts, we need
425 // to disable the optimization in this case.
426 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
427
428 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
429 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000430 if (Callbacks)
431 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
432 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000433 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000434 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000435 }
436
437 /// Args - If this is a function-like macro expansion, this contains,
438 /// for each macro argument, the list of tokens that were provided to the
439 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000440 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000441
442 // Remember where the end of the expansion occurred. For an object-like
443 // macro, this is the identifier. For a function-like macro, this is the ')'.
444 SourceLocation ExpansionEnd = Identifier.getLocation();
445
446 // If this is a function-like macro, read the arguments.
447 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000448 // Remember that we are now parsing the arguments to a macro invocation.
449 // Preprocessor directives used inside macro arguments are not portable, and
450 // this enables the warning.
451 InMacroArgs = true;
452 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
453
454 // Finished parsing args.
455 InMacroArgs = false;
456
457 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000458 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000459
460 ++NumFnMacroExpanded;
461 } else {
462 ++NumMacroExpanded;
463 }
464
465 // Notice that this macro has been used.
466 markMacroAsUsed(MI);
467
468 // Remember where the token is expanded.
469 SourceLocation ExpandLoc = Identifier.getLocation();
470 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
471
472 if (Callbacks) {
473 if (InMacroArgs) {
474 // We can have macro expansion inside a conditional directive while
475 // reading the function macro arguments. To ensure, in that case, that
476 // MacroExpands callbacks still happen in source order, queue this
477 // callback to have it happen after the function macro callback.
478 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000479 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000480 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000481 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000482 if (!DelayedMacroExpandsCallbacks.empty()) {
483 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
484 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000485 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000486 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
487 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000488 }
489 DelayedMacroExpandsCallbacks.clear();
490 }
491 }
492 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000493
494 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000495 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000496 Diag(Identifier, diag::warn_pp_ambiguous_macro)
497 << Identifier.getIdentifierInfo();
498 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
499 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000500 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
501 if (OtherMI != MI)
502 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
503 << Identifier.getIdentifierInfo();
504 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000505 }
506
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000507 // If we started lexing a macro, enter the macro expansion body.
508
509 // If this macro expands to no tokens, don't bother to push it onto the
510 // expansion stack, only to take it right back off.
511 if (MI->getNumTokens() == 0) {
512 // No need for arg info.
513 if (Args) Args->destroy(*this);
514
Eli Friedman0834a4b2013-09-19 00:41:32 +0000515 // Propagate whitespace info as if we had pushed, then popped,
516 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000517 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000518 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000519 ++NumFastMacroExpanded;
520 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000521 } else if (MI->getNumTokens() == 1 &&
522 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
523 *this)) {
524 // Otherwise, if this macro expands into a single trivially-expanded
525 // token: expand it now. This handles common cases like
526 // "#define VAL 42".
527
528 // No need for arg info.
529 if (Args) Args->destroy(*this);
530
531 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
532 // identifier to the expanded token.
533 bool isAtStartOfLine = Identifier.isAtStartOfLine();
534 bool hasLeadingSpace = Identifier.hasLeadingSpace();
535
536 // Replace the result token.
537 Identifier = MI->getReplacementToken(0);
538
539 // Restore the StartOfLine/LeadingSpace markers.
540 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
541 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
542
543 // Update the tokens location to include both its expansion and physical
544 // locations.
545 SourceLocation Loc =
546 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
547 ExpansionEnd,Identifier.getLength());
548 Identifier.setLocation(Loc);
549
550 // If this is a disabled macro or #define X X, we must mark the result as
551 // unexpandable.
552 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
553 if (MacroInfo *NewMI = getMacroInfo(NewII))
554 if (!NewMI->isEnabled() || NewMI == MI) {
555 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000556 // Don't warn for "#define X X" like "#define bool bool" from
557 // stdbool.h.
558 if (NewMI != MI || MI->isFunctionLike())
559 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000560 }
561 }
562
563 // Since this is not an identifier token, it can't be macro expanded, so
564 // we're done.
565 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000566 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000567 }
568
569 // Start expanding the macro.
570 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000571 return false;
572}
573
Richard Trieu79b45382013-07-23 18:01:49 +0000574enum Bracket {
575 Brace,
576 Paren
577};
578
579/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
580/// token vector are properly nested.
581static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
582 SmallVector<Bracket, 8> Brackets;
583 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
584 E = Tokens.end();
585 I != E; ++I) {
586 if (I->is(tok::l_paren)) {
587 Brackets.push_back(Paren);
588 } else if (I->is(tok::r_paren)) {
589 if (Brackets.empty() || Brackets.back() == Brace)
590 return false;
591 Brackets.pop_back();
592 } else if (I->is(tok::l_brace)) {
593 Brackets.push_back(Brace);
594 } else if (I->is(tok::r_brace)) {
595 if (Brackets.empty() || Brackets.back() == Paren)
596 return false;
597 Brackets.pop_back();
598 }
599 }
600 if (!Brackets.empty())
601 return false;
602 return true;
603}
604
605/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
606/// vector of tokens in NewTokens. The new number of arguments will be placed
607/// in NumArgs and the ranges which need to surrounded in parentheses will be
608/// in ParenHints.
609/// Returns false if the token stream cannot be changed. If this is because
610/// of an initializer list starting a macro argument, the range of those
611/// initializer lists will be place in InitLists.
612static bool GenerateNewArgTokens(Preprocessor &PP,
613 SmallVectorImpl<Token> &OldTokens,
614 SmallVectorImpl<Token> &NewTokens,
615 unsigned &NumArgs,
616 SmallVectorImpl<SourceRange> &ParenHints,
617 SmallVectorImpl<SourceRange> &InitLists) {
618 if (!CheckMatchedBrackets(OldTokens))
619 return false;
620
621 // Once it is known that the brackets are matched, only a simple count of the
622 // braces is needed.
623 unsigned Braces = 0;
624
625 // First token of a new macro argument.
626 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
627
628 // First closing brace in a new macro argument. Used to generate
629 // SourceRanges for InitLists.
630 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
631 NumArgs = 0;
632 Token TempToken;
633 // Set to true when a macro separator token is found inside a braced list.
634 // If true, the fixed argument spans multiple old arguments and ParenHints
635 // will be updated.
636 bool FoundSeparatorToken = false;
637 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
638 E = OldTokens.end();
639 I != E; ++I) {
640 if (I->is(tok::l_brace)) {
641 ++Braces;
642 } else if (I->is(tok::r_brace)) {
643 --Braces;
644 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
645 ClosingBrace = I;
646 } else if (I->is(tok::eof)) {
647 // EOF token is used to separate macro arguments
648 if (Braces != 0) {
649 // Assume comma separator is actually braced list separator and change
650 // it back to a comma.
651 FoundSeparatorToken = true;
652 I->setKind(tok::comma);
653 I->setLength(1);
654 } else { // Braces == 0
655 // Separator token still separates arguments.
656 ++NumArgs;
657
658 // If the argument starts with a brace, it can't be fixed with
659 // parentheses. A different diagnostic will be given.
660 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
661 InitLists.push_back(
662 SourceRange(ArgStartIterator->getLocation(),
663 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
664 ClosingBrace = E;
665 }
666
667 // Add left paren
668 if (FoundSeparatorToken) {
669 TempToken.startToken();
670 TempToken.setKind(tok::l_paren);
671 TempToken.setLocation(ArgStartIterator->getLocation());
672 TempToken.setLength(0);
673 NewTokens.push_back(TempToken);
674 }
675
676 // Copy over argument tokens
677 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
678
679 // Add right paren and store the paren locations in ParenHints
680 if (FoundSeparatorToken) {
681 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
682 TempToken.startToken();
683 TempToken.setKind(tok::r_paren);
684 TempToken.setLocation(Loc);
685 TempToken.setLength(0);
686 NewTokens.push_back(TempToken);
687 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
688 Loc));
689 }
690
691 // Copy separator token
692 NewTokens.push_back(*I);
693
694 // Reset values
695 ArgStartIterator = I + 1;
696 FoundSeparatorToken = false;
697 }
698 }
699 }
700
701 return !ParenHints.empty() && InitLists.empty();
702}
703
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000704/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
705/// token is the '(' of the macro, this method is invoked to read all of the
706/// actual arguments specified for the macro invocation. This returns null on
707/// error.
708MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
709 MacroInfo *MI,
710 SourceLocation &MacroEnd) {
711 // The number of fixed arguments to parse.
712 unsigned NumFixedArgsLeft = MI->getNumArgs();
713 bool isVariadic = MI->isVariadic();
714
715 // Outer loop, while there are more arguments, keep reading them.
716 Token Tok;
717
718 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
719 // an argument value in a macro could expand to ',' or '(' or ')'.
720 LexUnexpandedToken(Tok);
721 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
722
723 // ArgTokens - Build up a list of tokens that make up each argument. Each
724 // argument is separated by an EOF token. Use a SmallVector so we can avoid
725 // heap allocations in the common case.
726 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000727 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000728
Richard Trieu79b45382013-07-23 18:01:49 +0000729 SourceLocation TooManyArgsLoc;
730
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000731 unsigned NumActuals = 0;
732 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000733 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
734 break;
735
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000736 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
737 "only expect argument separators here");
738
739 unsigned ArgTokenStart = ArgTokens.size();
740 SourceLocation ArgStartLoc = Tok.getLocation();
741
742 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
743 // that we already consumed the first one.
744 unsigned NumParens = 0;
745
746 while (1) {
747 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
748 // an argument value in a macro could expand to ',' or '(' or ')'.
749 LexUnexpandedToken(Tok);
750
751 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000752 if (!ContainsCodeCompletionTok) {
753 Diag(MacroName, diag::err_unterm_macro_invoc);
754 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
755 << MacroName.getIdentifierInfo();
756 // Do not lose the EOF/EOD. Return it to the client.
757 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000758 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000759 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000760 // Do not lose the EOF/EOD.
761 Token *Toks = new Token[1];
762 Toks[0] = Tok;
763 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000764 break;
765 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000766 } else if (Tok.is(tok::r_paren)) {
767 // If we found the ) token, the macro arg list is done.
768 if (NumParens-- == 0) {
769 MacroEnd = Tok.getLocation();
770 break;
771 }
772 } else if (Tok.is(tok::l_paren)) {
773 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000774 } else if (Tok.is(tok::comma) && NumParens == 0 &&
775 !(Tok.getFlags() & Token::IgnoredComma)) {
776 // In Microsoft-compatibility mode, single commas from nested macro
777 // expansions should not be considered as argument separators. We test
778 // for this with the IgnoredComma token flag above.
779
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000780 // Comma ends this argument if there are more fixed arguments expected.
781 // However, if this is a variadic macro, and this is part of the
782 // variadic part, then the comma is just an argument token.
783 if (!isVariadic) break;
784 if (NumFixedArgsLeft > 1)
785 break;
786 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
787 // If this is a comment token in the argument list and we're just in
788 // -C mode (not -CC mode), discard the comment.
789 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000790 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000791 // Reading macro arguments can cause macros that we are currently
792 // expanding from to be popped off the expansion stack. Doing so causes
793 // them to be reenabled for expansion. Here we record whether any
794 // identifiers we lex as macro arguments correspond to disabled macros.
795 // If so, we mark the token as noexpand. This is a subtle aspect of
796 // C99 6.10.3.4p2.
797 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
798 if (!MI->isEnabled())
799 Tok.setFlag(Token::DisableExpand);
800 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000801 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000802 if (CodeComplete)
803 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
804 MI, NumActuals);
805 // Don't mark that we reached the code-completion point because the
806 // parser is going to handle the token and there will be another
807 // code-completion callback.
808 }
809
810 ArgTokens.push_back(Tok);
811 }
812
813 // If this was an empty argument list foo(), don't add this as an empty
814 // argument.
815 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
816 break;
817
818 // If this is not a variadic macro, and too many args were specified, emit
819 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000820 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000821 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000822 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
823 else
824 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000825 }
826
Richard Trieu79b45382013-07-23 18:01:49 +0000827 // Empty arguments are standard in C99 and C++0x, and are supported as an
828 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000829 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000830 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000831 diag::warn_cxx98_compat_empty_fnmacro_arg :
832 diag::ext_empty_fnmacro_arg);
833
834 // Add a marker EOF token to the end of the token list for this argument.
835 Token EOFTok;
836 EOFTok.startToken();
837 EOFTok.setKind(tok::eof);
838 EOFTok.setLocation(Tok.getLocation());
839 EOFTok.setLength(0);
840 ArgTokens.push_back(EOFTok);
841 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000842 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000843 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000844 }
845
846 // Okay, we either found the r_paren. Check to see if we parsed too few
847 // arguments.
848 unsigned MinArgsExpected = MI->getNumArgs();
849
Richard Trieu79b45382013-07-23 18:01:49 +0000850 // If this is not a variadic macro, and too many args were specified, emit
851 // an error.
852 if (!isVariadic && NumActuals > MinArgsExpected &&
853 !ContainsCodeCompletionTok) {
854 // Emit the diagnostic at the macro name in case there is a missing ).
855 // Emitting it at the , could be far away from the macro name.
856 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
857 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
858 << MacroName.getIdentifierInfo();
859
860 // Commas from braced initializer lists will be treated as argument
861 // separators inside macros. Attempt to correct for this with parentheses.
862 // TODO: See if this can be generalized to angle brackets for templates
863 // inside macro arguments.
864
Bob Wilson57217352013-07-27 21:59:57 +0000865 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000866 unsigned FixedNumArgs = 0;
867 SmallVector<SourceRange, 4> ParenHints, InitLists;
868 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
869 ParenHints, InitLists)) {
870 if (!InitLists.empty()) {
871 DiagnosticBuilder DB =
872 Diag(MacroName,
873 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000874 for (const SourceRange &Range : InitLists)
875 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000876 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000877 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000878 }
879 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000880 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000881
882 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000883 for (const SourceRange &ParenLocation : ParenHints) {
884 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
885 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000886 }
887 ArgTokens.swap(FixedArgTokens);
888 NumActuals = FixedNumArgs;
889 }
890
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000891 // See MacroArgs instance var for description of this.
892 bool isVarargsElided = false;
893
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000894 if (ContainsCodeCompletionTok) {
895 // Recover from not-fully-formed macro invocation during code-completion.
896 Token EOFTok;
897 EOFTok.startToken();
898 EOFTok.setKind(tok::eof);
899 EOFTok.setLocation(Tok.getLocation());
900 EOFTok.setLength(0);
901 for (; NumActuals < MinArgsExpected; ++NumActuals)
902 ArgTokens.push_back(EOFTok);
903 }
904
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000905 if (NumActuals < MinArgsExpected) {
906 // There are several cases where too few arguments is ok, handle them now.
907 if (NumActuals == 0 && MinArgsExpected == 1) {
908 // #define A(X) or #define A(...) ---> A()
909
910 // If there is exactly one argument, and that argument is missing,
911 // then we have an empty "()" argument empty list. This is fine, even if
912 // the macro expects one argument (the argument is just empty).
913 isVarargsElided = MI->isVariadic();
914 } else if (MI->isVariadic() &&
915 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
916 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
917 // Varargs where the named vararg parameter is missing: OK as extension.
918 // #define A(x, ...)
919 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000920 //
921 // If the macro contains the comma pasting extension, the diagnostic
922 // is suppressed; we know we'll get another diagnostic later.
923 if (!MI->hasCommaPasting()) {
924 Diag(Tok, diag::ext_missing_varargs_arg);
925 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
926 << MacroName.getIdentifierInfo();
927 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000928
929 // Remember this occurred, allowing us to elide the comma when used for
930 // cases like:
931 // #define A(x, foo...) blah(a, ## foo)
932 // #define B(x, ...) blah(a, ## __VA_ARGS__)
933 // #define C(...) blah(a, ## __VA_ARGS__)
934 // A(x) B(x) C()
935 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000936 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000937 // Otherwise, emit the error.
938 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000939 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
940 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000941 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000942 }
943
944 // Add a marker EOF token to the end of the token list for this argument.
945 SourceLocation EndLoc = Tok.getLocation();
946 Tok.startToken();
947 Tok.setKind(tok::eof);
948 Tok.setLocation(EndLoc);
949 Tok.setLength(0);
950 ArgTokens.push_back(Tok);
951
952 // If we expect two arguments, add both as empty.
953 if (NumActuals == 0 && MinArgsExpected == 2)
954 ArgTokens.push_back(Tok);
955
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000956 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
957 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000958 // Emit the diagnostic at the macro name in case there is a missing ).
959 // Emitting it at the , could be far away from the macro name.
960 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000961 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
962 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000963 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000964 }
965
966 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
967}
968
969/// \brief Keeps macro expanded tokens for TokenLexers.
970//
971/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
972/// going to lex in the cache and when it finishes the tokens are removed
973/// from the end of the cache.
974Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
975 ArrayRef<Token> tokens) {
976 assert(tokLexer);
977 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000978 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000979
980 size_t newIndex = MacroExpandedTokens.size();
981 bool cacheNeedsToGrow = tokens.size() >
982 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
983 MacroExpandedTokens.append(tokens.begin(), tokens.end());
984
985 if (cacheNeedsToGrow) {
986 // Go through all the TokenLexers whose 'Tokens' pointer points in the
987 // buffer and update the pointers to the (potential) new buffer array.
988 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
989 TokenLexer *prevLexer;
990 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000991 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000992 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
993 }
994 }
995
996 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
997 return MacroExpandedTokens.data() + newIndex;
998}
999
1000void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1001 assert(!MacroExpandingLexersStack.empty());
1002 size_t tokIndex = MacroExpandingLexersStack.back().second;
1003 assert(tokIndex < MacroExpandedTokens.size());
1004 // Pop the cached macro expanded tokens from the end.
1005 MacroExpandedTokens.resize(tokIndex);
1006 MacroExpandingLexersStack.pop_back();
1007}
1008
1009/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1010/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1011/// the identifier tokens inserted.
1012static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1013 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001014 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001015 struct tm *TM = localtime(&TT);
1016
1017 static const char * const Months[] = {
1018 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1019 };
1020
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001021 {
1022 SmallString<32> TmpBuffer;
1023 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1024 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1025 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001026 Token TmpTok;
1027 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001028 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001029 DATELoc = TmpTok.getLocation();
1030 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001031
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001032 {
1033 SmallString<32> TmpBuffer;
1034 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1035 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1036 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001037 Token TmpTok;
1038 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001039 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001040 TIMELoc = TmpTok.getLocation();
1041 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001042}
1043
1044
1045/// HasFeature - Return true if we recognize and implement the feature
1046/// specified by the identifier as a standard language feature.
1047static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
1048 const LangOptions &LangOpts = PP.getLangOpts();
1049 StringRef Feature = II->getName();
1050
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)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001056 .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
1057 .Case("attribute_analyzer_noreturn", true)
1058 .Case("attribute_availability", true)
1059 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001060 .Case("attribute_availability_app_extension", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001061 .Case("attribute_cf_returns_not_retained", true)
1062 .Case("attribute_cf_returns_retained", true)
1063 .Case("attribute_deprecated_with_message", true)
1064 .Case("attribute_ext_vector_type", true)
1065 .Case("attribute_ns_returns_not_retained", true)
1066 .Case("attribute_ns_returns_retained", true)
1067 .Case("attribute_ns_consumes_self", true)
1068 .Case("attribute_ns_consumed", true)
1069 .Case("attribute_cf_consumed", true)
1070 .Case("attribute_objc_ivar_unused", true)
1071 .Case("attribute_objc_method_family", true)
1072 .Case("attribute_overloadable", true)
1073 .Case("attribute_unavailable_with_message", true)
1074 .Case("attribute_unused_on_fields", true)
1075 .Case("blocks", LangOpts.Blocks)
1076 .Case("c_thread_safety_attributes", true)
1077 .Case("cxx_exceptions", LangOpts.CXXExceptions)
1078 .Case("cxx_rtti", LangOpts.RTTI)
1079 .Case("enumerator_attributes", true)
1080 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1081 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1082 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
1083 // Objective-C features
1084 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1085 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
1086 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
1087 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1088 .Case("objc_fixed_enum", LangOpts.ObjC2)
1089 .Case("objc_instancetype", LangOpts.ObjC2)
1090 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1091 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1092 .Case("objc_property_explicit_atomic",
1093 true) // Does clang support explicit "atomic" keyword?
1094 .Case("objc_protocol_qualifier_mangling", true)
1095 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1096 .Case("ownership_holds", true)
1097 .Case("ownership_returns", true)
1098 .Case("ownership_takes", true)
1099 .Case("objc_bool", true)
1100 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1101 .Case("objc_array_literals", LangOpts.ObjC2)
1102 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1103 .Case("objc_boxed_expressions", LangOpts.ObjC2)
1104 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001105 .Case("objc_bridge_id", true)
1106 .Case("objc_bridge_id_on_typedefs", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001107 // C11 features
1108 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001109 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001110 .Case("c_atomic", LangOpts.C11)
1111 .Case("c_generic_selections", LangOpts.C11)
1112 .Case("c_static_assert", LangOpts.C11)
1113 .Case("c_thread_local",
1114 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1115 // C++11 features
1116 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1117 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1118 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001119 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001120 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1121 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1122 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1123 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
1124 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1125 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1126 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1127 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1128 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1129 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1130 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1131 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1132 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1133 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1134 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1135 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1136 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1137 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1138 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1139 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1140 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1141 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1142 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1143 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1144 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1145 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1146 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1147 .Case("cxx_thread_local",
1148 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1149 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1150 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1151 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1152 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1153 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
1154 // C++1y features
1155 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1156 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1157 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1158 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1159 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1160 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1161 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1162 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1163 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
1164 // C++ TSes
1165 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1166 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1167 // FIXME: Should this be __has_feature or __has_extension?
1168 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1169 // Type traits
1170 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1171 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1172 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1173 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1174 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1175 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1176 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1177 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1178 .Case("is_abstract", LangOpts.CPlusPlus)
1179 .Case("is_base_of", LangOpts.CPlusPlus)
1180 .Case("is_class", LangOpts.CPlusPlus)
1181 .Case("is_constructible", LangOpts.CPlusPlus)
1182 .Case("is_convertible_to", LangOpts.CPlusPlus)
1183 .Case("is_empty", LangOpts.CPlusPlus)
1184 .Case("is_enum", LangOpts.CPlusPlus)
1185 .Case("is_final", LangOpts.CPlusPlus)
1186 .Case("is_literal", LangOpts.CPlusPlus)
1187 .Case("is_standard_layout", LangOpts.CPlusPlus)
1188 .Case("is_pod", LangOpts.CPlusPlus)
1189 .Case("is_polymorphic", LangOpts.CPlusPlus)
1190 .Case("is_sealed", LangOpts.MicrosoftExt)
1191 .Case("is_trivial", LangOpts.CPlusPlus)
1192 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1193 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1194 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1195 .Case("is_union", LangOpts.CPlusPlus)
1196 .Case("modules", LangOpts.Modules)
1197 .Case("tls", PP.getTargetInfo().isTLSSupported())
1198 .Case("underlying_type", LangOpts.CPlusPlus)
1199 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001200}
1201
1202/// HasExtension - Return true if we recognize and implement the feature
1203/// specified by the identifier, either as an extension or a standard language
1204/// feature.
1205static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1206 if (HasFeature(PP, II))
1207 return true;
1208
1209 // If the use of an extension results in an error diagnostic, extensions are
1210 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001211 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1212 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001213 return false;
1214
1215 const LangOptions &LangOpts = PP.getLangOpts();
1216 StringRef Extension = II->getName();
1217
1218 // Normalize the extension name, __foo__ becomes foo.
1219 if (Extension.startswith("__") && Extension.endswith("__") &&
1220 Extension.size() >= 4)
1221 Extension = Extension.substr(2, Extension.size() - 4);
1222
1223 // Because we inherit the feature list from HasFeature, this string switch
1224 // must be less restrictive than HasFeature's.
1225 return llvm::StringSwitch<bool>(Extension)
1226 // C11 features supported by other languages as extensions.
1227 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001228 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001229 .Case("c_atomic", true)
1230 .Case("c_generic_selections", true)
1231 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001232 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001233 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001234 .Case("cxx_atomic", LangOpts.CPlusPlus)
1235 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1236 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1237 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1238 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1239 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1240 .Case("cxx_override_control", LangOpts.CPlusPlus)
1241 .Case("cxx_range_for", LangOpts.CPlusPlus)
1242 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1243 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Eric Fiselier7aa0d4a2015-05-12 22:37:23 +00001244 .Case("cxx_variadic_templates", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001245 // C++1y features supported by other languages as extensions.
1246 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001247 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001248 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001249 .Default(false);
1250}
1251
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001252/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1253/// or '__has_include_next("path")' expression.
1254/// Returns true if successful.
1255static bool EvaluateHasIncludeCommon(Token &Tok,
1256 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001257 const DirectoryLookup *LookupFrom,
1258 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001259 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001260 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001261 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001262
Aaron Ballman6ce00002013-01-16 19:32:21 +00001263 // These expressions are only allowed within a preprocessor directive.
1264 if (!PP.isParsingIfOrElifDirective()) {
1265 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001266 // Return a valid identifier token.
1267 assert(Tok.is(tok::identifier));
1268 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001269 return false;
1270 }
1271
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001272 // Get '('.
1273 PP.LexNonComment(Tok);
1274
1275 // Ensure we have a '('.
1276 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001277 // No '(', use end of last token.
1278 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001279 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001280 // If the next token looks like a filename or the start of one,
1281 // assume it is and process it as such.
1282 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1283 !Tok.is(tok::less))
1284 return false;
1285 } else {
1286 // Save '(' location for possible missing ')' message.
1287 LParenLoc = Tok.getLocation();
1288
Eli Friedmanec94b612013-01-09 02:20:00 +00001289 if (PP.getCurrentLexer()) {
1290 // Get the file name.
1291 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1292 } else {
1293 // We're in a macro, so we can't use LexIncludeFilename; just
1294 // grab the next token.
1295 PP.Lex(Tok);
1296 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001297 }
1298
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001299 // Reserve a buffer to get the spelling.
1300 SmallString<128> FilenameBuffer;
1301 StringRef Filename;
1302 SourceLocation EndLoc;
1303
1304 switch (Tok.getKind()) {
1305 case tok::eod:
1306 // If the token kind is EOD, the error has already been diagnosed.
1307 return false;
1308
1309 case tok::angle_string_literal:
1310 case tok::string_literal: {
1311 bool Invalid = false;
1312 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1313 if (Invalid)
1314 return false;
1315 break;
1316 }
1317
1318 case tok::less:
1319 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1320 // case, glue the tokens together into FilenameBuffer and interpret those.
1321 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001322 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1323 // Let the caller know a <eod> was found by changing the Token kind.
1324 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001325 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001326 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001327 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001328 break;
1329 default:
1330 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1331 return false;
1332 }
1333
Richard Trieuda031982012-10-22 20:28:48 +00001334 SourceLocation FilenameLoc = Tok.getLocation();
1335
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001336 // Get ')'.
1337 PP.LexNonComment(Tok);
1338
1339 // Ensure we have a trailing ).
1340 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001341 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1342 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001343 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001344 return false;
1345 }
1346
1347 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1348 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1349 // error.
1350 if (Filename.empty())
1351 return false;
1352
1353 // Search include directories.
1354 const DirectoryLookup *CurDir;
1355 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001356 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1357 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001358
1359 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001360 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001361}
1362
1363/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1364/// Returns true if successful.
1365static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1366 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001367 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001368}
1369
1370/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1371/// Returns true if successful.
1372static bool EvaluateHasIncludeNext(Token &Tok,
1373 IdentifierInfo *II, Preprocessor &PP) {
1374 // __has_include_next is like __has_include, except that we start
1375 // searching after the current found directory. If we can't do this,
1376 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001377 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001378 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001379 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001380 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001381 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001382 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001383 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001384 } else if (PP.getCurrentSubmodule()) {
1385 // Start looking up in the directory *after* the one in which the current
1386 // file would be found, if any.
1387 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1388 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1389 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001390 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001391 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1392 } else {
1393 // Start looking up in the next directory.
1394 ++Lookup;
1395 }
1396
Richard Smith25d50752014-10-20 00:15:49 +00001397 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001398}
1399
Douglas Gregorc83de302012-09-25 15:44:52 +00001400/// \brief Process __building_module(identifier) expression.
1401/// \returns true if we are building the named module, false otherwise.
1402static bool EvaluateBuildingModule(Token &Tok,
1403 IdentifierInfo *II, Preprocessor &PP) {
1404 // Get '('.
1405 PP.LexNonComment(Tok);
1406
1407 // Ensure we have a '('.
1408 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001409 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1410 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001411 return false;
1412 }
1413
1414 // Save '(' location for possible missing ')' message.
1415 SourceLocation LParenLoc = Tok.getLocation();
1416
1417 // Get the module name.
1418 PP.LexNonComment(Tok);
1419
1420 // Ensure that we have an identifier.
1421 if (Tok.isNot(tok::identifier)) {
1422 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1423 return false;
1424 }
1425
1426 bool Result
1427 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1428
1429 // Get ')'.
1430 PP.LexNonComment(Tok);
1431
1432 // Ensure we have a trailing ).
1433 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001434 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1435 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001436 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001437 return false;
1438 }
1439
1440 return Result;
1441}
1442
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001443/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1444/// as a builtin macro, handle it and return the next token as 'Tok'.
1445void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1446 // Figure out which token this is.
1447 IdentifierInfo *II = Tok.getIdentifierInfo();
1448 assert(II && "Can't be a macro without id info!");
1449
1450 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1451 // invoke the pragma handler, then lex the token after it.
1452 if (II == Ident_Pragma)
1453 return Handle_Pragma(Tok);
1454 else if (II == Ident__pragma) // in non-MS mode this is null
1455 return HandleMicrosoft__pragma(Tok);
1456
1457 ++NumBuiltinMacroExpanded;
1458
1459 SmallString<128> TmpBuffer;
1460 llvm::raw_svector_ostream OS(TmpBuffer);
1461
1462 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001463 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001464 Tok.clearFlag(Token::NeedsCleaning);
1465
1466 if (II == Ident__LINE__) {
1467 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1468 // source file) of the current source line (an integer constant)". This can
1469 // be affected by #line.
1470 SourceLocation Loc = Tok.getLocation();
1471
1472 // Advance to the location of the first _, this might not be the first byte
1473 // of the token if it starts with an escaped newline.
1474 Loc = AdvanceToTokenCharacter(Loc, 0);
1475
1476 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1477 // a macro expansion. This doesn't matter for object-like macros, but
1478 // can matter for a function-like macro that expands to contain __LINE__.
1479 // Skip down through expansion points until we find a file loc for the
1480 // end of the expansion history.
1481 Loc = SourceMgr.getExpansionRange(Loc).second;
1482 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1483
1484 // __LINE__ expands to a simple numeric value.
1485 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1486 Tok.setKind(tok::numeric_constant);
1487 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1488 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1489 // character string literal)". This can be affected by #line.
1490 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1491
1492 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1493 // #include stack instead of the current file.
1494 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1495 SourceLocation NextLoc = PLoc.getIncludeLoc();
1496 while (NextLoc.isValid()) {
1497 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1498 if (PLoc.isInvalid())
1499 break;
1500
1501 NextLoc = PLoc.getIncludeLoc();
1502 }
1503 }
1504
1505 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1506 SmallString<128> FN;
1507 if (PLoc.isValid()) {
1508 FN += PLoc.getFilename();
1509 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001510 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001511 }
1512 Tok.setKind(tok::string_literal);
1513 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001514 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001515 if (!DATELoc.isValid())
1516 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1517 Tok.setKind(tok::string_literal);
1518 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1519 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1520 Tok.getLocation(),
1521 Tok.getLength()));
1522 return;
1523 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001524 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001525 if (!TIMELoc.isValid())
1526 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1527 Tok.setKind(tok::string_literal);
1528 Tok.setLength(strlen("\"hh:mm:ss\""));
1529 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1530 Tok.getLocation(),
1531 Tok.getLength()));
1532 return;
1533 } else if (II == Ident__INCLUDE_LEVEL__) {
1534 // Compute the presumed include depth of this token. This can be affected
1535 // by GNU line markers.
1536 unsigned Depth = 0;
1537
1538 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1539 if (PLoc.isValid()) {
1540 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1541 for (; PLoc.isValid(); ++Depth)
1542 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1543 }
1544
1545 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1546 OS << Depth;
1547 Tok.setKind(tok::numeric_constant);
1548 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001549 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001550 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1551 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1552
1553 // Get the file that we are lexing out of. If we're currently lexing from
1554 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001555 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001556 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1557
1558 if (TheLexer)
1559 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1560
1561 const char *Result;
1562 if (CurFile) {
1563 time_t TT = CurFile->getModificationTime();
1564 struct tm *TM = localtime(&TT);
1565 Result = asctime(TM);
1566 } else {
1567 Result = "??? ??? ?? ??:??:?? ????\n";
1568 }
1569 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001570 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001571 Tok.setKind(tok::string_literal);
1572 } else if (II == Ident__COUNTER__) {
1573 // __COUNTER__ expands to a simple numeric value.
1574 OS << CounterValue++;
1575 Tok.setKind(tok::numeric_constant);
1576 } else if (II == Ident__has_feature ||
1577 II == Ident__has_extension ||
1578 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001579 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001580 II == Ident__has_attribute ||
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001581 II == Ident__has_declspec ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001582 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001583 // The argument to these builtins should be a parenthesized identifier.
1584 SourceLocation StartLoc = Tok.getLocation();
1585
1586 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001587 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001588 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001589
1590 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001591 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001592 if (Tok.is(tok::l_paren)) {
1593 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001594 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001595 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001596 // If we're checking __has_cpp_attribute, it is possible to receive a
1597 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001598 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001599 bool IsScopeValid = true;
1600 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1601 LexUnexpandedToken(Tok);
1602 // The first thing we read was not the feature, it was the scope.
1603 ScopeII = FeatureII;
Aaron Ballman918474c2014-11-14 14:40:49 +00001604 if ((FeatureII = Tok.getIdentifierInfo()))
Aaron Ballmana0344c52014-11-14 13:44:02 +00001605 LexUnexpandedToken(Tok);
1606 else
1607 IsScopeValid = false;
1608 }
1609 // Read the closing paren.
1610 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001611 IsValid = true;
1612 }
David Majnemerd6163622014-12-15 09:03:58 +00001613 // Eat tokens until ')'.
1614 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1615 Tok.isNot(tok::eof))
1616 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001617 }
1618
Aaron Ballmana0344c52014-11-14 13:44:02 +00001619 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001620 if (!IsValid)
1621 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001622 else if (II == Ident__is_identifier)
1623 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001624 else if (II == Ident__has_builtin) {
1625 // Check for a builtin is trivial.
1626 Value = FeatureII->getBuiltinID() != 0;
1627 } else if (II == Ident__has_attribute)
Aaron Ballmana6f759e2014-12-05 15:24:55 +00001628 Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001629 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001630 else if (II == Ident__has_cpp_attribute)
1631 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1632 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001633 else if (II == Ident__has_declspec)
1634 Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
1635 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001636 else if (II == Ident__has_extension)
1637 Value = HasExtension(*this, FeatureII);
1638 else {
1639 assert(II == Ident__has_feature && "Must be feature check");
1640 Value = HasFeature(*this, FeatureII);
1641 }
1642
David Majnemerd6163622014-12-15 09:03:58 +00001643 if (!IsValid)
1644 return;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001645 OS << Value;
David Majnemerd6163622014-12-15 09:03:58 +00001646 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001647 } else if (II == Ident__has_include ||
1648 II == Ident__has_include_next) {
1649 // The argument to these two builtins should be a parenthesized
1650 // file name string literal using angle brackets (<>) or
1651 // double-quotes ("").
1652 bool Value;
1653 if (II == Ident__has_include)
1654 Value = EvaluateHasInclude(Tok, II, *this);
1655 else
1656 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001657
1658 if (Tok.isNot(tok::r_paren))
1659 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001660 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001661 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001662 } else if (II == Ident__has_warning) {
1663 // The argument should be a parenthesized string literal.
1664 // The argument to these builtins should be a parenthesized identifier.
1665 SourceLocation StartLoc = Tok.getLocation();
1666 bool IsValid = false;
1667 bool Value = false;
1668 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001669 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001670 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001671 if (Tok.isNot(tok::l_paren)) {
1672 Diag(StartLoc, diag::err_warning_check_malformed);
1673 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001674 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001675
1676 LexUnexpandedToken(Tok);
1677 std::string WarningName;
1678 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001679 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1680 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001681 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001682 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1683 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001684 LexUnexpandedToken(Tok);
1685 break;
1686 }
1687
1688 // Is the end a ')'?
1689 if (!(IsValid = Tok.is(tok::r_paren))) {
1690 Diag(StartLoc, diag::err_warning_check_malformed);
1691 break;
1692 }
1693
Richard Smith3be1cb22014-08-07 00:24:21 +00001694 // FIXME: Should we accept "-R..." flags here, or should that be handled
1695 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001696 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1697 WarningName[1] != 'W') {
1698 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1699 break;
1700 }
1701
1702 // Finally, check if the warning flags maps to a diagnostic group.
1703 // We construct a SmallVector here to talk to getDiagnosticIDs().
1704 // Although we don't use the result, this isn't a hot path, and not
1705 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001706 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001707 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001708 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1709 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001710 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001711
David Majnemerd6163622014-12-15 09:03:58 +00001712 if (!IsValid)
1713 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001714 OS << (int)Value;
David Majnemerd6163622014-12-15 09:03:58 +00001715 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001716 } else if (II == Ident__building_module) {
1717 // The argument to this builtin should be an identifier. The
1718 // builtin evaluates to 1 when that identifier names the module we are
1719 // currently building.
1720 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1721 Tok.setKind(tok::numeric_constant);
1722 } else if (II == Ident__MODULE__) {
1723 // The current module as an identifier.
1724 OS << getLangOpts().CurrentModule;
1725 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1726 Tok.setIdentifierInfo(ModuleII);
1727 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001728 } else if (II == Ident__identifier) {
1729 SourceLocation Loc = Tok.getLocation();
1730
1731 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1732 // if the parens are missing.
1733 LexNonComment(Tok);
1734 if (Tok.isNot(tok::l_paren)) {
1735 // No '(', use end of last token.
1736 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1737 << II << tok::l_paren;
1738 // If the next token isn't valid as our argument, we can't recover.
1739 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1740 Tok.setKind(tok::identifier);
1741 return;
1742 }
1743
1744 SourceLocation LParenLoc = Tok.getLocation();
1745 LexNonComment(Tok);
1746
1747 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1748 Tok.setKind(tok::identifier);
1749 else {
1750 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1751 << Tok.getKind();
1752 // Don't walk past anything that's not a real token.
1753 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1754 return;
1755 }
1756
1757 // Discard the ')', preserving 'Tok' as our result.
1758 Token RParen;
1759 LexNonComment(RParen);
1760 if (RParen.isNot(tok::r_paren)) {
1761 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1762 << Tok.getKind() << tok::r_paren;
1763 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1764 }
1765 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001766 } else {
1767 llvm_unreachable("Unknown identifier!");
1768 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001769 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001770}
1771
1772void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1773 // If the 'used' status changed, and the macro requires 'unused' warning,
1774 // remove its SourceLocation from the warn-for-unused-macro locations.
1775 if (MI->isWarnIfUnused() && !MI->isUsed())
1776 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1777 MI->setIsUsed(true);
1778}