blob: a6bfc32e2213998bf7fd0f1db929b2cf13a779c0 [file] [log] [blame]
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001//===--- MacroExpansion.cpp - Top level Macro Expansion -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
James Dennett32740042013-12-02 17:39:27 +000010// This file implements the top level handling of macro expansion for the
Joao Matosc0d4c1b2012-08-31 21:34:27 +000011// preprocessor.
12//
13//===----------------------------------------------------------------------===//
14
Aaron Ballman2fbf9942014-03-31 13:14:44 +000015#include "clang/Basic/Attributes.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000016#include "clang/Basic/FileManager.h"
17#include "clang/Basic/IdentifierTable.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/ObjCRuntime.h"
21#include "clang/Basic/SourceLocation.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000022#include "clang/Basic/TargetInfo.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000023#include "clang/Lex/CodeCompletionHandler.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000024#include "clang/Lex/DirectoryLookup.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000025#include "clang/Lex/ExternalPreprocessorSource.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "clang/Lex/LexDiagnostic.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000027#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000028#include "clang/Lex/MacroInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000029#include "clang/Lex/Preprocessor.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000030#include "clang/Lex/PreprocessorLexer.h"
31#include "clang/Lex/PTHLexer.h"
32#include "clang/Lex/Token.h"
33#include "llvm/ADT/ArrayRef.h"
34#include "llvm/ADT/DenseMap.h"
35#include "llvm/ADT/DenseSet.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
Andy Gibbs58905d22012-11-17 19:15:38 +000039#include "llvm/ADT/SmallString.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000040#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringRef.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000043#include "llvm/ADT/StringSwitch.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000044#include "llvm/Config/llvm-config.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000045#include "llvm/Support/Casting.h"
Joao Matosc0d4c1b2012-08-31 21:34:27 +000046#include "llvm/Support/ErrorHandling.h"
Dmitri Gribenkoae07f722012-09-24 20:56:28 +000047#include "llvm/Support/Format.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000048#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include <algorithm>
50#include <cassert>
51#include <cstddef>
52#include <cstring>
Joao Matosc0d4c1b2012-08-31 21:34:27 +000053#include <ctime>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include <string>
55#include <tuple>
56#include <utility>
57
Joao Matosc0d4c1b2012-08-31 21:34:27 +000058using namespace clang;
59
Argyrios Kyrtzidis09c9e812013-02-20 00:54:57 +000060MacroDirective *
Richard Smith20e883e2015-04-29 23:20:19 +000061Preprocessor::getLocalMacroDirectiveHistory(const IdentifierInfo *II) const {
62 if (!II->hadMacroDefinition())
63 return nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +000064 auto Pos = CurSubmoduleState->Macros.find(II);
65 return Pos == CurSubmoduleState->Macros.end() ? nullptr
66 : Pos->second.getLatest();
Joao Matosc0d4c1b2012-08-31 21:34:27 +000067}
68
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000069void Preprocessor::appendMacroDirective(IdentifierInfo *II, MacroDirective *MD){
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000070 assert(MD && "MacroDirective should be non-zero!");
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +000071 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
Douglas Gregor5a4649b2012-10-11 00:46:49 +000072
Richard Smith04765ae2015-05-21 01:20:10 +000073 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Richard Smithb8b2ed62015-04-23 18:18:26 +000074 auto *OldMD = StoredMD.getLatest();
75 MD->setPrevious(OldMD);
76 StoredMD.setLatest(MD);
Richard Smith753e0072015-04-27 23:21:38 +000077 StoredMD.overrideActiveModuleMacros(*this, II);
Richard Smithb8b2ed62015-04-23 18:18:26 +000078
Richard Smith802182f2016-02-23 23:20:51 +000079 if (needModuleMacros()) {
80 // Track that we created a new macro directive, so we know we should
81 // consider building a ModuleMacro for it when we get to the end of
82 // the module.
83 PendingModuleMacroNames.push_back(II);
84 }
85
Richard Smithb8b2ed62015-04-23 18:18:26 +000086 // Set up the identifier as having associated macro history.
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000087 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +000088 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Ben Langmuirc28ce3a2014-09-30 20:00:18 +000089 II->setHasMacroDefinition(false);
Richard Smith3981b172015-04-30 02:16:23 +000090 if (II->isFromAST())
Joao Matosc0d4c1b2012-08-31 21:34:27 +000091 II->setChangedSinceDeserialization();
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000092}
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +000093
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000094void Preprocessor::setLoadedMacroDirective(IdentifierInfo *II,
Nico Weberfd870702016-12-09 17:32:52 +000095 MacroDirective *ED,
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +000096 MacroDirective *MD) {
Nico Weberfd870702016-12-09 17:32:52 +000097 // Normally, when a macro is defined, it goes through appendMacroDirective()
98 // above, which chains a macro to previous defines, undefs, etc.
99 // However, in a pch, the whole macro history up to the end of the pch is
100 // stored, so ASTReader goes through this function instead.
101 // However, built-in macros are already registered in the Preprocessor
102 // ctor, and ASTWriter stops writing the macro chain at built-in macros,
103 // so in that case the chain from the pch needs to be spliced to the existing
104 // built-in.
105
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000106 assert(II && MD);
Richard Smith04765ae2015-05-21 01:20:10 +0000107 MacroState &StoredMD = CurSubmoduleState->Macros[II];
Nico Weberfd870702016-12-09 17:32:52 +0000108
109 if (auto *OldMD = StoredMD.getLatest()) {
110 // shouldIgnoreMacro() in ASTWriter also stops at macros from the
111 // predefines buffer in module builds. However, in module builds, modules
112 // are loaded completely before predefines are processed, so StoredMD
113 // will be nullptr for them when they're loaded. StoredMD should only be
114 // non-nullptr for builtins read from a pch file.
115 assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
116 "only built-ins should have an entry here");
117 assert(!OldMD->getPrevious() && "builtin should only have a single entry");
118 ED->setPrevious(OldMD);
119 StoredMD.setLatest(MD);
120 } else {
121 StoredMD = MD;
122 }
123
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000124 // Setup the identifier as having associated macro history.
125 II->setHasMacroDefinition(true);
Richard Smith20e883e2015-04-29 23:20:19 +0000126 if (!MD->isDefined() && LeafModuleMacros.find(II) == LeafModuleMacros.end())
Argyrios Kyrtzidiseb663da2013-03-22 21:12:57 +0000127 II->setHasMacroDefinition(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000128}
129
Richard Smithb8b2ed62015-04-23 18:18:26 +0000130ModuleMacro *Preprocessor::addModuleMacro(Module *Mod, IdentifierInfo *II,
Richard Smithe56c8bc2015-04-22 00:26:11 +0000131 MacroInfo *Macro,
132 ArrayRef<ModuleMacro *> Overrides,
133 bool &New) {
134 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000135 ModuleMacro::Profile(ID, Mod, II);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000136
137 void *InsertPos;
138 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
139 New = false;
140 return MM;
141 }
142
Richard Smithb8b2ed62015-04-23 18:18:26 +0000143 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000144 ModuleMacros.InsertNode(MM, InsertPos);
145
146 // Each overridden macro is now overridden by one more macro.
147 bool HidAny = false;
148 for (auto *O : Overrides) {
149 HidAny |= (O->NumOverriddenBy == 0);
150 ++O->NumOverriddenBy;
151 }
152
153 // If we were the first overrider for any macro, it's no longer a leaf.
154 auto &LeafMacros = LeafModuleMacros[II];
155 if (HidAny) {
156 LeafMacros.erase(std::remove_if(LeafMacros.begin(), LeafMacros.end(),
157 [](ModuleMacro *MM) {
158 return MM->NumOverriddenBy != 0;
159 }),
160 LeafMacros.end());
161 }
162
163 // The new macro is always a leaf macro.
164 LeafMacros.push_back(MM);
Richard Smith20e883e2015-04-29 23:20:19 +0000165 // The identifier now has defined macros (that may or may not be visible).
166 II->setHasMacroDefinition(true);
Richard Smithe56c8bc2015-04-22 00:26:11 +0000167
168 New = true;
169 return MM;
170}
171
Richard Smithb8b2ed62015-04-23 18:18:26 +0000172ModuleMacro *Preprocessor::getModuleMacro(Module *Mod, IdentifierInfo *II) {
Richard Smith5dbef922015-04-22 02:09:43 +0000173 llvm::FoldingSetNodeID ID;
Richard Smithb8b2ed62015-04-23 18:18:26 +0000174 ModuleMacro::Profile(ID, Mod, II);
Richard Smith5dbef922015-04-22 02:09:43 +0000175
176 void *InsertPos;
177 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
178}
179
Richard Smith20e883e2015-04-29 23:20:19 +0000180void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
Richard Smith753e0072015-04-27 23:21:38 +0000181 ModuleMacroInfo &Info) {
Richard Smith04765ae2015-05-21 01:20:10 +0000182 assert(Info.ActiveModuleMacrosGeneration !=
183 CurSubmoduleState->VisibleModules.getGeneration() &&
Richard Smith753e0072015-04-27 23:21:38 +0000184 "don't need to update this macro name info");
Richard Smith04765ae2015-05-21 01:20:10 +0000185 Info.ActiveModuleMacrosGeneration =
186 CurSubmoduleState->VisibleModules.getGeneration();
Richard Smith753e0072015-04-27 23:21:38 +0000187
188 auto Leaf = LeafModuleMacros.find(II);
189 if (Leaf == LeafModuleMacros.end()) {
190 // No imported macros at all: nothing to do.
191 return;
192 }
193
194 Info.ActiveModuleMacros.clear();
195
196 // Every macro that's locally overridden is overridden by a visible macro.
197 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
198 for (auto *O : Info.OverriddenMacros)
199 NumHiddenOverrides[O] = -1;
200
201 // Collect all macros that are not overridden by a visible macro.
Richard Smith938d7012015-09-16 00:55:50 +0000202 llvm::SmallVector<ModuleMacro *, 16> Worklist;
203 for (auto *LeafMM : Leaf->second) {
204 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
205 if (NumHiddenOverrides.lookup(LeafMM) == 0)
206 Worklist.push_back(LeafMM);
207 }
Richard Smith753e0072015-04-27 23:21:38 +0000208 while (!Worklist.empty()) {
209 auto *MM = Worklist.pop_back_val();
Richard Smith04765ae2015-05-21 01:20:10 +0000210 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
Richard Smith753e0072015-04-27 23:21:38 +0000211 // We only care about collecting definitions; undefinitions only act
212 // to override other definitions.
213 if (MM->getMacroInfo())
214 Info.ActiveModuleMacros.push_back(MM);
215 } else {
216 for (auto *O : MM->overrides())
217 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
218 Worklist.push_back(O);
219 }
220 }
Richard Smith20e883e2015-04-29 23:20:19 +0000221 // Our reverse postorder walk found the macros in reverse order.
222 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
Richard Smith753e0072015-04-27 23:21:38 +0000223
224 // Determine whether the macro name is ambiguous.
Richard Smith753e0072015-04-27 23:21:38 +0000225 MacroInfo *MI = nullptr;
Richard Smith20e883e2015-04-29 23:20:19 +0000226 bool IsSystemMacro = true;
227 bool IsAmbiguous = false;
228 if (auto *MD = Info.MD) {
229 while (MD && isa<VisibilityMacroDirective>(MD))
230 MD = MD->getPrevious();
231 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
232 MI = DMD->getInfo();
233 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
234 }
Richard Smith753e0072015-04-27 23:21:38 +0000235 }
236 for (auto *Active : Info.ActiveModuleMacros) {
237 auto *NewMI = Active->getMacroInfo();
238
239 // Before marking the macro as ambiguous, check if this is a case where
240 // both macros are in system headers. If so, we trust that the system
241 // did not get it wrong. This also handles cases where Clang's own
242 // headers have a different spelling of certain system macros:
243 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
244 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
245 //
246 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
247 // overrides the system limits.h's macros, so there's no conflict here.
Richard Smith20e883e2015-04-29 23:20:19 +0000248 if (MI && NewMI != MI &&
249 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
250 IsAmbiguous = true;
251 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
252 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
253 MI = NewMI;
Richard Smith753e0072015-04-27 23:21:38 +0000254 }
Richard Smith20e883e2015-04-29 23:20:19 +0000255 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
Richard Smith753e0072015-04-27 23:21:38 +0000256}
257
Richard Smith3ffa61d2015-04-30 23:10:40 +0000258void Preprocessor::dumpMacroInfo(const IdentifierInfo *II) {
259 ArrayRef<ModuleMacro*> Leaf;
260 auto LeafIt = LeafModuleMacros.find(II);
261 if (LeafIt != LeafModuleMacros.end())
262 Leaf = LeafIt->second;
263 const MacroState *State = nullptr;
Richard Smith04765ae2015-05-21 01:20:10 +0000264 auto Pos = CurSubmoduleState->Macros.find(II);
265 if (Pos != CurSubmoduleState->Macros.end())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000266 State = &Pos->second;
267
268 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
269 if (State && State->isAmbiguous(*this, II))
270 llvm::errs() << " ambiguous";
Richard Smithd0014bf2015-04-30 23:42:10 +0000271 if (State && !State->getOverriddenMacros().empty()) {
Richard Smith3ffa61d2015-04-30 23:10:40 +0000272 llvm::errs() << " overrides";
273 for (auto *O : State->getOverriddenMacros())
274 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
275 }
276 llvm::errs() << "\n";
277
278 // Dump local macro directives.
279 for (auto *MD = State ? State->getLatest() : nullptr; MD;
280 MD = MD->getPrevious()) {
281 llvm::errs() << " ";
282 MD->dump();
283 }
284
285 // Dump module macros.
286 llvm::DenseSet<ModuleMacro*> Active;
287 for (auto *MM : State ? State->getActiveModuleMacros(*this, II) : None)
288 Active.insert(MM);
289 llvm::DenseSet<ModuleMacro*> Visited;
290 llvm::SmallVector<ModuleMacro *, 16> Worklist(Leaf.begin(), Leaf.end());
291 while (!Worklist.empty()) {
292 auto *MM = Worklist.pop_back_val();
293 llvm::errs() << " ModuleMacro " << MM << " "
294 << MM->getOwningModule()->getFullModuleName();
295 if (!MM->getMacroInfo())
296 llvm::errs() << " undef";
297
298 if (Active.count(MM))
299 llvm::errs() << " active";
Richard Smith04765ae2015-05-21 01:20:10 +0000300 else if (!CurSubmoduleState->VisibleModules.isVisible(
301 MM->getOwningModule()))
Richard Smith3ffa61d2015-04-30 23:10:40 +0000302 llvm::errs() << " hidden";
Richard Smith42413142015-05-15 20:05:43 +0000303 else if (MM->getMacroInfo())
Richard Smith3ffa61d2015-04-30 23:10:40 +0000304 llvm::errs() << " overridden";
305
306 if (!MM->overrides().empty()) {
307 llvm::errs() << " overrides";
308 for (auto *O : MM->overrides()) {
309 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
310 if (Visited.insert(O).second)
311 Worklist.push_back(O);
312 }
313 }
314 llvm::errs() << "\n";
315 if (auto *MI = MM->getMacroInfo()) {
316 llvm::errs() << " ";
317 MI->dump();
318 llvm::errs() << "\n";
319 }
320 }
321}
322
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000323/// RegisterBuiltinMacro - Register the specified identifier in the identifier
324/// table and mark it as a builtin macro to be expanded.
325static IdentifierInfo *RegisterBuiltinMacro(Preprocessor &PP, const char *Name){
326 // Get the identifier.
327 IdentifierInfo *Id = PP.getIdentifierInfo(Name);
328
329 // Mark it as being a macro that is builtin.
330 MacroInfo *MI = PP.AllocateMacroInfo(SourceLocation());
331 MI->setIsBuiltinMacro();
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000332 PP.appendDefMacroDirective(Id, MI);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000333 return Id;
334}
335
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000336/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
337/// identifier table.
338void Preprocessor::RegisterBuiltinMacros() {
339 Ident__LINE__ = RegisterBuiltinMacro(*this, "__LINE__");
340 Ident__FILE__ = RegisterBuiltinMacro(*this, "__FILE__");
341 Ident__DATE__ = RegisterBuiltinMacro(*this, "__DATE__");
342 Ident__TIME__ = RegisterBuiltinMacro(*this, "__TIME__");
343 Ident__COUNTER__ = RegisterBuiltinMacro(*this, "__COUNTER__");
344 Ident_Pragma = RegisterBuiltinMacro(*this, "_Pragma");
345
Aaron Ballmana0344c52014-11-14 13:44:02 +0000346 // C++ Standing Document Extensions.
Aaron Ballman416b1272015-05-11 14:09:50 +0000347 if (LangOpts.CPlusPlus)
348 Ident__has_cpp_attribute =
349 RegisterBuiltinMacro(*this, "__has_cpp_attribute");
350 else
351 Ident__has_cpp_attribute = nullptr;
Aaron Ballmana0344c52014-11-14 13:44:02 +0000352
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000353 // GCC Extensions.
354 Ident__BASE_FILE__ = RegisterBuiltinMacro(*this, "__BASE_FILE__");
355 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro(*this, "__INCLUDE_LEVEL__");
356 Ident__TIMESTAMP__ = RegisterBuiltinMacro(*this, "__TIMESTAMP__");
357
Richard Smithae385082014-03-15 00:06:08 +0000358 // Microsoft Extensions.
359 if (LangOpts.MicrosoftExt) {
360 Ident__identifier = RegisterBuiltinMacro(*this, "__identifier");
361 Ident__pragma = RegisterBuiltinMacro(*this, "__pragma");
362 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000363 Ident__identifier = nullptr;
364 Ident__pragma = nullptr;
Richard Smithae385082014-03-15 00:06:08 +0000365 }
366
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000367 // Clang Extensions.
368 Ident__has_feature = RegisterBuiltinMacro(*this, "__has_feature");
369 Ident__has_extension = RegisterBuiltinMacro(*this, "__has_extension");
370 Ident__has_builtin = RegisterBuiltinMacro(*this, "__has_builtin");
371 Ident__has_attribute = RegisterBuiltinMacro(*this, "__has_attribute");
Aaron Ballman3c0f9b42014-12-05 15:05:29 +0000372 Ident__has_declspec = RegisterBuiltinMacro(*this, "__has_declspec_attribute");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000373 Ident__has_include = RegisterBuiltinMacro(*this, "__has_include");
374 Ident__has_include_next = RegisterBuiltinMacro(*this, "__has_include_next");
375 Ident__has_warning = RegisterBuiltinMacro(*this, "__has_warning");
Yunzhong Gaoef309f42014-04-11 20:55:19 +0000376 Ident__is_identifier = RegisterBuiltinMacro(*this, "__is_identifier");
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000377
Douglas Gregorc83de302012-09-25 15:44:52 +0000378 // Modules.
Richard Smithe0fa4c82016-04-21 01:46:37 +0000379 Ident__building_module = RegisterBuiltinMacro(*this, "__building_module");
380 if (!LangOpts.CurrentModule.empty())
381 Ident__MODULE__ = RegisterBuiltinMacro(*this, "__MODULE__");
382 else
Craig Topperd2d442c2014-05-17 23:10:59 +0000383 Ident__MODULE__ = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000384}
385
386/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
387/// in its expansion, currently expands to that token literally.
388static bool isTrivialSingleTokenExpansion(const MacroInfo *MI,
389 const IdentifierInfo *MacroIdent,
390 Preprocessor &PP) {
391 IdentifierInfo *II = MI->getReplacementToken(0).getIdentifierInfo();
392
393 // If the token isn't an identifier, it's always literally expanded.
Craig Topperd2d442c2014-05-17 23:10:59 +0000394 if (!II) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000395
396 // If the information about this identifier is out of date, update it from
397 // the external source.
398 if (II->isOutOfDate())
399 PP.getExternalSource()->updateOutOfDateIdentifier(*II);
400
401 // If the identifier is a macro, and if that macro is enabled, it may be
402 // expanded so it's not a trivial expansion.
Richard Smith20e883e2015-04-29 23:20:19 +0000403 if (auto *ExpansionMI = PP.getMacroInfo(II))
Richard Smith3d5925b2015-04-29 23:26:13 +0000404 if (ExpansionMI->isEnabled() &&
Richard Smith20e883e2015-04-29 23:20:19 +0000405 // Fast expanding "#define X X" is ok, because X would be disabled.
406 II != MacroIdent)
407 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000408
409 // If this is an object-like macro invocation, it is safe to trivially expand
410 // it.
411 if (MI->isObjectLike()) return true;
412
413 // If this is a function-like macro invocation, it's safe to trivially expand
414 // as long as the identifier is not a macro argument.
Daniel Marjamakie4770da2015-05-29 09:15:24 +0000415 return std::find(MI->arg_begin(), MI->arg_end(), II) == MI->arg_end();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000416}
417
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000418/// isNextPPTokenLParen - Determine whether the next preprocessor token to be
419/// lexed is a '('. If so, consume the token and return true, if not, this
420/// method should have no observable side-effect on the lexed tokens.
421bool Preprocessor::isNextPPTokenLParen() {
422 // Do some quick tests for rejection cases.
423 unsigned Val;
424 if (CurLexer)
425 Val = CurLexer->isNextPPTokenLParen();
426 else if (CurPTHLexer)
427 Val = CurPTHLexer->isNextPPTokenLParen();
428 else
429 Val = CurTokenLexer->isNextTokenLParen();
430
431 if (Val == 2) {
432 // We have run off the end. If it's a source file we don't
433 // examine enclosing ones (C99 5.1.1.2p4). Otherwise walk up the
434 // macro stack.
435 if (CurPPLexer)
436 return false;
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000437 for (const IncludeStackInfo &Entry : llvm::reverse(IncludeMacroStack)) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000438 if (Entry.TheLexer)
439 Val = Entry.TheLexer->isNextPPTokenLParen();
440 else if (Entry.ThePTHLexer)
441 Val = Entry.ThePTHLexer->isNextPPTokenLParen();
442 else
443 Val = Entry.TheTokenLexer->isNextTokenLParen();
444
445 if (Val != 2)
446 break;
447
448 // Ran off the end of a source file?
449 if (Entry.ThePPLexer)
450 return false;
451 }
452 }
453
454 // Okay, if we know that the token is a '(', lex it and return. Otherwise we
455 // have found something that isn't a '(' or we found the end of the
456 // translation unit. In either case, return false.
457 return Val == 1;
458}
459
460/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
461/// expanded as a macro, handle it and return the next token as 'Identifier'.
462bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
Richard Smith20e883e2015-04-29 23:20:19 +0000463 const MacroDefinition &M) {
464 MacroInfo *MI = M.getMacroInfo();
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000465
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000466 // If this is a macro expansion in the "#if !defined(x)" line for the file,
467 // then the macro could expand to different things in other contexts, we need
468 // to disable the optimization in this case.
469 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
470
471 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
472 if (MI->isBuiltinMacro()) {
Richard Smith36bd40d2015-05-04 03:15:40 +0000473 if (Callbacks)
474 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
475 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000476 ExpandBuiltinMacro(Identifier);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000477 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000478 }
479
480 /// Args - If this is a function-like macro expansion, this contains,
481 /// for each macro argument, the list of tokens that were provided to the
482 /// invocation.
Craig Topperd2d442c2014-05-17 23:10:59 +0000483 MacroArgs *Args = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000484
485 // Remember where the end of the expansion occurred. For an object-like
486 // macro, this is the identifier. For a function-like macro, this is the ')'.
487 SourceLocation ExpansionEnd = Identifier.getLocation();
488
489 // If this is a function-like macro, read the arguments.
490 if (MI->isFunctionLike()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000491 // Remember that we are now parsing the arguments to a macro invocation.
492 // Preprocessor directives used inside macro arguments are not portable, and
493 // this enables the warning.
494 InMacroArgs = true;
495 Args = ReadFunctionLikeMacroArgs(Identifier, MI, ExpansionEnd);
496
497 // Finished parsing args.
498 InMacroArgs = false;
499
500 // If there was an error parsing the arguments, bail out.
Craig Topperd2d442c2014-05-17 23:10:59 +0000501 if (!Args) return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000502
503 ++NumFnMacroExpanded;
504 } else {
505 ++NumMacroExpanded;
506 }
507
508 // Notice that this macro has been used.
509 markMacroAsUsed(MI);
510
511 // Remember where the token is expanded.
512 SourceLocation ExpandLoc = Identifier.getLocation();
513 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
514
515 if (Callbacks) {
516 if (InMacroArgs) {
517 // We can have macro expansion inside a conditional directive while
518 // reading the function macro arguments. To ensure, in that case, that
519 // MacroExpands callbacks still happen in source order, queue this
520 // callback to have it happen after the function macro callback.
521 DelayedMacroExpandsCallbacks.push_back(
Richard Smith36bd40d2015-05-04 03:15:40 +0000522 MacroExpandsInfo(Identifier, M, ExpansionRange));
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000523 } else {
Richard Smith36bd40d2015-05-04 03:15:40 +0000524 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000525 if (!DelayedMacroExpandsCallbacks.empty()) {
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000526 for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +0000527 // FIXME: We lose macro args info with delayed callback.
Craig Topperd2d442c2014-05-17 23:10:59 +0000528 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
529 /*Args=*/nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000530 }
531 DelayedMacroExpandsCallbacks.clear();
532 }
533 }
534 }
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000535
536 // If the macro definition is ambiguous, complain.
Richard Smith20e883e2015-04-29 23:20:19 +0000537 if (M.isAmbiguous()) {
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000538 Diag(Identifier, diag::warn_pp_ambiguous_macro)
539 << Identifier.getIdentifierInfo();
540 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
541 << Identifier.getIdentifierInfo();
Richard Smith20e883e2015-04-29 23:20:19 +0000542 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
543 if (OtherMI != MI)
544 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
545 << Identifier.getIdentifierInfo();
546 });
Douglas Gregor5968b1b2012-10-11 21:07:39 +0000547 }
548
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000549 // If we started lexing a macro, enter the macro expansion body.
550
551 // If this macro expands to no tokens, don't bother to push it onto the
552 // expansion stack, only to take it right back off.
553 if (MI->getNumTokens() == 0) {
554 // No need for arg info.
555 if (Args) Args->destroy(*this);
556
Eli Friedman0834a4b2013-09-19 00:41:32 +0000557 // Propagate whitespace info as if we had pushed, then popped,
558 // a macro context.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000559 Identifier.setFlag(Token::LeadingEmptyMacro);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000560 PropagateLineStartLeadingSpaceInfo(Identifier);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000561 ++NumFastMacroExpanded;
562 return false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000563 } else if (MI->getNumTokens() == 1 &&
564 isTrivialSingleTokenExpansion(MI, Identifier.getIdentifierInfo(),
565 *this)) {
566 // Otherwise, if this macro expands into a single trivially-expanded
567 // token: expand it now. This handles common cases like
568 // "#define VAL 42".
569
570 // No need for arg info.
571 if (Args) Args->destroy(*this);
572
573 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
574 // identifier to the expanded token.
575 bool isAtStartOfLine = Identifier.isAtStartOfLine();
576 bool hasLeadingSpace = Identifier.hasLeadingSpace();
577
578 // Replace the result token.
579 Identifier = MI->getReplacementToken(0);
580
581 // Restore the StartOfLine/LeadingSpace markers.
582 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
583 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
584
585 // Update the tokens location to include both its expansion and physical
586 // locations.
587 SourceLocation Loc =
588 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
589 ExpansionEnd,Identifier.getLength());
590 Identifier.setLocation(Loc);
591
592 // If this is a disabled macro or #define X X, we must mark the result as
593 // unexpandable.
594 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
595 if (MacroInfo *NewMI = getMacroInfo(NewII))
596 if (!NewMI->isEnabled() || NewMI == MI) {
597 Identifier.setFlag(Token::DisableExpand);
Douglas Gregor1a347f72013-01-30 23:10:17 +0000598 // Don't warn for "#define X X" like "#define bool bool" from
599 // stdbool.h.
600 if (NewMI != MI || MI->isFunctionLike())
601 Diag(Identifier, diag::pp_disabled_macro_expansion);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000602 }
603 }
604
605 // Since this is not an identifier token, it can't be macro expanded, so
606 // we're done.
607 ++NumFastMacroExpanded;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000608 return true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000609 }
610
611 // Start expanding the macro.
612 EnterMacro(Identifier, ExpansionEnd, MI, Args);
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000613 return false;
614}
615
Richard Trieu79b45382013-07-23 18:01:49 +0000616enum Bracket {
617 Brace,
618 Paren
619};
620
621/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
622/// token vector are properly nested.
623static bool CheckMatchedBrackets(const SmallVectorImpl<Token> &Tokens) {
624 SmallVector<Bracket, 8> Brackets;
625 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
626 E = Tokens.end();
627 I != E; ++I) {
628 if (I->is(tok::l_paren)) {
629 Brackets.push_back(Paren);
630 } else if (I->is(tok::r_paren)) {
631 if (Brackets.empty() || Brackets.back() == Brace)
632 return false;
633 Brackets.pop_back();
634 } else if (I->is(tok::l_brace)) {
635 Brackets.push_back(Brace);
636 } else if (I->is(tok::r_brace)) {
637 if (Brackets.empty() || Brackets.back() == Paren)
638 return false;
639 Brackets.pop_back();
640 }
641 }
Alexander Kornienkoa26c4952015-12-28 15:30:42 +0000642 return Brackets.empty();
Richard Trieu79b45382013-07-23 18:01:49 +0000643}
644
645/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
646/// vector of tokens in NewTokens. The new number of arguments will be placed
647/// in NumArgs and the ranges which need to surrounded in parentheses will be
648/// in ParenHints.
649/// Returns false if the token stream cannot be changed. If this is because
650/// of an initializer list starting a macro argument, the range of those
651/// initializer lists will be place in InitLists.
652static bool GenerateNewArgTokens(Preprocessor &PP,
653 SmallVectorImpl<Token> &OldTokens,
654 SmallVectorImpl<Token> &NewTokens,
655 unsigned &NumArgs,
656 SmallVectorImpl<SourceRange> &ParenHints,
657 SmallVectorImpl<SourceRange> &InitLists) {
658 if (!CheckMatchedBrackets(OldTokens))
659 return false;
660
661 // Once it is known that the brackets are matched, only a simple count of the
662 // braces is needed.
663 unsigned Braces = 0;
664
665 // First token of a new macro argument.
666 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
667
668 // First closing brace in a new macro argument. Used to generate
669 // SourceRanges for InitLists.
670 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
671 NumArgs = 0;
672 Token TempToken;
673 // Set to true when a macro separator token is found inside a braced list.
674 // If true, the fixed argument spans multiple old arguments and ParenHints
675 // will be updated.
676 bool FoundSeparatorToken = false;
677 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
678 E = OldTokens.end();
679 I != E; ++I) {
680 if (I->is(tok::l_brace)) {
681 ++Braces;
682 } else if (I->is(tok::r_brace)) {
683 --Braces;
684 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
685 ClosingBrace = I;
686 } else if (I->is(tok::eof)) {
687 // EOF token is used to separate macro arguments
688 if (Braces != 0) {
689 // Assume comma separator is actually braced list separator and change
690 // it back to a comma.
691 FoundSeparatorToken = true;
692 I->setKind(tok::comma);
693 I->setLength(1);
694 } else { // Braces == 0
695 // Separator token still separates arguments.
696 ++NumArgs;
697
698 // If the argument starts with a brace, it can't be fixed with
699 // parentheses. A different diagnostic will be given.
700 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
701 InitLists.push_back(
702 SourceRange(ArgStartIterator->getLocation(),
703 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
704 ClosingBrace = E;
705 }
706
707 // Add left paren
708 if (FoundSeparatorToken) {
709 TempToken.startToken();
710 TempToken.setKind(tok::l_paren);
711 TempToken.setLocation(ArgStartIterator->getLocation());
712 TempToken.setLength(0);
713 NewTokens.push_back(TempToken);
714 }
715
716 // Copy over argument tokens
717 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
718
719 // Add right paren and store the paren locations in ParenHints
720 if (FoundSeparatorToken) {
721 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
722 TempToken.startToken();
723 TempToken.setKind(tok::r_paren);
724 TempToken.setLocation(Loc);
725 TempToken.setLength(0);
726 NewTokens.push_back(TempToken);
727 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
728 Loc));
729 }
730
731 // Copy separator token
732 NewTokens.push_back(*I);
733
734 // Reset values
735 ArgStartIterator = I + 1;
736 FoundSeparatorToken = false;
737 }
738 }
739 }
740
741 return !ParenHints.empty() && InitLists.empty();
742}
743
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000744/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
745/// token is the '(' of the macro, this method is invoked to read all of the
746/// actual arguments specified for the macro invocation. This returns null on
747/// error.
748MacroArgs *Preprocessor::ReadFunctionLikeMacroArgs(Token &MacroName,
749 MacroInfo *MI,
750 SourceLocation &MacroEnd) {
751 // The number of fixed arguments to parse.
752 unsigned NumFixedArgsLeft = MI->getNumArgs();
753 bool isVariadic = MI->isVariadic();
754
755 // Outer loop, while there are more arguments, keep reading them.
756 Token Tok;
757
758 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
759 // an argument value in a macro could expand to ',' or '(' or ')'.
760 LexUnexpandedToken(Tok);
761 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
762
763 // ArgTokens - Build up a list of tokens that make up each argument. Each
764 // argument is separated by an EOF token. Use a SmallVector so we can avoid
765 // heap allocations in the common case.
766 SmallVector<Token, 64> ArgTokens;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000767 bool ContainsCodeCompletionTok = false;
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000768 bool FoundElidedComma = false;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000769
Richard Trieu79b45382013-07-23 18:01:49 +0000770 SourceLocation TooManyArgsLoc;
771
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000772 unsigned NumActuals = 0;
773 while (Tok.isNot(tok::r_paren)) {
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000774 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000775 break;
776
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000777 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000778 "only expect argument separators here");
779
Erik Verbruggene4fd6522016-10-26 13:06:13 +0000780 size_t ArgTokenStart = ArgTokens.size();
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000781 SourceLocation ArgStartLoc = Tok.getLocation();
782
783 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
784 // that we already consumed the first one.
785 unsigned NumParens = 0;
786
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +0000787 while (true) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000788 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
789 // an argument value in a macro could expand to ',' or '(' or ')'.
790 LexUnexpandedToken(Tok);
791
Daniel Marjamakie59f8d72015-06-18 10:59:26 +0000792 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000793 if (!ContainsCodeCompletionTok) {
794 Diag(MacroName, diag::err_unterm_macro_invoc);
795 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
796 << MacroName.getIdentifierInfo();
797 // Do not lose the EOF/EOD. Return it to the client.
798 MacroName = Tok;
Craig Topperd2d442c2014-05-17 23:10:59 +0000799 return nullptr;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000800 }
David Blaikie2eabcc92016-02-09 18:52:09 +0000801 // Do not lose the EOF/EOD.
802 auto Toks = llvm::make_unique<Token[]>(1);
803 Toks[0] = Tok;
804 EnterTokenStream(std::move(Toks), 1, true);
805 break;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000806 } else if (Tok.is(tok::r_paren)) {
807 // If we found the ) token, the macro arg list is done.
808 if (NumParens-- == 0) {
809 MacroEnd = Tok.getLocation();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000810 if (!ArgTokens.empty() &&
811 ArgTokens.back().commaAfterElided()) {
812 FoundElidedComma = true;
813 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000814 break;
815 }
816 } else if (Tok.is(tok::l_paren)) {
817 ++NumParens;
Reid Kleckner596b85c2013-06-26 17:16:08 +0000818 } else if (Tok.is(tok::comma) && NumParens == 0 &&
819 !(Tok.getFlags() & Token::IgnoredComma)) {
820 // In Microsoft-compatibility mode, single commas from nested macro
821 // expansions should not be considered as argument separators. We test
822 // for this with the IgnoredComma token flag above.
823
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000824 // Comma ends this argument if there are more fixed arguments expected.
825 // However, if this is a variadic macro, and this is part of the
826 // variadic part, then the comma is just an argument token.
827 if (!isVariadic) break;
828 if (NumFixedArgsLeft > 1)
829 break;
830 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
831 // If this is a comment token in the argument list and we're just in
832 // -C mode (not -CC mode), discard the comment.
833 continue;
David Majnemerd8dee1f2015-03-18 07:53:20 +0000834 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000835 // Reading macro arguments can cause macros that we are currently
836 // expanding from to be popped off the expansion stack. Doing so causes
837 // them to be reenabled for expansion. Here we record whether any
838 // identifiers we lex as macro arguments correspond to disabled macros.
839 // If so, we mark the token as noexpand. This is a subtle aspect of
840 // C99 6.10.3.4p2.
841 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
842 if (!MI->isEnabled())
843 Tok.setFlag(Token::DisableExpand);
844 } else if (Tok.is(tok::code_completion)) {
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000845 ContainsCodeCompletionTok = true;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000846 if (CodeComplete)
847 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
848 MI, NumActuals);
849 // Don't mark that we reached the code-completion point because the
850 // parser is going to handle the token and there will be another
851 // code-completion callback.
852 }
853
854 ArgTokens.push_back(Tok);
855 }
856
857 // If this was an empty argument list foo(), don't add this as an empty
858 // argument.
859 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
860 break;
861
862 // If this is not a variadic macro, and too many args were specified, emit
863 // an error.
Richard Trieu79b45382013-07-23 18:01:49 +0000864 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000865 if (ArgTokens.size() != ArgTokenStart)
Richard Trieu79b45382013-07-23 18:01:49 +0000866 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
867 else
868 TooManyArgsLoc = ArgStartLoc;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000869 }
870
Richard Trieu79b45382013-07-23 18:01:49 +0000871 // Empty arguments are standard in C99 and C++0x, and are supported as an
872 // extension in other modes.
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000873 if (ArgTokens.size() == ArgTokenStart && !LangOpts.C99)
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000874 Diag(Tok, LangOpts.CPlusPlus11 ?
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000875 diag::warn_cxx98_compat_empty_fnmacro_arg :
876 diag::ext_empty_fnmacro_arg);
877
878 // Add a marker EOF token to the end of the token list for this argument.
879 Token EOFTok;
880 EOFTok.startToken();
881 EOFTok.setKind(tok::eof);
882 EOFTok.setLocation(Tok.getLocation());
883 EOFTok.setLength(0);
884 ArgTokens.push_back(EOFTok);
885 ++NumActuals;
Richard Trieu79b45382013-07-23 18:01:49 +0000886 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
Argyrios Kyrtzidisfb703802013-02-22 22:28:58 +0000887 --NumFixedArgsLeft;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000888 }
889
890 // Okay, we either found the r_paren. Check to see if we parsed too few
891 // arguments.
892 unsigned MinArgsExpected = MI->getNumArgs();
893
Richard Trieu79b45382013-07-23 18:01:49 +0000894 // If this is not a variadic macro, and too many args were specified, emit
895 // an error.
896 if (!isVariadic && NumActuals > MinArgsExpected &&
897 !ContainsCodeCompletionTok) {
898 // Emit the diagnostic at the macro name in case there is a missing ).
899 // Emitting it at the , could be far away from the macro name.
900 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
901 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
902 << MacroName.getIdentifierInfo();
903
904 // Commas from braced initializer lists will be treated as argument
905 // separators inside macros. Attempt to correct for this with parentheses.
906 // TODO: See if this can be generalized to angle brackets for templates
907 // inside macro arguments.
908
Bob Wilson57217352013-07-27 21:59:57 +0000909 SmallVector<Token, 4> FixedArgTokens;
Richard Trieu79b45382013-07-23 18:01:49 +0000910 unsigned FixedNumArgs = 0;
911 SmallVector<SourceRange, 4> ParenHints, InitLists;
912 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
913 ParenHints, InitLists)) {
914 if (!InitLists.empty()) {
915 DiagnosticBuilder DB =
916 Diag(MacroName,
917 diag::note_init_list_at_beginning_of_macro_argument);
Craig Toppere335f252015-10-04 04:53:55 +0000918 for (SourceRange Range : InitLists)
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000919 DB << Range;
Richard Trieu79b45382013-07-23 18:01:49 +0000920 }
Craig Topperd2d442c2014-05-17 23:10:59 +0000921 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000922 }
923 if (FixedNumArgs != MinArgsExpected)
Craig Topperd2d442c2014-05-17 23:10:59 +0000924 return nullptr;
Richard Trieu79b45382013-07-23 18:01:49 +0000925
926 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
Craig Toppere335f252015-10-04 04:53:55 +0000927 for (SourceRange ParenLocation : ParenHints) {
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000928 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
929 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
Richard Trieu79b45382013-07-23 18:01:49 +0000930 }
931 ArgTokens.swap(FixedArgTokens);
932 NumActuals = FixedNumArgs;
933 }
934
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000935 // See MacroArgs instance var for description of this.
936 bool isVarargsElided = false;
937
Argyrios Kyrtzidisd4635d42012-12-21 01:51:12 +0000938 if (ContainsCodeCompletionTok) {
939 // Recover from not-fully-formed macro invocation during code-completion.
940 Token EOFTok;
941 EOFTok.startToken();
942 EOFTok.setKind(tok::eof);
943 EOFTok.setLocation(Tok.getLocation());
944 EOFTok.setLength(0);
945 for (; NumActuals < MinArgsExpected; ++NumActuals)
946 ArgTokens.push_back(EOFTok);
947 }
948
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000949 if (NumActuals < MinArgsExpected) {
950 // There are several cases where too few arguments is ok, handle them now.
951 if (NumActuals == 0 && MinArgsExpected == 1) {
952 // #define A(X) or #define A(...) ---> A()
953
954 // If there is exactly one argument, and that argument is missing,
955 // then we have an empty "()" argument empty list. This is fine, even if
956 // the macro expects one argument (the argument is just empty).
957 isVarargsElided = MI->isVariadic();
Ehsan Akhgari34461a62016-01-22 19:26:44 +0000958 } else if ((FoundElidedComma || MI->isVariadic()) &&
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000959 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
960 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
961 // Varargs where the named vararg parameter is missing: OK as extension.
962 // #define A(x, ...)
963 // A("blah")
Eli Friedman14d3c792012-11-14 02:18:46 +0000964 //
965 // If the macro contains the comma pasting extension, the diagnostic
966 // is suppressed; we know we'll get another diagnostic later.
967 if (!MI->hasCommaPasting()) {
968 Diag(Tok, diag::ext_missing_varargs_arg);
969 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
970 << MacroName.getIdentifierInfo();
971 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000972
973 // Remember this occurred, allowing us to elide the comma when used for
974 // cases like:
975 // #define A(x, foo...) blah(a, ## foo)
976 // #define B(x, ...) blah(a, ## __VA_ARGS__)
977 // #define C(...) blah(a, ## __VA_ARGS__)
978 // A(x) B(x) C()
979 isVarargsElided = true;
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +0000980 } else if (!ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000981 // Otherwise, emit the error.
982 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +0000983 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
984 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +0000985 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +0000986 }
987
988 // Add a marker EOF token to the end of the token list for this argument.
989 SourceLocation EndLoc = Tok.getLocation();
990 Tok.startToken();
991 Tok.setKind(tok::eof);
992 Tok.setLocation(EndLoc);
993 Tok.setLength(0);
994 ArgTokens.push_back(Tok);
995
996 // If we expect two arguments, add both as empty.
997 if (NumActuals == 0 && MinArgsExpected == 2)
998 ArgTokens.push_back(Tok);
999
Argyrios Kyrtzidisc1d9a672012-12-21 01:17:20 +00001000 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
1001 !ContainsCodeCompletionTok) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001002 // Emit the diagnostic at the macro name in case there is a missing ).
1003 // Emitting it at the , could be far away from the macro name.
1004 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
Argyrios Kyrtzidis164fdb62012-12-14 18:53:47 +00001005 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1006 << MacroName.getIdentifierInfo();
Craig Topperd2d442c2014-05-17 23:10:59 +00001007 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001008 }
1009
1010 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
1011}
1012
1013/// \brief Keeps macro expanded tokens for TokenLexers.
1014//
1015/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1016/// going to lex in the cache and when it finishes the tokens are removed
1017/// from the end of the cache.
1018Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1019 ArrayRef<Token> tokens) {
1020 assert(tokLexer);
1021 if (tokens.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +00001022 return nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001023
1024 size_t newIndex = MacroExpandedTokens.size();
1025 bool cacheNeedsToGrow = tokens.size() >
1026 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1027 MacroExpandedTokens.append(tokens.begin(), tokens.end());
1028
1029 if (cacheNeedsToGrow) {
1030 // Go through all the TokenLexers whose 'Tokens' pointer points in the
1031 // buffer and update the pointers to the (potential) new buffer array.
Erik Verbruggene4fd6522016-10-26 13:06:13 +00001032 for (const auto &Lexer : MacroExpandingLexersStack) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001033 TokenLexer *prevLexer;
1034 size_t tokIndex;
Erik Verbruggene4fd6522016-10-26 13:06:13 +00001035 std::tie(prevLexer, tokIndex) = Lexer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001036 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1037 }
1038 }
1039
1040 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1041 return MacroExpandedTokens.data() + newIndex;
1042}
1043
1044void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1045 assert(!MacroExpandingLexersStack.empty());
1046 size_t tokIndex = MacroExpandingLexersStack.back().second;
1047 assert(tokIndex < MacroExpandedTokens.size());
1048 // Pop the cached macro expanded tokens from the end.
1049 MacroExpandedTokens.resize(tokIndex);
1050 MacroExpandingLexersStack.pop_back();
1051}
1052
1053/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1054/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1055/// the identifier tokens inserted.
1056static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1057 Preprocessor &PP) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001058 time_t TT = time(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001059 struct tm *TM = localtime(&TT);
1060
1061 static const char * const Months[] = {
1062 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1063 };
1064
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001065 {
1066 SmallString<32> TmpBuffer;
1067 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1068 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1069 TM->tm_mday, TM->tm_year + 1900);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001070 Token TmpTok;
1071 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001072 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001073 DATELoc = TmpTok.getLocation();
1074 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001075
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001076 {
1077 SmallString<32> TmpBuffer;
1078 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1079 TmpStream << llvm::format("\"%02d:%02d:%02d\"",
1080 TM->tm_hour, TM->tm_min, TM->tm_sec);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001081 Token TmpTok;
1082 TmpTok.startToken();
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001083 PP.CreateString(TmpStream.str(), TmpTok);
Dmitri Gribenkoae07f722012-09-24 20:56:28 +00001084 TIMELoc = TmpTok.getLocation();
1085 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001086}
1087
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001088/// HasFeature - Return true if we recognize and implement the feature
1089/// specified by the identifier as a standard language feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001090static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001091 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001092
1093 // Normalize the feature name, __foo__ becomes foo.
1094 if (Feature.startswith("__") && Feature.endswith("__") && Feature.size() >= 4)
1095 Feature = Feature.substr(2, Feature.size() - 4);
1096
1097 return llvm::StringSwitch<bool>(Feature)
Alexander Potapenkob9b73ef2015-06-19 12:19:07 +00001098 .Case("address_sanitizer",
1099 LangOpts.Sanitize.hasOneOf(SanitizerKind::Address |
1100 SanitizerKind::KernelAddress))
Douglas Gregor4c27d102015-06-29 18:11:42 +00001101 .Case("assume_nonnull", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001102 .Case("attribute_analyzer_noreturn", true)
1103 .Case("attribute_availability", true)
1104 .Case("attribute_availability_with_message", true)
Bob Wilsonb111ec92015-03-02 19:01:14 +00001105 .Case("attribute_availability_app_extension", true)
Jordan Rose7e5de9c2015-07-16 22:30:10 +00001106 .Case("attribute_availability_with_version_underscores", true)
Tim Northover7a73cc72015-10-30 16:30:49 +00001107 .Case("attribute_availability_tvos", true)
1108 .Case("attribute_availability_watchos", true)
Manman Ren6731d732016-02-22 18:24:30 +00001109 .Case("attribute_availability_with_strict", true)
Manman Ren75bc6762016-03-21 17:30:55 +00001110 .Case("attribute_availability_with_replacement", true)
Duncan P. N. Exon Smithec599a92016-02-26 19:27:00 +00001111 .Case("attribute_availability_in_templates", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001112 .Case("attribute_cf_returns_not_retained", true)
1113 .Case("attribute_cf_returns_retained", true)
Douglas Gregoreb6e64c2015-06-19 23:17:46 +00001114 .Case("attribute_cf_returns_on_parameters", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001115 .Case("attribute_deprecated_with_message", true)
Manman Renc7890fe2016-03-16 18:50:49 +00001116 .Case("attribute_deprecated_with_replacement", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001117 .Case("attribute_ext_vector_type", true)
1118 .Case("attribute_ns_returns_not_retained", true)
1119 .Case("attribute_ns_returns_retained", true)
1120 .Case("attribute_ns_consumes_self", true)
1121 .Case("attribute_ns_consumed", true)
1122 .Case("attribute_cf_consumed", true)
1123 .Case("attribute_objc_ivar_unused", true)
1124 .Case("attribute_objc_method_family", true)
1125 .Case("attribute_overloadable", true)
1126 .Case("attribute_unavailable_with_message", true)
1127 .Case("attribute_unused_on_fields", true)
Argyrios Kyrtzidis9f4950a2017-05-24 01:38:00 +00001128 .Case("attribute_diagnose_if_objc", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001129 .Case("blocks", LangOpts.Blocks)
1130 .Case("c_thread_safety_attributes", true)
1131 .Case("cxx_exceptions", LangOpts.CXXExceptions)
Reid Kleckner6cf4a6b2015-08-13 17:56:49 +00001132 .Case("cxx_rtti", LangOpts.RTTI && LangOpts.RTTIData)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001133 .Case("enumerator_attributes", true)
Douglas Gregor4c27d102015-06-29 18:11:42 +00001134 .Case("nullability", true)
Jordan Rose303e2f12016-11-10 23:28:17 +00001135 .Case("nullability_on_arrays", true)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001136 .Case("memory_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Memory))
1137 .Case("thread_sanitizer", LangOpts.Sanitize.has(SanitizerKind::Thread))
1138 .Case("dataflow_sanitizer", LangOpts.Sanitize.has(SanitizerKind::DataFlow))
Derek Bruening256c2e12016-04-21 21:32:04 +00001139 .Case("efficiency_sanitizer",
1140 LangOpts.Sanitize.hasOneOf(SanitizerKind::Efficiency))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001141 // Objective-C features
1142 .Case("objc_arr", LangOpts.ObjCAutoRefCount) // FIXME: REMOVE?
1143 .Case("objc_arc", LangOpts.ObjCAutoRefCount)
John McCall460ce582015-10-22 18:38:17 +00001144 .Case("objc_arc_weak", LangOpts.ObjCWeak)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001145 .Case("objc_default_synthesize_properties", LangOpts.ObjC2)
1146 .Case("objc_fixed_enum", LangOpts.ObjC2)
1147 .Case("objc_instancetype", LangOpts.ObjC2)
Douglas Gregorab209d82015-07-07 03:58:42 +00001148 .Case("objc_kindof", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001149 .Case("objc_modules", LangOpts.ObjC2 && LangOpts.Modules)
1150 .Case("objc_nonfragile_abi", LangOpts.ObjCRuntime.isNonFragile())
1151 .Case("objc_property_explicit_atomic",
1152 true) // Does clang support explicit "atomic" keyword?
1153 .Case("objc_protocol_qualifier_mangling", true)
1154 .Case("objc_weak_class", LangOpts.ObjCRuntime.hasWeakClassImport())
1155 .Case("ownership_holds", true)
1156 .Case("ownership_returns", true)
1157 .Case("ownership_takes", true)
1158 .Case("objc_bool", true)
1159 .Case("objc_subscripting", LangOpts.ObjCRuntime.isNonFragile())
1160 .Case("objc_array_literals", LangOpts.ObjC2)
1161 .Case("objc_dictionary_literals", LangOpts.ObjC2)
1162 .Case("objc_boxed_expressions", LangOpts.ObjC2)
Alex Denisovfde64952015-06-26 05:28:36 +00001163 .Case("objc_boxed_nsvalue_expressions", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001164 .Case("arc_cf_code_audited", true)
John McCall28592582015-02-01 22:34:06 +00001165 .Case("objc_bridge_id", true)
1166 .Case("objc_bridge_id_on_typedefs", true)
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001167 .Case("objc_generics", LangOpts.ObjC2)
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001168 .Case("objc_generics_variance", LangOpts.ObjC2)
Manman Ren515758e2016-03-10 23:51:03 +00001169 .Case("objc_class_property", LangOpts.ObjC2)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001170 // C11 features
1171 .Case("c_alignas", LangOpts.C11)
Nico Weber736a9932014-12-03 01:25:49 +00001172 .Case("c_alignof", LangOpts.C11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001173 .Case("c_atomic", LangOpts.C11)
1174 .Case("c_generic_selections", LangOpts.C11)
1175 .Case("c_static_assert", LangOpts.C11)
1176 .Case("c_thread_local",
1177 LangOpts.C11 && PP.getTargetInfo().isTLSSupported())
1178 // C++11 features
1179 .Case("cxx_access_control_sfinae", LangOpts.CPlusPlus11)
1180 .Case("cxx_alias_templates", LangOpts.CPlusPlus11)
1181 .Case("cxx_alignas", LangOpts.CPlusPlus11)
Nico Weber736a9932014-12-03 01:25:49 +00001182 .Case("cxx_alignof", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001183 .Case("cxx_atomic", LangOpts.CPlusPlus11)
1184 .Case("cxx_attributes", LangOpts.CPlusPlus11)
1185 .Case("cxx_auto_type", LangOpts.CPlusPlus11)
1186 .Case("cxx_constexpr", LangOpts.CPlusPlus11)
Richard Smith5e29dd32017-01-20 00:45:35 +00001187 .Case("cxx_constexpr_string_builtins", LangOpts.CPlusPlus11)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001188 .Case("cxx_decltype", LangOpts.CPlusPlus11)
1189 .Case("cxx_decltype_incomplete_return_types", LangOpts.CPlusPlus11)
1190 .Case("cxx_default_function_template_args", LangOpts.CPlusPlus11)
1191 .Case("cxx_defaulted_functions", LangOpts.CPlusPlus11)
1192 .Case("cxx_delegating_constructors", LangOpts.CPlusPlus11)
1193 .Case("cxx_deleted_functions", LangOpts.CPlusPlus11)
1194 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus11)
1195 .Case("cxx_generalized_initializers", LangOpts.CPlusPlus11)
1196 .Case("cxx_implicit_moves", LangOpts.CPlusPlus11)
1197 .Case("cxx_inheriting_constructors", LangOpts.CPlusPlus11)
1198 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus11)
1199 .Case("cxx_lambdas", LangOpts.CPlusPlus11)
1200 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus11)
1201 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus11)
1202 .Case("cxx_noexcept", LangOpts.CPlusPlus11)
1203 .Case("cxx_nullptr", LangOpts.CPlusPlus11)
1204 .Case("cxx_override_control", LangOpts.CPlusPlus11)
1205 .Case("cxx_range_for", LangOpts.CPlusPlus11)
1206 .Case("cxx_raw_string_literals", LangOpts.CPlusPlus11)
1207 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus11)
1208 .Case("cxx_rvalue_references", LangOpts.CPlusPlus11)
1209 .Case("cxx_strong_enums", LangOpts.CPlusPlus11)
1210 .Case("cxx_static_assert", LangOpts.CPlusPlus11)
1211 .Case("cxx_thread_local",
1212 LangOpts.CPlusPlus11 && PP.getTargetInfo().isTLSSupported())
1213 .Case("cxx_trailing_return", LangOpts.CPlusPlus11)
1214 .Case("cxx_unicode_literals", LangOpts.CPlusPlus11)
1215 .Case("cxx_unrestricted_unions", LangOpts.CPlusPlus11)
1216 .Case("cxx_user_literals", LangOpts.CPlusPlus11)
1217 .Case("cxx_variadic_templates", LangOpts.CPlusPlus11)
Richard Smith27143d82016-09-29 00:08:05 +00001218 // C++14 features
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001219 .Case("cxx_aggregate_nsdmi", LangOpts.CPlusPlus14)
1220 .Case("cxx_binary_literals", LangOpts.CPlusPlus14)
1221 .Case("cxx_contextual_conversions", LangOpts.CPlusPlus14)
1222 .Case("cxx_decltype_auto", LangOpts.CPlusPlus14)
1223 .Case("cxx_generic_lambdas", LangOpts.CPlusPlus14)
1224 .Case("cxx_init_captures", LangOpts.CPlusPlus14)
1225 .Case("cxx_relaxed_constexpr", LangOpts.CPlusPlus14)
1226 .Case("cxx_return_type_deduction", LangOpts.CPlusPlus14)
1227 .Case("cxx_variable_templates", LangOpts.CPlusPlus14)
Richard Smith27143d82016-09-29 00:08:05 +00001228 // NOTE: For features covered by SD-6, it is preferable to provide *only*
1229 // the SD-6 macro and not a __has_feature check.
1230
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001231 // C++ TSes
1232 //.Case("cxx_runtime_arrays", LangOpts.CPlusPlusTSArrays)
1233 //.Case("cxx_concepts", LangOpts.CPlusPlusTSConcepts)
1234 // FIXME: Should this be __has_feature or __has_extension?
1235 //.Case("raw_invocation_type", LangOpts.CPlusPlus)
1236 // Type traits
David Majnemer3e5e05a2016-05-24 17:21:42 +00001237 // N.B. Additional type traits should not be added to the following list.
1238 // Instead, they should be detected by has_extension.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001239 .Case("has_nothrow_assign", LangOpts.CPlusPlus)
1240 .Case("has_nothrow_copy", LangOpts.CPlusPlus)
1241 .Case("has_nothrow_constructor", LangOpts.CPlusPlus)
1242 .Case("has_trivial_assign", LangOpts.CPlusPlus)
1243 .Case("has_trivial_copy", LangOpts.CPlusPlus)
1244 .Case("has_trivial_constructor", LangOpts.CPlusPlus)
1245 .Case("has_trivial_destructor", LangOpts.CPlusPlus)
1246 .Case("has_virtual_destructor", LangOpts.CPlusPlus)
1247 .Case("is_abstract", LangOpts.CPlusPlus)
1248 .Case("is_base_of", LangOpts.CPlusPlus)
1249 .Case("is_class", LangOpts.CPlusPlus)
1250 .Case("is_constructible", LangOpts.CPlusPlus)
1251 .Case("is_convertible_to", LangOpts.CPlusPlus)
1252 .Case("is_empty", LangOpts.CPlusPlus)
1253 .Case("is_enum", LangOpts.CPlusPlus)
1254 .Case("is_final", LangOpts.CPlusPlus)
1255 .Case("is_literal", LangOpts.CPlusPlus)
David Majnemer3e5e05a2016-05-24 17:21:42 +00001256 .Case("is_standard_layout", LangOpts.CPlusPlus)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001257 .Case("is_pod", LangOpts.CPlusPlus)
1258 .Case("is_polymorphic", LangOpts.CPlusPlus)
David Majnemer3e5e05a2016-05-24 17:21:42 +00001259 .Case("is_sealed", LangOpts.CPlusPlus && LangOpts.MicrosoftExt)
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001260 .Case("is_trivial", LangOpts.CPlusPlus)
1261 .Case("is_trivially_assignable", LangOpts.CPlusPlus)
1262 .Case("is_trivially_constructible", LangOpts.CPlusPlus)
1263 .Case("is_trivially_copyable", LangOpts.CPlusPlus)
1264 .Case("is_union", LangOpts.CPlusPlus)
1265 .Case("modules", LangOpts.Modules)
Peter Collingbournec4122c12015-06-15 21:08:13 +00001266 .Case("safe_stack", LangOpts.Sanitize.has(SanitizerKind::SafeStack))
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001267 .Case("tls", PP.getTargetInfo().isTLSSupported())
1268 .Case("underlying_type", LangOpts.CPlusPlus)
1269 .Default(false);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001270}
1271
1272/// HasExtension - Return true if we recognize and implement the feature
1273/// specified by the identifier, either as an extension or a standard language
1274/// feature.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001275static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1276 if (HasFeature(PP, Extension))
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001277 return true;
1278
1279 // If the use of an extension results in an error diagnostic, extensions are
1280 // effectively unavailable, so just return false here.
Alp Tokerac4e8e52014-06-22 21:58:33 +00001281 if (PP.getDiagnostics().getExtensionHandlingBehavior() >=
1282 diag::Severity::Error)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001283 return false;
1284
1285 const LangOptions &LangOpts = PP.getLangOpts();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001286
1287 // Normalize the extension name, __foo__ becomes foo.
1288 if (Extension.startswith("__") && Extension.endswith("__") &&
1289 Extension.size() >= 4)
1290 Extension = Extension.substr(2, Extension.size() - 4);
1291
1292 // Because we inherit the feature list from HasFeature, this string switch
1293 // must be less restrictive than HasFeature's.
1294 return llvm::StringSwitch<bool>(Extension)
1295 // C11 features supported by other languages as extensions.
1296 .Case("c_alignas", true)
Nico Weber736a9932014-12-03 01:25:49 +00001297 .Case("c_alignof", true)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001298 .Case("c_atomic", true)
1299 .Case("c_generic_selections", true)
1300 .Case("c_static_assert", true)
Ed Schouten401aeba2013-09-14 16:17:20 +00001301 .Case("c_thread_local", PP.getTargetInfo().isTLSSupported())
Richard Smith0a715422013-05-07 19:32:56 +00001302 // C++11 features supported by other languages as extensions.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001303 .Case("cxx_atomic", LangOpts.CPlusPlus)
1304 .Case("cxx_deleted_functions", LangOpts.CPlusPlus)
1305 .Case("cxx_explicit_conversions", LangOpts.CPlusPlus)
1306 .Case("cxx_inline_namespaces", LangOpts.CPlusPlus)
1307 .Case("cxx_local_type_template_args", LangOpts.CPlusPlus)
1308 .Case("cxx_nonstatic_member_init", LangOpts.CPlusPlus)
1309 .Case("cxx_override_control", LangOpts.CPlusPlus)
1310 .Case("cxx_range_for", LangOpts.CPlusPlus)
1311 .Case("cxx_reference_qualified_functions", LangOpts.CPlusPlus)
1312 .Case("cxx_rvalue_references", LangOpts.CPlusPlus)
Eric Fiselier7aa0d4a2015-05-12 22:37:23 +00001313 .Case("cxx_variadic_templates", LangOpts.CPlusPlus)
Richard Smith27143d82016-09-29 00:08:05 +00001314 // C++14 features supported by other languages as extensions.
Richard Smith0a715422013-05-07 19:32:56 +00001315 .Case("cxx_binary_literals", true)
Richard Smithb438e622013-09-28 04:37:56 +00001316 .Case("cxx_init_captures", LangOpts.CPlusPlus11)
Alp Tokera8bb9c92014-01-15 04:11:24 +00001317 .Case("cxx_variable_templates", LangOpts.CPlusPlus)
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001318 .Default(false);
1319}
1320
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001321/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1322/// or '__has_include_next("path")' expression.
1323/// Returns true if successful.
1324static bool EvaluateHasIncludeCommon(Token &Tok,
1325 IdentifierInfo *II, Preprocessor &PP,
Richard Smith25d50752014-10-20 00:15:49 +00001326 const DirectoryLookup *LookupFrom,
1327 const FileEntry *LookupFromFile) {
Richard Trieuda031982012-10-22 20:28:48 +00001328 // Save the location of the current token. If a '(' is later found, use
Aaron Ballman5cb24112013-01-15 21:59:46 +00001329 // that location. If not, use the end of this location instead.
Richard Trieuda031982012-10-22 20:28:48 +00001330 SourceLocation LParenLoc = Tok.getLocation();
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001331
Aaron Ballman6ce00002013-01-16 19:32:21 +00001332 // These expressions are only allowed within a preprocessor directive.
1333 if (!PP.isParsingIfOrElifDirective()) {
1334 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II->getName();
Benjamin Kramer0a126ad2015-03-29 19:05:27 +00001335 // Return a valid identifier token.
1336 assert(Tok.is(tok::identifier));
1337 Tok.setIdentifierInfo(II);
Aaron Ballman6ce00002013-01-16 19:32:21 +00001338 return false;
1339 }
1340
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001341 // Get '('.
1342 PP.LexNonComment(Tok);
1343
1344 // Ensure we have a '('.
1345 if (Tok.isNot(tok::l_paren)) {
Richard Trieuda031982012-10-22 20:28:48 +00001346 // No '(', use end of last token.
1347 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
Alp Toker751d6352013-12-30 01:59:29 +00001348 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
Richard Trieuda031982012-10-22 20:28:48 +00001349 // If the next token looks like a filename or the start of one,
1350 // assume it is and process it as such.
1351 if (!Tok.is(tok::angle_string_literal) && !Tok.is(tok::string_literal) &&
1352 !Tok.is(tok::less))
1353 return false;
1354 } else {
1355 // Save '(' location for possible missing ')' message.
1356 LParenLoc = Tok.getLocation();
1357
Eli Friedmanec94b612013-01-09 02:20:00 +00001358 if (PP.getCurrentLexer()) {
1359 // Get the file name.
1360 PP.getCurrentLexer()->LexIncludeFilename(Tok);
1361 } else {
1362 // We're in a macro, so we can't use LexIncludeFilename; just
1363 // grab the next token.
1364 PP.Lex(Tok);
1365 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001366 }
1367
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001368 // Reserve a buffer to get the spelling.
1369 SmallString<128> FilenameBuffer;
1370 StringRef Filename;
1371 SourceLocation EndLoc;
1372
1373 switch (Tok.getKind()) {
1374 case tok::eod:
1375 // If the token kind is EOD, the error has already been diagnosed.
1376 return false;
1377
1378 case tok::angle_string_literal:
1379 case tok::string_literal: {
1380 bool Invalid = false;
1381 Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1382 if (Invalid)
1383 return false;
1384 break;
1385 }
1386
1387 case tok::less:
1388 // This could be a <foo/bar.h> file coming from a macro expansion. In this
1389 // case, glue the tokens together into FilenameBuffer and interpret those.
1390 FilenameBuffer.push_back('<');
Richard Trieuda031982012-10-22 20:28:48 +00001391 if (PP.ConcatenateIncludeName(FilenameBuffer, EndLoc)) {
1392 // Let the caller know a <eod> was found by changing the Token kind.
1393 Tok.setKind(tok::eod);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001394 return false; // Found <eod> but no ">"? Diagnostic already emitted.
Richard Trieuda031982012-10-22 20:28:48 +00001395 }
Yaron Keren92e1b622015-03-18 10:17:07 +00001396 Filename = FilenameBuffer;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001397 break;
1398 default:
1399 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1400 return false;
1401 }
1402
Richard Trieuda031982012-10-22 20:28:48 +00001403 SourceLocation FilenameLoc = Tok.getLocation();
1404
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001405 // Get ')'.
1406 PP.LexNonComment(Tok);
1407
1408 // Ensure we have a trailing ).
1409 if (Tok.isNot(tok::r_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001410 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1411 << II << tok::r_paren;
Alp Tokerec543272013-12-24 09:48:30 +00001412 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001413 return false;
1414 }
1415
1416 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1417 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1418 // error.
1419 if (Filename.empty())
1420 return false;
1421
1422 // Search include directories.
1423 const DirectoryLookup *CurDir;
1424 const FileEntry *File =
Richard Smith25d50752014-10-20 00:15:49 +00001425 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
Duncan P. N. Exon Smithcfc1f6a2017-04-27 21:41:51 +00001426 CurDir, nullptr, nullptr, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001427
1428 // Get the result value. A result of true means the file exists.
Craig Topperd2d442c2014-05-17 23:10:59 +00001429 return File != nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001430}
1431
1432/// EvaluateHasInclude - Process a '__has_include("path")' expression.
1433/// Returns true if successful.
1434static bool EvaluateHasInclude(Token &Tok, IdentifierInfo *II,
1435 Preprocessor &PP) {
Richard Smith25d50752014-10-20 00:15:49 +00001436 return EvaluateHasIncludeCommon(Tok, II, PP, nullptr, nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001437}
1438
1439/// EvaluateHasIncludeNext - Process '__has_include_next("path")' expression.
1440/// Returns true if successful.
1441static bool EvaluateHasIncludeNext(Token &Tok,
1442 IdentifierInfo *II, Preprocessor &PP) {
1443 // __has_include_next is like __has_include, except that we start
1444 // searching after the current found directory. If we can't do this,
1445 // issue a diagnostic.
Yaron Kerenbc5986f2015-02-19 11:21:11 +00001446 // FIXME: Factor out duplication with
Richard Smith25d50752014-10-20 00:15:49 +00001447 // Preprocessor::HandleIncludeNextDirective.
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001448 const DirectoryLookup *Lookup = PP.GetCurDirLookup();
Richard Smith25d50752014-10-20 00:15:49 +00001449 const FileEntry *LookupFromFile = nullptr;
Erik Verbruggene0bde752016-10-27 14:17:10 +00001450 if (PP.isInPrimaryFile() && PP.getLangOpts().IsHeaderFile) {
1451 // If the main file is a header, then it's either for PCH/AST generation,
1452 // or libclang opened it. Either way, handle it as a normal include below
1453 // and do not complain about __has_include_next.
1454 } else if (PP.isInPrimaryFile()) {
Craig Topperd2d442c2014-05-17 23:10:59 +00001455 Lookup = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001456 PP.Diag(Tok, diag::pp_include_next_in_primary);
Richard Smithd1386302017-05-04 00:29:54 +00001457 } else if (PP.getCurrentLexerSubmodule()) {
Richard Smith25d50752014-10-20 00:15:49 +00001458 // Start looking up in the directory *after* the one in which the current
1459 // file would be found, if any.
1460 assert(PP.getCurrentLexer() && "#include_next directive in macro?");
1461 LookupFromFile = PP.getCurrentLexer()->getFileEntry();
1462 Lookup = nullptr;
Craig Topperd2d442c2014-05-17 23:10:59 +00001463 } else if (!Lookup) {
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001464 PP.Diag(Tok, diag::pp_include_next_absolute_path);
1465 } else {
1466 // Start looking up in the next directory.
1467 ++Lookup;
1468 }
1469
Richard Smith25d50752014-10-20 00:15:49 +00001470 return EvaluateHasIncludeCommon(Tok, II, PP, Lookup, LookupFromFile);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001471}
1472
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001473/// \brief Process single-argument builtin feature-like macros that return
1474/// integer values.
1475static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1476 Token &Tok, IdentifierInfo *II,
1477 Preprocessor &PP,
1478 llvm::function_ref<
1479 int(Token &Tok,
1480 bool &HasLexedNextTok)> Op) {
1481 // Parse the initial '('.
1482 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001483 if (Tok.isNot(tok::l_paren)) {
Alp Toker751d6352013-12-30 01:59:29 +00001484 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1485 << tok::l_paren;
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001486
1487 // Provide a dummy '0' value on output stream to elide further errors.
1488 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1489 OS << 0;
1490 Tok.setKind(tok::numeric_constant);
1491 }
1492 return;
Douglas Gregorc83de302012-09-25 15:44:52 +00001493 }
1494
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001495 unsigned ParenDepth = 1;
Douglas Gregorc83de302012-09-25 15:44:52 +00001496 SourceLocation LParenLoc = Tok.getLocation();
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001497 llvm::Optional<int> Result;
Douglas Gregorc83de302012-09-25 15:44:52 +00001498
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001499 Token ResultTok;
1500 bool SuppressDiagnostic = false;
1501 while (true) {
1502 // Parse next token.
1503 PP.LexUnexpandedToken(Tok);
Douglas Gregorc83de302012-09-25 15:44:52 +00001504
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001505already_lexed:
1506 switch (Tok.getKind()) {
1507 case tok::eof:
1508 case tok::eod:
1509 // Don't provide even a dummy value if the eod or eof marker is
1510 // reached. Simply provide a diagnostic.
1511 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1512 return;
1513
1514 case tok::comma:
1515 if (!SuppressDiagnostic) {
1516 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1517 SuppressDiagnostic = true;
1518 }
1519 continue;
1520
1521 case tok::l_paren:
1522 ++ParenDepth;
1523 if (Result.hasValue())
1524 break;
1525 if (!SuppressDiagnostic) {
1526 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1527 SuppressDiagnostic = true;
1528 }
1529 continue;
1530
1531 case tok::r_paren:
1532 if (--ParenDepth > 0)
1533 continue;
1534
1535 // The last ')' has been reached; return the value if one found or
1536 // a diagnostic and a dummy value.
1537 if (Result.hasValue())
1538 OS << Result.getValue();
1539 else {
1540 OS << 0;
1541 if (!SuppressDiagnostic)
1542 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1543 }
1544 Tok.setKind(tok::numeric_constant);
1545 return;
1546
1547 default: {
1548 // Parse the macro argument, if one not found so far.
1549 if (Result.hasValue())
1550 break;
1551
1552 bool HasLexedNextToken = false;
1553 Result = Op(Tok, HasLexedNextToken);
1554 ResultTok = Tok;
1555 if (HasLexedNextToken)
1556 goto already_lexed;
1557 continue;
1558 }
1559 }
1560
1561 // Diagnose missing ')'.
1562 if (!SuppressDiagnostic) {
1563 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1564 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1565 Diag << LastII;
1566 else
1567 Diag << ResultTok.getKind();
1568 Diag << tok::r_paren << ResultTok.getLocation();
1569 }
1570 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1571 SuppressDiagnostic = true;
1572 }
Douglas Gregorc83de302012-09-25 15:44:52 +00001573 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001574}
Douglas Gregorc83de302012-09-25 15:44:52 +00001575
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001576/// \brief Helper function to return the IdentifierInfo structure of a Token
1577/// or generate a diagnostic if none available.
1578static IdentifierInfo *ExpectFeatureIdentifierInfo(Token &Tok,
1579 Preprocessor &PP,
1580 signed DiagID) {
1581 IdentifierInfo *II;
1582 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1583 return II;
Douglas Gregorc83de302012-09-25 15:44:52 +00001584
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001585 PP.Diag(Tok.getLocation(), DiagID);
1586 return nullptr;
Douglas Gregorc83de302012-09-25 15:44:52 +00001587}
1588
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001589/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1590/// as a builtin macro, handle it and return the next token as 'Tok'.
1591void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1592 // Figure out which token this is.
1593 IdentifierInfo *II = Tok.getIdentifierInfo();
1594 assert(II && "Can't be a macro without id info!");
1595
1596 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1597 // invoke the pragma handler, then lex the token after it.
1598 if (II == Ident_Pragma)
1599 return Handle_Pragma(Tok);
1600 else if (II == Ident__pragma) // in non-MS mode this is null
1601 return HandleMicrosoft__pragma(Tok);
1602
1603 ++NumBuiltinMacroExpanded;
1604
1605 SmallString<128> TmpBuffer;
1606 llvm::raw_svector_ostream OS(TmpBuffer);
1607
1608 // Set up the return result.
Craig Topperd2d442c2014-05-17 23:10:59 +00001609 Tok.setIdentifierInfo(nullptr);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001610 Tok.clearFlag(Token::NeedsCleaning);
1611
1612 if (II == Ident__LINE__) {
1613 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1614 // source file) of the current source line (an integer constant)". This can
1615 // be affected by #line.
1616 SourceLocation Loc = Tok.getLocation();
1617
1618 // Advance to the location of the first _, this might not be the first byte
1619 // of the token if it starts with an escaped newline.
1620 Loc = AdvanceToTokenCharacter(Loc, 0);
1621
1622 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1623 // a macro expansion. This doesn't matter for object-like macros, but
1624 // can matter for a function-like macro that expands to contain __LINE__.
1625 // Skip down through expansion points until we find a file loc for the
1626 // end of the expansion history.
1627 Loc = SourceMgr.getExpansionRange(Loc).second;
1628 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1629
1630 // __LINE__ expands to a simple numeric value.
1631 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1632 Tok.setKind(tok::numeric_constant);
1633 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__) {
1634 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1635 // character string literal)". This can be affected by #line.
1636 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1637
1638 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1639 // #include stack instead of the current file.
1640 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1641 SourceLocation NextLoc = PLoc.getIncludeLoc();
1642 while (NextLoc.isValid()) {
1643 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1644 if (PLoc.isInvalid())
1645 break;
1646
1647 NextLoc = PLoc.getIncludeLoc();
1648 }
1649 }
1650
1651 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1652 SmallString<128> FN;
1653 if (PLoc.isValid()) {
1654 FN += PLoc.getFilename();
1655 Lexer::Stringify(FN);
Yaron Keren09fb7c62015-03-10 07:33:23 +00001656 OS << '"' << FN << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001657 }
1658 Tok.setKind(tok::string_literal);
1659 } else if (II == Ident__DATE__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001660 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001661 if (!DATELoc.isValid())
1662 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1663 Tok.setKind(tok::string_literal);
1664 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1665 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1666 Tok.getLocation(),
1667 Tok.getLength()));
1668 return;
1669 } else if (II == Ident__TIME__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001670 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001671 if (!TIMELoc.isValid())
1672 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1673 Tok.setKind(tok::string_literal);
1674 Tok.setLength(strlen("\"hh:mm:ss\""));
1675 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1676 Tok.getLocation(),
1677 Tok.getLength()));
1678 return;
1679 } else if (II == Ident__INCLUDE_LEVEL__) {
1680 // Compute the presumed include depth of this token. This can be affected
1681 // by GNU line markers.
1682 unsigned Depth = 0;
1683
1684 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1685 if (PLoc.isValid()) {
1686 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1687 for (; PLoc.isValid(); ++Depth)
1688 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1689 }
1690
1691 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1692 OS << Depth;
1693 Tok.setKind(tok::numeric_constant);
1694 } else if (II == Ident__TIMESTAMP__) {
Alp Toker4f43e552014-06-10 06:08:51 +00001695 Diag(Tok.getLocation(), diag::warn_pp_date_time);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001696 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1697 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1698
1699 // Get the file that we are lexing out of. If we're currently lexing from
1700 // a macro, dig into the include stack.
Craig Topperd2d442c2014-05-17 23:10:59 +00001701 const FileEntry *CurFile = nullptr;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001702 PreprocessorLexer *TheLexer = getCurrentFileLexer();
1703
1704 if (TheLexer)
1705 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1706
1707 const char *Result;
1708 if (CurFile) {
1709 time_t TT = CurFile->getModificationTime();
1710 struct tm *TM = localtime(&TT);
1711 Result = asctime(TM);
1712 } else {
1713 Result = "??? ??? ?? ??:??:?? ????\n";
1714 }
1715 // Surround the string with " and strip the trailing newline.
Alp Toker4f43e552014-06-10 06:08:51 +00001716 OS << '"' << StringRef(Result).drop_back() << '"';
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001717 Tok.setKind(tok::string_literal);
1718 } else if (II == Ident__COUNTER__) {
1719 // __COUNTER__ expands to a simple numeric value.
1720 OS << CounterValue++;
1721 Tok.setKind(tok::numeric_constant);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001722 } else if (II == Ident__has_feature) {
1723 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1724 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1725 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1726 diag::err_feature_check_malformed);
1727 return II && HasFeature(*this, II->getName());
1728 });
1729 } else if (II == Ident__has_extension) {
1730 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1731 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1732 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1733 diag::err_feature_check_malformed);
1734 return II && HasExtension(*this, II->getName());
1735 });
1736 } else if (II == Ident__has_builtin) {
1737 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1738 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1739 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1740 diag::err_feature_check_malformed);
1741 if (!II)
1742 return false;
1743 else if (II->getBuiltinID() != 0)
1744 return true;
1745 else {
1746 const LangOptions &LangOpts = getLangOpts();
1747 return llvm::StringSwitch<bool>(II->getName())
1748 .Case("__make_integer_seq", LangOpts.CPlusPlus)
Eric Fiselier6ad68552016-07-01 01:24:09 +00001749 .Case("__type_pack_element", LangOpts.CPlusPlus)
Alex Lorenz53b4b182017-04-12 11:03:25 +00001750 .Case("__builtin_available", true)
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001751 .Default(false);
Aaron Ballmana0344c52014-11-14 13:44:02 +00001752 }
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001753 });
1754 } else if (II == Ident__is_identifier) {
1755 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1756 [](Token &Tok, bool &HasLexedNextToken) -> int {
1757 return Tok.is(tok::identifier);
1758 });
1759 } else if (II == Ident__has_attribute) {
1760 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1761 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1762 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1763 diag::err_feature_check_malformed);
1764 return II ? hasAttribute(AttrSyntax::GNU, nullptr, II,
1765 getTargetInfo(), getLangOpts()) : 0;
1766 });
1767 } else if (II == Ident__has_declspec) {
1768 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1769 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1770 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1771 diag::err_feature_check_malformed);
1772 return II ? hasAttribute(AttrSyntax::Declspec, nullptr, II,
1773 getTargetInfo(), getLangOpts()) : 0;
1774 });
1775 } else if (II == Ident__has_cpp_attribute) {
1776 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1777 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1778 IdentifierInfo *ScopeII = nullptr;
1779 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1780 diag::err_feature_check_malformed);
1781 if (!II)
1782 return false;
1783
1784 // It is possible to receive a scope token. Read the "::", if it is
1785 // available, and the subsequent identifier.
David Majnemerd6163622014-12-15 09:03:58 +00001786 LexUnexpandedToken(Tok);
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001787 if (Tok.isNot(tok::coloncolon))
1788 HasLexedNextToken = true;
1789 else {
1790 ScopeII = II;
1791 LexUnexpandedToken(Tok);
1792 II = ExpectFeatureIdentifierInfo(Tok, *this,
1793 diag::err_feature_check_malformed);
1794 }
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001795
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001796 return II ? hasAttribute(AttrSyntax::CXX, ScopeII, II,
1797 getTargetInfo(), getLangOpts()) : 0;
1798 });
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001799 } else if (II == Ident__has_include ||
1800 II == Ident__has_include_next) {
1801 // The argument to these two builtins should be a parenthesized
1802 // file name string literal using angle brackets (<>) or
1803 // double-quotes ("").
1804 bool Value;
1805 if (II == Ident__has_include)
1806 Value = EvaluateHasInclude(Tok, II, *this);
1807 else
1808 Value = EvaluateHasIncludeNext(Tok, II, *this);
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001809
1810 if (Tok.isNot(tok::r_paren))
1811 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001812 OS << (int)Value;
Benjamin Kramer18ff02d2015-03-29 15:33:29 +00001813 Tok.setKind(tok::numeric_constant);
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001814 } else if (II == Ident__has_warning) {
1815 // The argument should be a parenthesized string literal.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001816 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1817 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1818 std::string WarningName;
1819 SourceLocation StrStartLoc = Tok.getLocation();
Andy Gibbs58905d22012-11-17 19:15:38 +00001820
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001821 HasLexedNextToken = Tok.is(tok::string_literal);
1822 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1823 /*MacroExpansion=*/false))
1824 return false;
Andy Gibbs58905d22012-11-17 19:15:38 +00001825
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001826 // FIXME: Should we accept "-R..." flags here, or should that be
1827 // handled by a separate __has_remark?
1828 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1829 WarningName[1] != 'W') {
1830 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1831 return false;
1832 }
Andy Gibbs58905d22012-11-17 19:15:38 +00001833
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001834 // Finally, check if the warning flags maps to a diagnostic group.
1835 // We construct a SmallVector here to talk to getDiagnosticIDs().
1836 // Although we don't use the result, this isn't a hot path, and not
1837 // worth special casing.
1838 SmallVector<diag::kind, 10> Diags;
1839 return !getDiagnostics().getDiagnosticIDs()->
1840 getDiagnosticsInGroup(diag::Flavor::WarningOrError,
1841 WarningName.substr(2), Diags);
1842 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001843 } else if (II == Ident__building_module) {
1844 // The argument to this builtin should be an identifier. The
1845 // builtin evaluates to 1 when that identifier names the module we are
1846 // currently building.
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001847 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this,
1848 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1849 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1850 diag::err_expected_id_building_module);
Richard Smithbbcc9f02016-08-26 00:14:38 +00001851 return getLangOpts().isCompilingModule() && II &&
Andy Gibbs50b6cef2016-04-05 08:36:47 +00001852 (II->getName() == getLangOpts().CurrentModule);
1853 });
Douglas Gregorc83de302012-09-25 15:44:52 +00001854 } else if (II == Ident__MODULE__) {
1855 // The current module as an identifier.
1856 OS << getLangOpts().CurrentModule;
1857 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1858 Tok.setIdentifierInfo(ModuleII);
1859 Tok.setKind(ModuleII->getTokenID());
Richard Smithae385082014-03-15 00:06:08 +00001860 } else if (II == Ident__identifier) {
1861 SourceLocation Loc = Tok.getLocation();
1862
1863 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1864 // if the parens are missing.
1865 LexNonComment(Tok);
1866 if (Tok.isNot(tok::l_paren)) {
1867 // No '(', use end of last token.
1868 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
1869 << II << tok::l_paren;
1870 // If the next token isn't valid as our argument, we can't recover.
1871 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1872 Tok.setKind(tok::identifier);
1873 return;
1874 }
1875
1876 SourceLocation LParenLoc = Tok.getLocation();
1877 LexNonComment(Tok);
1878
1879 if (!Tok.isAnnotation() && Tok.getIdentifierInfo())
1880 Tok.setKind(tok::identifier);
1881 else {
1882 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
1883 << Tok.getKind();
1884 // Don't walk past anything that's not a real token.
Daniel Marjamakie59f8d72015-06-18 10:59:26 +00001885 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
Richard Smithae385082014-03-15 00:06:08 +00001886 return;
1887 }
1888
1889 // Discard the ')', preserving 'Tok' as our result.
1890 Token RParen;
1891 LexNonComment(RParen);
1892 if (RParen.isNot(tok::r_paren)) {
1893 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
1894 << Tok.getKind() << tok::r_paren;
1895 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1896 }
1897 return;
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001898 } else {
1899 llvm_unreachable("Unknown identifier!");
1900 }
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +00001901 CreateString(OS.str(), Tok, Tok.getLocation(), Tok.getLocation());
Joao Matosc0d4c1b2012-08-31 21:34:27 +00001902}
1903
1904void Preprocessor::markMacroAsUsed(MacroInfo *MI) {
1905 // If the 'used' status changed, and the macro requires 'unused' warning,
1906 // remove its SourceLocation from the warn-for-unused-macro locations.
1907 if (MI->isWarnIfUnused() && !MI->isUsed())
1908 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
1909 MI->setIsUsed(true);
1910}