blob: aa4e8b67644a9e634ce1cfae914d2d8254c74776 [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 Smithb8b2ed62015-04-23 18:18:26 +000040 auto Pos = Macros.find(II);
Richard Smith20e883e2015-04-29 23:20:19 +000041 return Pos == Macros.end() ? nullptr : 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 Smithb8b2ed62015-04-23 18:18:26 +000048 MacroState &StoredMD = Macros[II];
49 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
54 // Set up the identifier as having associated macro history.
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000055 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000056 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000057 II->setHasMacroDefinition(false);
Richard Smith3981b172015-04-30 02:16:23 +000058 if (II->isFromAST())
Joao Matosc0d4c1b2012-08-31 21:34:27 +000059 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000060}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000061
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000062void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
63 MacroDirective *MD) {
64 assert(II && MD);
Richard Smithb8b2ed62015-04-23 18:18:26 +000065 MacroState &StoredMD = Macros[II];
66 assert(!StoredMD.getLatest() &&
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000067 "the macro history was modified before initializing it from a pch");
68 StoredMD = MD;
69 // Setup the identifier as having associated macro history.
70 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000071 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000072 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +000073}
74
Richard Smithb8b2ed62015-04-23 18:18:26 +000075ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
Richard Smithe56c8bc2015-04-22 00:26:11 +000076 MacroInfo *Macro,
77 ArrayRef<ModuleMacro *> Overrides,
78 bool &New) {
79 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +000080 ModuleMacro::Profile(ID, Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +000081
82 void *InsertPos;
83 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
84 New = false;
85 return MM;
86 }
87
Richard Smithb8b2ed62015-04-23 18:18:26 +000088 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
Richard Smithe56c8bc2015-04-22 00:26:11 +000089 ModuleMacros.InsertNode(MM, InsertPos);
90
91 // Each overridden macro is now overridden by one more macro.
92 bool HidAny = false;
93 for (auto *O : Overrides) {
94 HidAny |= (O->NumOverriddenBy == 0);
95 ++O->NumOverriddenBy;
96 }
97
98 // If we were the first overrider for any macro, it's no longer a leaf.
99 auto &LeafMacros = LeafModuleMacros[II];
100 if (HidAny) {
101 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
102 [](ModuleMacro *MM) {
103 return MM->NumOverriddenBy != 0;
104 }),
105 LeafMacros.end());
106 }
107
108 // The new macro is always a leaf macro.
109 LeafMacros.push_back(MM);
Richard Smith20e883e2015-04-29 23:20:19 +0000110 // The identifier now has defined macros (that may or may not be visible).
111 II->setHasMacroDefinition(true);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000112
113 New = true;
114 return MM;
115}
116
Richard Smithb8b2ed62015-04-23 18:18:26 +0000117ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) {
Richard Smith5dbef922015-04-22 02:09:43 +0000118 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000119 ModuleMacro::Profile(ID, Mod, II);
Richard Smith5dbef922015-04-22 02:09:43 +0000120
121 void *InsertPos;
122 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
123}
124
Richard Smith20e883e2015-04-29 23:20:19 +0000125void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
Richard Smith753e0072015-04-27 23:21:38 +0000126 ModuleMacroInfo &Info) {
Richard Smitha7e2cc62015-05-01 01:53:09 +0000127 assert(Info.ActiveModuleMacrosGeneration != VisibleModules.getGeneration() &&
Richard Smith753e0072015-04-27 23:21:38 +0000128 "don't need to update this macro name info");
Richard Smitha7e2cc62015-05-01 01:53:09 +0000129 Info.ActiveModuleMacrosGeneration = VisibleModules.getGeneration();
Richard Smith753e0072015-04-27 23:21:38 +0000130
131 auto Leaf = LeafModuleMacros.find(II);
132 if (Leaf == LeafModuleMacros.end()) {
133 // No imported macros at all: nothing to do.
134 return;
135 }
136
137 Info.ActiveModuleMacros.clear();
138
139 // Every macro that's locally overridden is overridden by a visible macro.
140 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
141 for (auto *O : Info.OverriddenMacros)
142 NumHiddenOverrides[O] = -1;
143
144 // Collect all macros that are not overridden by a visible macro.
145 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf->second.begin(),
146 Leaf->second.end());
147 while (!Worklist.empty()) {
148 auto *MM = Worklist.pop_back_val();
Richard Smitha7e2cc62015-05-01 01:53:09 +0000149 if (VisibleModules.isVisible(MM->getOwningModule())) {
Richard Smith753e0072015-04-27 23:21:38 +0000150 // We only care about collecting definitions; undefinitions only act
151 // to override other definitions.
152 if (MM->getMacroInfo())
153 Info.ActiveModuleMacros.push_back(MM);
154 } else {
155 for (auto *O : MM->overrides())
156 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
157 Worklist.push_back(O);
158 }
159 }
Richard Smith20e883e2015-04-29 23:20:19 +0000160 // Our reverse postorder walk found the macros in reverse order.
161 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
Richard Smith753e0072015-04-27 23:21:38 +0000162
163 // Determine whether the macro name is ambiguous.
Richard Smith753e0072015-04-27 23:21:38 +0000164 MacroInfo *MI = nullptr;
Richard Smith20e883e2015-04-29 23:20:19 +0000165 bool IsSystemMacro = true;
166 bool IsAmbiguous = false;
167 if (auto *MD = Info.MD) {
168 while (MD && isa<VisibilityMacroDirective>(MD))
169 MD = MD->getPrevious();
170 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
171 MI = DMD->getInfo();
172 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
173 }
Richard Smith753e0072015-04-27 23:21:38 +0000174 }
175 for (auto *Active : Info.ActiveModuleMacros) {
176 auto *NewMI = Active->getMacroInfo();
177
178 // Before marking the macro as ambiguous, check if this is a case where
179 // both macros are in system headers. If so, we trust that the system
180 // did not get it wrong. This also handles cases where Clang's own
181 // headers have a different spelling of certain system macros:
182 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
183 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
184 //
185 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
186 // overrides the system limits.h's macros, so there's no conflict here.
Richard Smith20e883e2015-04-29 23:20:19 +0000187 if (MI && NewMI != MI &&
188 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
189 IsAmbiguous = true;
190 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
191 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
192 MI = NewMI;
Richard Smith753e0072015-04-27 23:21:38 +0000193 }
Richard Smith20e883e2015-04-29 23:20:19 +0000194 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
Richard Smith753e0072015-04-27 23:21:38 +0000195}
196
Richard Smith3ffa61d2015-04-30 23:10:40 +0000197void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
198 ArrayRef<ModuleMacro*> Leaf;
199 auto LeafIt = LeafModuleMacros.find(II);
200 if (LeafIt != LeafModuleMacros.end())
201 Leaf = LeafIt->second;
202 const MacroState *State = nullptr;
203 auto Pos = Macros.find(II);
204 if (Pos != Macros.end())
205 State = &Pos->second;
206
207 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
208 if (State && State->isAmbiguous(*this, II))
209 llvm::errs() << " ambiguous";
Richard Smithd0014bf2015-04-30 23:42:10 +0000210 if (State && !State->getOverriddenMacros().empty()) {
Richard Smith3ffa61d2015-04-30 23:10:40 +0000211 llvm::errs() << " overrides";
212 for (auto *O : State->getOverriddenMacros())
213 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
214 }
215 llvm::errs() << "\n";
216
217 // Dump local macro directives.
218 for (auto *MD = State ? State->getLatest() : nullptr; MD;
219 MD = MD->getPrevious()) {
220 llvm::errs() << " ";
221 MD->dump();
222 }
223
224 // Dump module macros.
225 llvm::DenseSet<ModuleMacro*> Active;
226 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
227 Active.insert(MM);
228 llvm::DenseSet<ModuleMacro*> Visited;
229 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
230 while (!Worklist.empty()) {
231 auto *MM = Worklist.pop_back_val();
232 llvm::errs() << " ModuleMacro " << MM << " "
233 << MM->getOwningModule()->getFullModuleName();
234 if (!MM->getMacroInfo())
235 llvm::errs() << " undef";
236
237 if (Active.count(MM))
238 llvm::errs() << " active";
Richard Smitha7e2cc62015-05-01 01:53:09 +0000239 else if (!VisibleModules.isVisible(MM->getOwningModule()))
Richard Smith3ffa61d2015-04-30 23:10:40 +0000240 llvm::errs() << " hidden";
Richard Smith42413142015-05-15 20:05:43 +0000241 else if (MM->getMacroInfo())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000242 llvm::errs() << " overridden";
243
244 if (!MM->overrides().empty()) {
245 llvm::errs() << " overrides";
246 for (auto *O : MM->overrides()) {
247 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
248 if (Visited.insert(O).second)
249 Worklist.push_back(O);
250 }
251 }
252 llvm::errs() << "\n";
253 if (auto *MI = MM->getMacroInfo()) {
254 llvm::errs() << " ";
255 MI->dump();
256 llvm::errs() << "\n";
257 }
258 }
259}
260
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000261/// RegisterBuiltinMacro - Register the specified identifier in the identifier
262/// table and mark it as a builtin macro to be expanded.
263static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
264 // Get the identifier.
265 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
266
267 // Mark it as being a macro that is builtin.
268 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
269 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000270 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000271 return Id;
272}
273
274
275/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
276/// identifier table.
277void Preprocessor::RegisterBuiltinMacros() {
278 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
279 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
280 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
281 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
282 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
283 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
284
Aaron Ballmana0344c52014-11-14 13:44:02 +0000285 // C++ Standing Document Extensions.
Aaron Ballman416b1272015-05-11 14:09:50 +0000286 if (LangOpts.CPlusPlus)
287 Ident__has_cpp_attribute =
288 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
289 else
290 Ident__has_cpp_attribute = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +0000291
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000292 // GCC Extensions.
293 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
294 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
295 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
296
Richard Smithae385082014-03-15 00:06:08 +0000297 // Microsoft Extensions.
298 if (LangOpts.MicrosoftExt) {
299 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
300 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
301 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000302 Ident__identifier = nullptr;
303 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000304 }
305
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000306 // Clang Extensions.
307 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
308 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
309 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
310 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000311 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000312 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
313 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
314 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000315 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000316
Douglas Gregorc83de302012-09-25 15:44:52 +0000317 // Modules.
318 if (LangOpts.Modules) {
319 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
320
321 // __MODULE__
322 if (!LangOpts.CurrentModule.empty())
323 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
324 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000325 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000326 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000327 Ident__building_module = nullptr;
328 Ident__MODULE__ = nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +0000329 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000330}
331
332/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
333/// in its expansion, currently expands to that token literally.
334static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
335 const IdentifierInfo *MacroIdent,
336 Preprocessor &PP) {
337 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
338
339 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000340 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000341
342 // If the information about this identifier is out of date, update it from
343 // the external source.
344 if (II->isOutOfDate())
345 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
346
347 // If the identifier is a macro, and if that macro is enabled, it may be
348 // expanded so it's not a trivial expansion.
Richard Smith20e883e2015-04-29 23:20:19 +0000349 if (auto *ExpansionMI = PP.getMacroInfo(II))
Richard Smith3d5925b2015-04-29 23:26:13 +0000350 if (ExpansionMI->isEnabled() &&
Richard Smith20e883e2015-04-29 23:20:19 +0000351 // Fast expanding "#define X X" is ok, because X would be disabled.
352 II != MacroIdent)
353 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000354
355 // If this is an object-like macro invocation, it is safe to trivially expand
356 // it.
357 if (MI->isObjectLike()) return true;
358
359 // If this is a function-like macro invocation, it's safe to trivially expand
360 // as long as the identifier is not a macro argument.
361 for (MacroInfo::arg_iterator I = MI->arg_begin(), E = MI->arg_end();
362 I != E; ++I)
363 if (*I == II)
364 return false; // Identifier is a macro argument.
365
366 return true;
367}
368
369
370/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
371/// lexed is a '('. If so, consume the token and return true, if not, this
372/// method should have no observable side-effect on the lexed tokens.
373bool Preprocessor::isNextPPTokenLParen() {
374 // Do some quick tests for rejection cases.
375 unsigned Val;
376 if (CurLexer)
377 Val = CurLexer->isNextPPTokenLParen();
378 else if (CurPTHLexer)
379 Val = CurPTHLexer->isNextPPTokenLParen();
380 else
381 Val = CurTokenLexer->isNextTokenLParen();
382
383 if (Val == 2) {
384 // We have run off the end. If it's a source file we don't
385 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
386 // macro stack.
387 if (CurPPLexer)
388 return false;
389 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
390 IncludeStackInfo &Entry = IncludeMacroStack[i-1];
391 if (Entry.TheLexer)
392 Val = Entry.TheLexer->isNextPPTokenLParen();
393 else if (Entry.ThePTHLexer)
394 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
395 else
396 Val = Entry.TheTokenLexer->isNextTokenLParen();
397
398 if (Val != 2)
399 break;
400
401 // Ran off the end of a source file?
402 if (Entry.ThePPLexer)
403 return false;
404 }
405 }
406
407 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
408 // have found something that isn't a '(' or we found the end of the
409 // translation unit. In either case, return false.
410 return Val == 1;
411}
412
413/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
414/// expanded as a macro, handle it and return the next token as 'Identifier'.
415bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000416 const MacroDefinition &M) {
417 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000418
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000419 // If this is a macro expansion in the "#if !defined(x)" line for the file,
420 // then the macro could expand to different things in other contexts, we need
421 // to disable the optimization in this case.
422 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
423
424 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
425 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000426 if (Callbacks)
427 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
428 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000429 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000430 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000431 }
432
433 /// Args - If this is a function-like macro expansion, this contains,
434 /// for each macro argument, the list of tokens that were provided to the
435 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000436 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000437
438 // Remember where the end of the expansion occurred. For an object-like
439 // macro, this is the identifier. For a function-like macro, this is the ')'.
440 SourceLocation ExpansionEnd = Identifier.getLocation();
441
442 // If this is a function-like macro, read the arguments.
443 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000444 // Remember that we are now parsing the arguments to a macro invocation.
445 // Preprocessor directives used inside macro arguments are not portable, and
446 // this enables the warning.
447 InMacroArgs = true;
448 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
449
450 // Finished parsing args.
451 InMacroArgs = false;
452
453 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000454 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000455
456 ++NumFnMacroExpanded;
457 } else {
458 ++NumMacroExpanded;
459 }
460
461 // Notice that this macro has been used.
462 markMacroAsUsed(MI);
463
464 // Remember where the token is expanded.
465 SourceLocation ExpandLoc = Identifier.getLocation();
466 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
467
468 if (Callbacks) {
469 if (InMacroArgs) {
470 // We can have macro expansion inside a conditional directive while
471 // reading the function macro arguments. To ensure, in that case, that
472 // MacroExpands callbacks still happen in source order, queue this
473 // callback to have it happen after the function macro callback.
474 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000475 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000476 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000477 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000478 if (!DelayedMacroExpandsCallbacks.empty()) {
479 for (unsigned i=0, e = DelayedMacroExpandsCallbacks.size(); i!=e; ++i) {
480 MacroExpandsInfo &Info = DelayedMacroExpandsCallbacks[i];
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000481 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000482 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
483 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000484 }
485 DelayedMacroExpandsCallbacks.clear();
486 }
487 }
488 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000489
490 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000491 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000492 Diag(Identifier, diag::warn_pp_ambiguous_macro)
493 << Identifier.getIdentifierInfo();
494 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
495 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000496 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
497 if (OtherMI != MI)
498 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
499 << Identifier.getIdentifierInfo();
500 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000501 }
502
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000503 // If we started lexing a macro, enter the macro expansion body.
504
505 // If this macro expands to no tokens, don't bother to push it onto the
506 // expansion stack, only to take it right back off.
507 if (MI->getNumTokens() == 0) {
508 // No need for arg info.
509 if (Args) Args->destroy(*this);
510
Eli Friedman0834a4b2013-09-19 00:41:32 +0000511 // Propagate whitespace info as if we had pushed, then popped,
512 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000513 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000514 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000515 ++NumFastMacroExpanded;
516 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000517 } else if (MI->getNumTokens() == 1 &&
518 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
519 *this)) {
520 // Otherwise, if this macro expands into a single trivially-expanded
521 // token: expand it now. This handles common cases like
522 // "#define VAL 42".
523
524 // No need for arg info.
525 if (Args) Args->destroy(*this);
526
527 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
528 // identifier to the expanded token.
529 bool isAtStartOfLine = Identifier.isAtStartOfLine();
530 bool hasLeadingSpace = Identifier.hasLeadingSpace();
531
532 // Replace the result token.
533 Identifier = MI->getReplacementToken(0);
534
535 // Restore the StartOfLine/LeadingSpace markers.
536 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
537 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
538
539 // Update the tokens location to include both its expansion and physical
540 // locations.
541 SourceLocation Loc =
542 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
543 ExpansionEnd,Identifier.getLength());
544 Identifier.setLocation(Loc);
545
546 // If this is a disabled macro or #define X X, we must mark the result as
547 // unexpandable.
548 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
549 if (MacroInfo *NewMI = getMacroInfo(NewII))
550 if (!NewMI->isEnabled() || NewMI == MI) {
551 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000552 // Don't warn for "#define X X" like "#define bool bool" from
553 // stdbool.h.
554 if (NewMI != MI || MI->isFunctionLike())
555 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000556 }
557 }
558
559 // Since this is not an identifier token, it can't be macro expanded, so
560 // we're done.
561 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000562 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000563 }
564
565 // Start expanding the macro.
566 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000567 return false;
568}
569
Richard Trieu79b45382013-07-23 18:01:49 +0000570enum Bracket {
571 Brace,
572 Paren
573};
574
575/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
576/// token vector are properly nested.
577static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
578 SmallVector<Bracket, 8> Brackets;
579 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
580 E = Tokens.end();
581 I != E; ++I) {
582 if (I->is(tok::l_paren)) {
583 Brackets.push_back(Paren);
584 } else if (I->is(tok::r_paren)) {
585 if (Brackets.empty() || Brackets.back() == Brace)
586 return false;
587 Brackets.pop_back();
588 } else if (I->is(tok::l_brace)) {
589 Brackets.push_back(Brace);
590 } else if (I->is(tok::r_brace)) {
591 if (Brackets.empty() || Brackets.back() == Paren)
592 return false;
593 Brackets.pop_back();
594 }
595 }
596 if (!Brackets.empty())
597 return false;
598 return true;
599}
600
601/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
602/// vector of tokens in NewTokens. The new number of arguments will be placed
603/// in NumArgs and the ranges which need to surrounded in parentheses will be
604/// in ParenHints.
605/// Returns false if the token stream cannot be changed. If this is because
606/// of an initializer list starting a macro argument, the range of those
607/// initializer lists will be place in InitLists.
608static bool GenerateNewArgTokens(Preprocessor &PP,
609 SmallVectorImpl<Token> &OldTokens,
610 SmallVectorImpl<Token> &NewTokens,
611 unsigned &NumArgs,
612 SmallVectorImpl<SourceRange> &ParenHints,
613 SmallVectorImpl<SourceRange> &InitLists) {
614 if (!CheckMatchedBrackets(OldTokens))
615 return false;
616
617 // Once it is known that the brackets are matched, only a simple count of the
618 // braces is needed.
619 unsigned Braces = 0;
620
621 // First token of a new macro argument.
622 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
623
624 // First closing brace in a new macro argument. Used to generate
625 // SourceRanges for InitLists.
626 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
627 NumArgs = 0;
628 Token TempToken;
629 // Set to true when a macro separator token is found inside a braced list.
630 // If true, the fixed argument spans multiple old arguments and ParenHints
631 // will be updated.
632 bool FoundSeparatorToken = false;
633 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
634 E = OldTokens.end();
635 I != E; ++I) {
636 if (I->is(tok::l_brace)) {
637 ++Braces;
638 } else if (I->is(tok::r_brace)) {
639 --Braces;
640 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
641 ClosingBrace = I;
642 } else if (I->is(tok::eof)) {
643 // EOF token is used to separate macro arguments
644 if (Braces != 0) {
645 // Assume comma separator is actually braced list separator and change
646 // it back to a comma.
647 FoundSeparatorToken = true;
648 I->setKind(tok::comma);
649 I->setLength(1);
650 } else { // Braces == 0
651 // Separator token still separates arguments.
652 ++NumArgs;
653
654 // If the argument starts with a brace, it can't be fixed with
655 // parentheses. A different diagnostic will be given.
656 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
657 InitLists.push_back(
658 SourceRange(ArgStartIterator->getLocation(),
659 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
660 ClosingBrace = E;
661 }
662
663 // Add left paren
664 if (FoundSeparatorToken) {
665 TempToken.startToken();
666 TempToken.setKind(tok::l_paren);
667 TempToken.setLocation(ArgStartIterator->getLocation());
668 TempToken.setLength(0);
669 NewTokens.push_back(TempToken);
670 }
671
672 // Copy over argument tokens
673 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
674
675 // Add right paren and store the paren locations in ParenHints
676 if (FoundSeparatorToken) {
677 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
678 TempToken.startToken();
679 TempToken.setKind(tok::r_paren);
680 TempToken.setLocation(Loc);
681 TempToken.setLength(0);
682 NewTokens.push_back(TempToken);
683 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
684 Loc));
685 }
686
687 // Copy separator token
688 NewTokens.push_back(*I);
689
690 // Reset values
691 ArgStartIterator = I + 1;
692 FoundSeparatorToken = false;
693 }
694 }
695 }
696
697 return !ParenHints.empty() && InitLists.empty();
698}
699
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000700/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
701/// token is the '(' of the macro, this method is invoked to read all of the
702/// actual arguments specified for the macro invocation. This returns null on
703/// error.
704MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
705 MacroInfo *MI,
706 SourceLocation &MacroEnd) {
707 // The number of fixed arguments to parse.
708 unsigned NumFixedArgsLeft = MI->getNumArgs();
709 bool isVariadic = MI->isVariadic();
710
711 // Outer loop, while there are more arguments, keep reading them.
712 Token Tok;
713
714 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
715 // an argument value in a macro could expand to ',' or '(' or ')'.
716 LexUnexpandedToken(Tok);
717 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
718
719 // ArgTokens - Build up a list of tokens that make up each argument. Each
720 // argument is separated by an EOF token. Use a SmallVector so we can avoid
721 // heap allocations in the common case.
722 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000723 bool ContainsCodeCompletionTok = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000724
Richard Trieu79b45382013-07-23 18:01:49 +0000725 SourceLocation TooManyArgsLoc;
726
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000727 unsigned NumActuals = 0;
728 while (Tok.isNot(tok::r_paren)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000729 if (ContainsCodeCompletionTok && (Tok.is(tok::eof) || Tok.is(tok::eod)))
730 break;
731
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000732 assert((Tok.is(tok::l_paren) || Tok.is(tok::comma)) &&
733 "only expect argument separators here");
734
735 unsigned ArgTokenStart = ArgTokens.size();
736 SourceLocation ArgStartLoc = Tok.getLocation();
737
738 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
739 // that we already consumed the first one.
740 unsigned NumParens = 0;
741
742 while (1) {
743 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
744 // an argument value in a macro could expand to ',' or '(' or ')'.
745 LexUnexpandedToken(Tok);
746
747 if (Tok.is(tok::eof) || Tok.is(tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000748 if (!ContainsCodeCompletionTok) {
749 Diag(MacroName, diag::err_unterm_macro_invoc);
750 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
751 << MacroName.getIdentifierInfo();
752 // Do not lose the EOF/EOD. Return it to the client.
753 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000754 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000755 } else {
Argyrios Kyrtzidis9fd15712012-12-22 04:48:10 +0000756 // Do not lose the EOF/EOD.
757 Token *Toks = new Token[1];
758 Toks[0] = Tok;
759 EnterTokenStream(Toks, 1, true, true);
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000760 break;
761 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000762 } else if (Tok.is(tok::r_paren)) {
763 // If we found the ) token, the macro arg list is done.
764 if (NumParens-- == 0) {
765 MacroEnd = Tok.getLocation();
766 break;
767 }
768 } else if (Tok.is(tok::l_paren)) {
769 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000770 } else if (Tok.is(tok::comma) && NumParens == 0 &&
771 !(Tok.getFlags() & Token::IgnoredComma)) {
772 // In Microsoft-compatibility mode, single commas from nested macro
773 // expansions should not be considered as argument separators. We test
774 // for this with the IgnoredComma token flag above.
775
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000776 // Comma ends this argument if there are more fixed arguments expected.
777 // However, if this is a variadic macro, and this is part of the
778 // variadic part, then the comma is just an argument token.
779 if (!isVariadic) break;
780 if (NumFixedArgsLeft > 1)
781 break;
782 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
783 // If this is a comment token in the argument list and we're just in
784 // -C mode (not -CC mode), discard the comment.
785 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000786 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000787 // Reading macro arguments can cause macros that we are currently
788 // expanding from to be popped off the expansion stack. Doing so causes
789 // them to be reenabled for expansion. Here we record whether any
790 // identifiers we lex as macro arguments correspond to disabled macros.
791 // If so, we mark the token as noexpand. This is a subtle aspect of
792 // C99 6.10.3.4p2.
793 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
794 if (!MI->isEnabled())
795 Tok.setFlag(Token::DisableExpand);
796 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000797 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000798 if (CodeComplete)
799 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
800 MI, NumActuals);
801 // Don't mark that we reached the code-completion point because the
802 // parser is going to handle the token and there will be another
803 // code-completion callback.
804 }
805
806 ArgTokens.push_back(Tok);
807 }
808
809 // If this was an empty argument list foo(), don't add this as an empty
810 // argument.
811 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
812 break;
813
814 // If this is not a variadic macro, and too many args were specified, emit
815 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000816 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000817 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000818 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
819 else
820 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000821 }
822
Richard Trieu79b45382013-07-23 18:01:49 +0000823 // Empty arguments are standard in C99 and C++0x, and are supported as an
824 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000825 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000826 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000827 diag::warn_cxx98_compat_empty_fnmacro_arg :
828 diag::ext_empty_fnmacro_arg);
829
830 // Add a marker EOF token to the end of the token list for this argument.
831 Token EOFTok;
832 EOFTok.startToken();
833 EOFTok.setKind(tok::eof);
834 EOFTok.setLocation(Tok.getLocation());
835 EOFTok.setLength(0);
836 ArgTokens.push_back(EOFTok);
837 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000838 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000839 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000840 }
841
842 // Okay, we either found the r_paren. Check to see if we parsed too few
843 // arguments.
844 unsigned MinArgsExpected = MI->getNumArgs();
845
Richard Trieu79b45382013-07-23 18:01:49 +0000846 // If this is not a variadic macro, and too many args were specified, emit
847 // an error.
848 if (!isVariadic && NumActuals > MinArgsExpected &&
849 !ContainsCodeCompletionTok) {
850 // Emit the diagnostic at the macro name in case there is a missing ).
851 // Emitting it at the , could be far away from the macro name.
852 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
853 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
854 << MacroName.getIdentifierInfo();
855
856 // Commas from braced initializer lists will be treated as argument
857 // separators inside macros. Attempt to correct for this with parentheses.
858 // TODO: See if this can be generalized to angle brackets for templates
859 // inside macro arguments.
860
Bob Wilson57217352013-07-27 21:59:57 +0000861 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000862 unsigned FixedNumArgs = 0;
863 SmallVector<SourceRange, 4> ParenHints, InitLists;
864 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
865 ParenHints, InitLists)) {
866 if (!InitLists.empty()) {
867 DiagnosticBuilder DB =
868 Diag(MacroName,
869 diag::note_init_list_at_beginning_of_macro_argument);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000870 for (const SourceRange &Range : InitLists)
871 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000872 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000873 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000874 }
875 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000876 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000877
878 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000879 for (const SourceRange &ParenLocation : ParenHints) {
880 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
881 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000882 }
883 ArgTokens.swap(FixedArgTokens);
884 NumActuals = FixedNumArgs;
885 }
886
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000887 // See MacroArgs instance var for description of this.
888 bool isVarargsElided = false;
889
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000890 if (ContainsCodeCompletionTok) {
891 // Recover from not-fully-formed macro invocation during code-completion.
892 Token EOFTok;
893 EOFTok.startToken();
894 EOFTok.setKind(tok::eof);
895 EOFTok.setLocation(Tok.getLocation());
896 EOFTok.setLength(0);
897 for (; NumActuals < MinArgsExpected; ++NumActuals)
898 ArgTokens.push_back(EOFTok);
899 }
900
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000901 if (NumActuals < MinArgsExpected) {
902 // There are several cases where too few arguments is ok, handle them now.
903 if (NumActuals == 0 && MinArgsExpected == 1) {
904 // #define A(X) or #define A(...) ---> A()
905
906 // If there is exactly one argument, and that argument is missing,
907 // then we have an empty "()" argument empty list. This is fine, even if
908 // the macro expects one argument (the argument is just empty).
909 isVarargsElided = MI->isVariadic();
910 } else if (MI->isVariadic() &&
911 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
912 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
913 // Varargs where the named vararg parameter is missing: OK as extension.
914 // #define A(x, ...)
915 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000916 //
917 // If the macro contains the comma pasting extension, the diagnostic
918 // is suppressed; we know we'll get another diagnostic later.
919 if (!MI->hasCommaPasting()) {
920 Diag(Tok, diag::ext_missing_varargs_arg);
921 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
922 << MacroName.getIdentifierInfo();
923 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000924
925 // Remember this occurred, allowing us to elide the comma when used for
926 // cases like:
927 // #define A(x, foo...) blah(a, ## foo)
928 // #define B(x, ...) blah(a, ## __VA_ARGS__)
929 // #define C(...) blah(a, ## __VA_ARGS__)
930 // A(x) B(x) C()
931 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000932 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000933 // Otherwise, emit the error.
934 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000935 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
936 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000937 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000938 }
939
940 // Add a marker EOF token to the end of the token list for this argument.
941 SourceLocation EndLoc = Tok.getLocation();
942 Tok.startToken();
943 Tok.setKind(tok::eof);
944 Tok.setLocation(EndLoc);
945 Tok.setLength(0);
946 ArgTokens.push_back(Tok);
947
948 // If we expect two arguments, add both as empty.
949 if (NumActuals == 0 && MinArgsExpected == 2)
950 ArgTokens.push_back(Tok);
951
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000952 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
953 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000954 // Emit the diagnostic at the macro name in case there is a missing ).
955 // Emitting it at the , could be far away from the macro name.
956 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000957 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
958 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000959 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000960 }
961
962 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
963}
964
965/// \brief Keeps macro expanded tokens for TokenLexers.
966//
967/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
968/// going to lex in the cache and when it finishes the tokens are removed
969/// from the end of the cache.
970Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
971 ArrayRef<Token> tokens) {
972 assert(tokLexer);
973 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000974 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000975
976 size_t newIndex = MacroExpandedTokens.size();
977 bool cacheNeedsToGrow = tokens.size() >
978 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
979 MacroExpandedTokens.append(tokens.begin(), tokens.end());
980
981 if (cacheNeedsToGrow) {
982 // Go through all the TokenLexers whose 'Tokens' pointer points in the
983 // buffer and update the pointers to the (potential) new buffer array.
984 for (unsigned i = 0, e = MacroExpandingLexersStack.size(); i != e; ++i) {
985 TokenLexer *prevLexer;
986 size_t tokIndex;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000987 std::tie(prevLexer, tokIndex) = MacroExpandingLexersStack[i];
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000988 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
989 }
990 }
991
992 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
993 return MacroExpandedTokens.data() + newIndex;
994}
995
996void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
997 assert(!MacroExpandingLexersStack.empty());
998 size_t tokIndex = MacroExpandingLexersStack.back().second;
999 assert(tokIndex < MacroExpandedTokens.size());
1000 // Pop the cached macro expanded tokens from the end.
1001 MacroExpandedTokens.resize(tokIndex);
1002 MacroExpandingLexersStack.pop_back();
1003}
1004
1005/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1006/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1007/// the identifier tokens inserted.
1008static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1009 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001010 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001011 struct tm *TM = localtime(&TT);
1012
1013 static const char * const Months[] = {
1014 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1015 };
1016
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001017 {
1018 SmallString<32> TmpBuffer;
1019 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1020 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1021 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001022 Token TmpTok;
1023 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001024 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001025 DATELoc = TmpTok.getLocation();
1026 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001027
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001028 {
1029 SmallString<32> TmpBuffer;
1030 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1031 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1032 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001033 Token TmpTok;
1034 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001035 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001036 TIMELoc = TmpTok.getLocation();
1037 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001038}
1039
1040
1041/// HasFeature - Return true if we recognize and implement the feature
1042/// specified by the identifier as a standard language feature.
1043static bool HasFeature(const Preprocessor &PP, const IdentifierInfo *II) {
1044 const LangOptions &LangOpts = PP.getLangOpts();
1045 StringRef Feature = II->getName();
1046
1047 // Normalize the feature name, __foo__ becomes foo.
1048 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1049 Feature = Feature.substr(2, Feature.size() - 4);
1050
1051 return llvm::StringSwitch<bool>(Feature)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001052 .Case("address_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Address))
1053 .Case("attribute_analyzer_noreturn", true)
1054 .Case("attribute_availability", true)
1055 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001056 .Case("attribute_availability_app_extension", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001057 .Case("attribute_cf_returns_not_retained", true)
1058 .Case("attribute_cf_returns_retained", true)
1059 .Case("attribute_deprecated_with_message", true)
1060 .Case("attribute_ext_vector_type", true)
1061 .Case("attribute_ns_returns_not_retained", true)
1062 .Case("attribute_ns_returns_retained", true)
1063 .Case("attribute_ns_consumes_self", true)
1064 .Case("attribute_ns_consumed", true)
1065 .Case("attribute_cf_consumed", true)
1066 .Case("attribute_objc_ivar_unused", true)
1067 .Case("attribute_objc_method_family", true)
1068 .Case("attribute_overloadable", true)
1069 .Case("attribute_unavailable_with_message", true)
1070 .Case("attribute_unused_on_fields", true)
1071 .Case("blocks", LangOpts.Blocks)
1072 .Case("c_thread_safety_attributes", true)
1073 .Case("cxx_exceptions", LangOpts.CXXExceptions)
1074 .Case("cxx_rtti", LangOpts.RTTI)
1075 .Case("enumerator_attributes", true)
1076 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1077 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1078 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
1079 // Objective-C features
1080 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1081 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
1082 .Case("objc_arc_weak", LangOpts.ObjCARCWeak)
1083 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1084 .Case("objc_fixed_enum", LangOpts.ObjC2)
1085 .Case("objc_instancetype", LangOpts.ObjC2)
1086 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1087 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1088 .Case("objc_property_explicit_atomic",
1089 true) // Does clang support explicit "atomic" keyword?
1090 .Case("objc_protocol_qualifier_mangling", true)
1091 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1092 .Case("ownership_holds", true)
1093 .Case("ownership_returns", true)
1094 .Case("ownership_takes", true)
1095 .Case("objc_bool", true)
1096 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1097 .Case("objc_array_literals", LangOpts.ObjC2)
1098 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1099 .Case("objc_boxed_expressions", LangOpts.ObjC2)
1100 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001101 .Case("objc_bridge_id", true)
1102 .Case("objc_bridge_id_on_typedefs", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001103 // C11 features
1104 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001105 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001106 .Case("c_atomic", LangOpts.C11)
1107 .Case("c_generic_selections", LangOpts.C11)
1108 .Case("c_static_assert", LangOpts.C11)
1109 .Case("c_thread_local",
1110 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1111 // C++11 features
1112 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1113 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1114 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001115 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001116 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1117 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1118 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1119 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
1120 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1121 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1122 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1123 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1124 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1125 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1126 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1127 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1128 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1129 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1130 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1131 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1132 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1133 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1134 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1135 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1136 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1137 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1138 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1139 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1140 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1141 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1142 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1143 .Case("cxx_thread_local",
1144 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1145 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1146 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1147 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1148 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1149 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
1150 // C++1y features
1151 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1152 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1153 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1154 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1155 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1156 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1157 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1158 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1159 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
1160 // C++ TSes
1161 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1162 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1163 // FIXME: Should this be __has_feature or __has_extension?
1164 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1165 // Type traits
1166 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1167 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1168 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1169 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1170 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1171 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1172 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1173 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1174 .Case("is_abstract", LangOpts.CPlusPlus)
1175 .Case("is_base_of", LangOpts.CPlusPlus)
1176 .Case("is_class", LangOpts.CPlusPlus)
1177 .Case("is_constructible", LangOpts.CPlusPlus)
1178 .Case("is_convertible_to", LangOpts.CPlusPlus)
1179 .Case("is_empty", LangOpts.CPlusPlus)
1180 .Case("is_enum", LangOpts.CPlusPlus)
1181 .Case("is_final", LangOpts.CPlusPlus)
1182 .Case("is_literal", LangOpts.CPlusPlus)
1183 .Case("is_standard_layout", LangOpts.CPlusPlus)
1184 .Case("is_pod", LangOpts.CPlusPlus)
1185 .Case("is_polymorphic", LangOpts.CPlusPlus)
1186 .Case("is_sealed", LangOpts.MicrosoftExt)
1187 .Case("is_trivial", LangOpts.CPlusPlus)
1188 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1189 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1190 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1191 .Case("is_union", LangOpts.CPlusPlus)
1192 .Case("modules", LangOpts.Modules)
1193 .Case("tls", PP.getTargetInfo().isTLSSupported())
1194 .Case("underlying_type", LangOpts.CPlusPlus)
1195 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001196}
1197
1198/// HasExtension - Return true if we recognize and implement the feature
1199/// specified by the identifier, either as an extension or a standard language
1200/// feature.
1201static bool HasExtension(const Preprocessor &PP, const IdentifierInfo *II) {
1202 if (HasFeature(PP, II))
1203 return true;
1204
1205 // If the use of an extension results in an error diagnostic, extensions are
1206 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001207 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1208 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001209 return false;
1210
1211 const LangOptions &LangOpts = PP.getLangOpts();
1212 StringRef Extension = II->getName();
1213
1214 // Normalize the extension name, __foo__ becomes foo.
1215 if (Extension.startswith("__") && Extension.endswith("__") &&
1216 Extension.size() >= 4)
1217 Extension = Extension.substr(2, Extension.size() - 4);
1218
1219 // Because we inherit the feature list from HasFeature, this string switch
1220 // must be less restrictive than HasFeature's.
1221 return llvm::StringSwitch<bool>(Extension)
1222 // C11 features supported by other languages as extensions.
1223 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001224 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001225 .Case("c_atomic", true)
1226 .Case("c_generic_selections", true)
1227 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001228 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001229 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001230 .Case("cxx_atomic", LangOpts.CPlusPlus)
1231 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1232 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1233 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1234 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1235 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1236 .Case("cxx_override_control", LangOpts.CPlusPlus)
1237 .Case("cxx_range_for", LangOpts.CPlusPlus)
1238 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1239 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Eric Fiselier7aa0d4a2015-05-12 22:37:23 +00001240 .Case("cxx_variadic_templates", LangOpts.CPlusPlus)
Richard Smith0a715422013-05-07 19:32:56 +00001241 // C++1y features supported by other languages as extensions.
1242 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001243 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001244 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001245 .Default(false);
1246}
1247
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001248/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1249/// or '__has_include_next("path")' expression.
1250/// Returns true if successful.
1251static bool EvaluateHasIncludeCommon(Token &Tok,
1252 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001253 const DirectoryLookup *LookupFrom,
1254 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001255 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001256 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001257 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001258
Aaron Ballman6ce00002013-01-16 19:32:21 +00001259 // These expressions are only allowed within a preprocessor directive.
1260 if (!PP.isParsingIfOrElifDirective()) {
1261 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001262 // Return a valid identifier token.
1263 assert(Tok.is(tok::identifier));
1264 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001265 return false;
1266 }
1267
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001268 // Get '('.
1269 PP.LexNonComment(Tok);
1270
1271 // Ensure we have a '('.
1272 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001273 // No '(', use end of last token.
1274 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001275 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001276 // If the next token looks like a filename or the start of one,
1277 // assume it is and process it as such.
1278 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1279 !Tok.is(tok::less))
1280 return false;
1281 } else {
1282 // Save '(' location for possible missing ')' message.
1283 LParenLoc = Tok.getLocation();
1284
Eli Friedmanec94b612013-01-09 02:20:00 +00001285 if (PP.getCurrentLexer()) {
1286 // Get the file name.
1287 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1288 } else {
1289 // We're in a macro, so we can't use LexIncludeFilename; just
1290 // grab the next token.
1291 PP.Lex(Tok);
1292 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001293 }
1294
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001295 // Reserve a buffer to get the spelling.
1296 SmallString<128> FilenameBuffer;
1297 StringRef Filename;
1298 SourceLocation EndLoc;
1299
1300 switch (Tok.getKind()) {
1301 case tok::eod:
1302 // If the token kind is EOD, the error has already been diagnosed.
1303 return false;
1304
1305 case tok::angle_string_literal:
1306 case tok::string_literal: {
1307 bool Invalid = false;
1308 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1309 if (Invalid)
1310 return false;
1311 break;
1312 }
1313
1314 case tok::less:
1315 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1316 // case, glue the tokens together into FilenameBuffer and interpret those.
1317 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001318 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1319 // Let the caller know a <eod> was found by changing the Token kind.
1320 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001321 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001322 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001323 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001324 break;
1325 default:
1326 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1327 return false;
1328 }
1329
Richard Trieuda031982012-10-22 20:28:48 +00001330 SourceLocation FilenameLoc = Tok.getLocation();
1331
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001332 // Get ')'.
1333 PP.LexNonComment(Tok);
1334
1335 // Ensure we have a trailing ).
1336 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001337 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1338 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001339 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001340 return false;
1341 }
1342
1343 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1344 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1345 // error.
1346 if (Filename.empty())
1347 return false;
1348
1349 // Search include directories.
1350 const DirectoryLookup *CurDir;
1351 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001352 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1353 CurDir, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001354
1355 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001356 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001357}
1358
1359/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1360/// Returns true if successful.
1361static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1362 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001363 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001364}
1365
1366/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1367/// Returns true if successful.
1368static bool EvaluateHasIncludeNext(Token &Tok,
1369 IdentifierInfo *II, Preprocessor &PP) {
1370 // __has_include_next is like __has_include, except that we start
1371 // searching after the current found directory. If we can't do this,
1372 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001373 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001374 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001375 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001376 const FileEntry *LookupFromFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001377 if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001378 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001379 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smith25d50752014-10-20 00:15:49 +00001380 } else if (PP.getCurrentSubmodule()) {
1381 // Start looking up in the directory *after* the one in which the current
1382 // file would be found, if any.
1383 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1384 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1385 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001386 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001387 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1388 } else {
1389 // Start looking up in the next directory.
1390 ++Lookup;
1391 }
1392
Richard Smith25d50752014-10-20 00:15:49 +00001393 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001394}
1395
Douglas Gregorc83de302012-09-25 15:44:52 +00001396/// \brief Process __building_module(identifier) expression.
1397/// \returns true if we are building the named module, false otherwise.
1398static bool EvaluateBuildingModule(Token &Tok,
1399 IdentifierInfo *II, Preprocessor &PP) {
1400 // Get '('.
1401 PP.LexNonComment(Tok);
1402
1403 // Ensure we have a '('.
1404 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001405 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1406 << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001407 return false;
1408 }
1409
1410 // Save '(' location for possible missing ')' message.
1411 SourceLocation LParenLoc = Tok.getLocation();
1412
1413 // Get the module name.
1414 PP.LexNonComment(Tok);
1415
1416 // Ensure that we have an identifier.
1417 if (Tok.isNot(tok::identifier)) {
1418 PP.Diag(Tok.getLocation(), diag::err_expected_id_building_module);
1419 return false;
1420 }
1421
1422 bool Result
1423 = Tok.getIdentifierInfo()->getName() == PP.getLangOpts().CurrentModule;
1424
1425 // Get ')'.
1426 PP.LexNonComment(Tok);
1427
1428 // Ensure we have a trailing ).
1429 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001430 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1431 << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001432 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Douglas Gregorc83de302012-09-25 15:44:52 +00001433 return false;
1434 }
1435
1436 return Result;
1437}
1438
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001439/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1440/// as a builtin macro, handle it and return the next token as 'Tok'.
1441void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1442 // Figure out which token this is.
1443 IdentifierInfo *II = Tok.getIdentifierInfo();
1444 assert(II && "Can't be a macro without id info!");
1445
1446 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1447 // invoke the pragma handler, then lex the token after it.
1448 if (II == Ident_Pragma)
1449 return Handle_Pragma(Tok);
1450 else if (II == Ident__pragma) // in non-MS mode this is null
1451 return HandleMicrosoft__pragma(Tok);
1452
1453 ++NumBuiltinMacroExpanded;
1454
1455 SmallString<128> TmpBuffer;
1456 llvm::raw_svector_ostream OS(TmpBuffer);
1457
1458 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001459 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001460 Tok.clearFlag(Token::NeedsCleaning);
1461
1462 if (II == Ident__LINE__) {
1463 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1464 // source file) of the current source line (an integer constant)". This can
1465 // be affected by #line.
1466 SourceLocation Loc = Tok.getLocation();
1467
1468 // Advance to the location of the first _, this might not be the first byte
1469 // of the token if it starts with an escaped newline.
1470 Loc = AdvanceToTokenCharacter(Loc, 0);
1471
1472 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1473 // a macro expansion. This doesn't matter for object-like macros, but
1474 // can matter for a function-like macro that expands to contain __LINE__.
1475 // Skip down through expansion points until we find a file loc for the
1476 // end of the expansion history.
1477 Loc = SourceMgr.getExpansionRange(Loc).second;
1478 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1479
1480 // __LINE__ expands to a simple numeric value.
1481 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1482 Tok.setKind(tok::numeric_constant);
1483 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1484 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1485 // character string literal)". This can be affected by #line.
1486 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1487
1488 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1489 // #include stack instead of the current file.
1490 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1491 SourceLocation NextLoc = PLoc.getIncludeLoc();
1492 while (NextLoc.isValid()) {
1493 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1494 if (PLoc.isInvalid())
1495 break;
1496
1497 NextLoc = PLoc.getIncludeLoc();
1498 }
1499 }
1500
1501 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1502 SmallString<128> FN;
1503 if (PLoc.isValid()) {
1504 FN += PLoc.getFilename();
1505 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001506 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001507 }
1508 Tok.setKind(tok::string_literal);
1509 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001510 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001511 if (!DATELoc.isValid())
1512 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1513 Tok.setKind(tok::string_literal);
1514 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1515 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1516 Tok.getLocation(),
1517 Tok.getLength()));
1518 return;
1519 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001520 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001521 if (!TIMELoc.isValid())
1522 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1523 Tok.setKind(tok::string_literal);
1524 Tok.setLength(strlen("\"hh:mm:ss\""));
1525 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1526 Tok.getLocation(),
1527 Tok.getLength()));
1528 return;
1529 } else if (II == Ident__INCLUDE_LEVEL__) {
1530 // Compute the presumed include depth of this token. This can be affected
1531 // by GNU line markers.
1532 unsigned Depth = 0;
1533
1534 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1535 if (PLoc.isValid()) {
1536 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1537 for (; PLoc.isValid(); ++Depth)
1538 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1539 }
1540
1541 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1542 OS << Depth;
1543 Tok.setKind(tok::numeric_constant);
1544 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001545 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001546 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1547 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1548
1549 // Get the file that we are lexing out of. If we're currently lexing from
1550 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001551 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001552 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1553
1554 if (TheLexer)
1555 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1556
1557 const char *Result;
1558 if (CurFile) {
1559 time_t TT = CurFile->getModificationTime();
1560 struct tm *TM = localtime(&TT);
1561 Result = asctime(TM);
1562 } else {
1563 Result = "??? ??? ?? ??:??:?? ????\n";
1564 }
1565 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001566 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001567 Tok.setKind(tok::string_literal);
1568 } else if (II == Ident__COUNTER__) {
1569 // __COUNTER__ expands to a simple numeric value.
1570 OS << CounterValue++;
1571 Tok.setKind(tok::numeric_constant);
1572 } else if (II == Ident__has_feature ||
1573 II == Ident__has_extension ||
1574 II == Ident__has_builtin ||
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001575 II == Ident__is_identifier ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001576 II == Ident__has_attribute ||
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001577 II == Ident__has_declspec ||
Aaron Ballmana0344c52014-11-14 13:44:02 +00001578 II == Ident__has_cpp_attribute) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001579 // The argument to these builtins should be a parenthesized identifier.
1580 SourceLocation StartLoc = Tok.getLocation();
1581
1582 bool IsValid = false;
Craig Topperd2d442c2014-05-17 23:10:59 +00001583 IdentifierInfo *FeatureII = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001584 IdentifierInfo *ScopeII = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001585
1586 // Read the '('.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001587 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001588 if (Tok.is(tok::l_paren)) {
1589 // Read the identifier
Andy Gibbsd41d0942012-11-17 19:18:27 +00001590 LexUnexpandedToken(Tok);
Richard Smithbaf29122013-07-09 00:57:56 +00001591 if ((FeatureII = Tok.getIdentifierInfo())) {
Aaron Ballmana0344c52014-11-14 13:44:02 +00001592 // If we're checking __has_cpp_attribute, it is possible to receive a
1593 // scope token. Read the "::", if it's available.
Andy Gibbsd41d0942012-11-17 19:18:27 +00001594 LexUnexpandedToken(Tok);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001595 bool IsScopeValid = true;
1596 if (II == Ident__has_cpp_attribute && Tok.is(tok::coloncolon)) {
1597 LexUnexpandedToken(Tok);
1598 // The first thing we read was not the feature, it was the scope.
1599 ScopeII = FeatureII;
Aaron Ballman918474c2014-11-14 14:40:49 +00001600 if ((FeatureII = Tok.getIdentifierInfo()))
Aaron Ballmana0344c52014-11-14 13:44:02 +00001601 LexUnexpandedToken(Tok);
1602 else
1603 IsScopeValid = false;
1604 }
1605 // Read the closing paren.
1606 if (IsScopeValid && Tok.is(tok::r_paren))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001607 IsValid = true;
1608 }
David Majnemerd6163622014-12-15 09:03:58 +00001609 // Eat tokens until ')'.
1610 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1611 Tok.isNot(tok::eof))
1612 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001613 }
1614
Aaron Ballmana0344c52014-11-14 13:44:02 +00001615 int Value = 0;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001616 if (!IsValid)
1617 Diag(StartLoc, diag::err_feature_check_malformed);
Yunzhong Gaoef309f42014-04-11 20:55:19 +00001618 else if (II == Ident__is_identifier)
1619 Value = FeatureII->getTokenID() == tok::identifier;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001620 else if (II == Ident__has_builtin) {
1621 // Check for a builtin is trivial.
1622 Value = FeatureII->getBuiltinID() != 0;
1623 } else if (II == Ident__has_attribute)
Aaron Ballmana6f759e2014-12-05 15:24:55 +00001624 Value = hasAttribute(AttrSyntax::GNU, nullptr, FeatureII,
Aaron Ballman2fbf9942014-03-31 13:14:44 +00001625 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballmana0344c52014-11-14 13:44:02 +00001626 else if (II == Ident__has_cpp_attribute)
1627 Value = hasAttribute(AttrSyntax::CXX, ScopeII, FeatureII,
1628 getTargetInfo().getTriple(), getLangOpts());
Aaron Ballman3c0f9b42014-12-05 15:05:29 +00001629 else if (II == Ident__has_declspec)
1630 Value = hasAttribute(AttrSyntax::Declspec, nullptr, FeatureII,
1631 getTargetInfo().getTriple(), getLangOpts());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001632 else if (II == Ident__has_extension)
1633 Value = HasExtension(*this, FeatureII);
1634 else {
1635 assert(II == Ident__has_feature && "Must be feature check");
1636 Value = HasFeature(*this, FeatureII);
1637 }
1638
David Majnemerd6163622014-12-15 09:03:58 +00001639 if (!IsValid)
1640 return;
Aaron Ballmana0344c52014-11-14 13:44:02 +00001641 OS << Value;
David Majnemerd6163622014-12-15 09:03:58 +00001642 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001643 } else if (II == Ident__has_include ||
1644 II == Ident__has_include_next) {
1645 // The argument to these two builtins should be a parenthesized
1646 // file name string literal using angle brackets (<>) or
1647 // double-quotes ("").
1648 bool Value;
1649 if (II == Ident__has_include)
1650 Value = EvaluateHasInclude(Tok, II, *this);
1651 else
1652 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001653
1654 if (Tok.isNot(tok::r_paren))
1655 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001656 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001657 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001658 } else if (II == Ident__has_warning) {
1659 // The argument should be a parenthesized string literal.
1660 // The argument to these builtins should be a parenthesized identifier.
1661 SourceLocation StartLoc = Tok.getLocation();
1662 bool IsValid = false;
1663 bool Value = false;
1664 // Read the '('.
Andy Gibbs58905d22012-11-17 19:15:38 +00001665 LexUnexpandedToken(Tok);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001666 do {
Andy Gibbs58905d22012-11-17 19:15:38 +00001667 if (Tok.isNot(tok::l_paren)) {
1668 Diag(StartLoc, diag::err_warning_check_malformed);
1669 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001670 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001671
1672 LexUnexpandedToken(Tok);
1673 std::string WarningName;
1674 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001675 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1676 /*MacroExpansion=*/false)) {
Andy Gibbs58905d22012-11-17 19:15:38 +00001677 // Eat tokens until ')'.
Andy Gibbsb5b30c42012-11-17 22:17:28 +00001678 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eod) &&
1679 Tok.isNot(tok::eof))
Andy Gibbs58905d22012-11-17 19:15:38 +00001680 LexUnexpandedToken(Tok);
1681 break;
1682 }
1683
1684 // Is the end a ')'?
1685 if (!(IsValid = Tok.is(tok::r_paren))) {
1686 Diag(StartLoc, diag::err_warning_check_malformed);
1687 break;
1688 }
1689
Richard Smith3be1cb22014-08-07 00:24:21 +00001690 // FIXME: Should we accept "-R..." flags here, or should that be handled
1691 // by a separate __has_remark?
Andy Gibbs58905d22012-11-17 19:15:38 +00001692 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1693 WarningName[1] != 'W') {
1694 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1695 break;
1696 }
1697
1698 // Finally, check if the warning flags maps to a diagnostic group.
1699 // We construct a SmallVector here to talk to getDiagnosticIDs().
1700 // Although we don't use the result, this isn't a hot path, and not
1701 // worth special casing.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001702 SmallVector<diag::kind, 10> Diags;
Andy Gibbs58905d22012-11-17 19:15:38 +00001703 Value = !getDiagnostics().getDiagnosticIDs()->
Richard Smith3be1cb22014-08-07 00:24:21 +00001704 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1705 WarningName.substr(2), Diags);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001706 } while (false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001707
David Majnemerd6163622014-12-15 09:03:58 +00001708 if (!IsValid)
1709 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001710 OS << (int)Value;
David Majnemerd6163622014-12-15 09:03:58 +00001711 Tok.setKind(tok::numeric_constant);
Douglas Gregorc83de302012-09-25 15:44:52 +00001712 } else if (II == Ident__building_module) {
1713 // The argument to this builtin should be an identifier. The
1714 // builtin evaluates to 1 when that identifier names the module we are
1715 // currently building.
1716 OS << (int)EvaluateBuildingModule(Tok, II, *this);
1717 Tok.setKind(tok::numeric_constant);
1718 } else if (II == Ident__MODULE__) {
1719 // The current module as an identifier.
1720 OS << getLangOpts().CurrentModule;
1721 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1722 Tok.setIdentifierInfo(ModuleII);
1723 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001724 } else if (II == Ident__identifier) {
1725 SourceLocation Loc = Tok.getLocation();
1726
1727 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1728 // if the parens are missing.
1729 LexNonComment(Tok);
1730 if (Tok.isNot(tok::l_paren)) {
1731 // No '(', use end of last token.
1732 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1733 << II << tok::l_paren;
1734 // If the next token isn't valid as our argument, we can't recover.
1735 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1736 Tok.setKind(tok::identifier);
1737 return;
1738 }
1739
1740 SourceLocation LParenLoc = Tok.getLocation();
1741 LexNonComment(Tok);
1742
1743 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1744 Tok.setKind(tok::identifier);
1745 else {
1746 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1747 << Tok.getKind();
1748 // Don't walk past anything that's not a real token.
1749 if (Tok.is(tok::eof) || Tok.is(tok::eod) || Tok.isAnnotation())
1750 return;
1751 }
1752
1753 // Discard the ')', preserving 'Tok' as our result.
1754 Token RParen;
1755 LexNonComment(RParen);
1756 if (RParen.isNot(tok::r_paren)) {
1757 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1758 << Tok.getKind() << tok::r_paren;
1759 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1760 }
1761 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001762 } else {
1763 llvm_unreachable("Unknown identifier!");
1764 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001765 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001766}
1767
1768void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1769 // If the 'used' status changed, and the macro requires 'unused' warning,
1770 // remove its SourceLocation from the warn-for-unused-macro locations.
1771 if (MI->isWarnIfUnused() && !MI->isUsed())
1772 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1773 MI->setIsUsed(true);
1774}