Bug Summary

File:clang/include/clang/Basic/Diagnostic.h
Warning:line 1183, column 5
Use of memory after it is freed

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ParsePragma.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Parse -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Parse -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp

1//===--- ParsePragma.cpp - Language specific pragma parsing ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the language specific #pragma handlers.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/Basic/PragmaKinds.h"
15#include "clang/Basic/TargetInfo.h"
16#include "clang/Lex/Preprocessor.h"
17#include "clang/Lex/Token.h"
18#include "clang/Parse/LoopHint.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Parse/Parser.h"
21#include "clang/Parse/RAIIObjectsForParser.h"
22#include "clang/Sema/Scope.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/StringSwitch.h"
25using namespace clang;
26
27namespace {
28
29struct PragmaAlignHandler : public PragmaHandler {
30 explicit PragmaAlignHandler() : PragmaHandler("align") {}
31 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
32 Token &FirstToken) override;
33};
34
35struct PragmaGCCVisibilityHandler : public PragmaHandler {
36 explicit PragmaGCCVisibilityHandler() : PragmaHandler("visibility") {}
37 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
38 Token &FirstToken) override;
39};
40
41struct PragmaOptionsHandler : public PragmaHandler {
42 explicit PragmaOptionsHandler() : PragmaHandler("options") {}
43 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
44 Token &FirstToken) override;
45};
46
47struct PragmaPackHandler : public PragmaHandler {
48 explicit PragmaPackHandler() : PragmaHandler("pack") {}
49 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
50 Token &FirstToken) override;
51};
52
53struct PragmaClangSectionHandler : public PragmaHandler {
54 explicit PragmaClangSectionHandler(Sema &S)
55 : PragmaHandler("section"), Actions(S) {}
56 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
57 Token &FirstToken) override;
58
59private:
60 Sema &Actions;
61};
62
63struct PragmaMSStructHandler : public PragmaHandler {
64 explicit PragmaMSStructHandler() : PragmaHandler("ms_struct") {}
65 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
66 Token &FirstToken) override;
67};
68
69struct PragmaUnusedHandler : public PragmaHandler {
70 PragmaUnusedHandler() : PragmaHandler("unused") {}
71 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
72 Token &FirstToken) override;
73};
74
75struct PragmaWeakHandler : public PragmaHandler {
76 explicit PragmaWeakHandler() : PragmaHandler("weak") {}
77 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
78 Token &FirstToken) override;
79};
80
81struct PragmaRedefineExtnameHandler : public PragmaHandler {
82 explicit PragmaRedefineExtnameHandler() : PragmaHandler("redefine_extname") {}
83 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
84 Token &FirstToken) override;
85};
86
87struct PragmaOpenCLExtensionHandler : public PragmaHandler {
88 PragmaOpenCLExtensionHandler() : PragmaHandler("EXTENSION") {}
89 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
90 Token &FirstToken) override;
91};
92
93
94struct PragmaFPContractHandler : public PragmaHandler {
95 PragmaFPContractHandler() : PragmaHandler("FP_CONTRACT") {}
96 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
97 Token &FirstToken) override;
98};
99
100// Pragma STDC implementations.
101
102/// PragmaSTDC_FENV_ACCESSHandler - "\#pragma STDC FENV_ACCESS ...".
103struct PragmaSTDC_FENV_ACCESSHandler : public PragmaHandler {
104 PragmaSTDC_FENV_ACCESSHandler() : PragmaHandler("FENV_ACCESS") {}
105
106 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
107 Token &Tok) override {
108 Token PragmaName = Tok;
109 if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
110 PP.Diag(Tok.getLocation(), diag::warn_pragma_fp_ignored)
111 << PragmaName.getIdentifierInfo()->getName();
112 return;
113 }
114 tok::OnOffSwitch OOS;
115 if (PP.LexOnOffSwitch(OOS))
116 return;
117
118 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
119 1);
120 Toks[0].startToken();
121 Toks[0].setKind(tok::annot_pragma_fenv_access);
122 Toks[0].setLocation(Tok.getLocation());
123 Toks[0].setAnnotationEndLoc(Tok.getLocation());
124 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
125 static_cast<uintptr_t>(OOS)));
126 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
127 /*IsReinject=*/false);
128 }
129};
130
131/// PragmaSTDC_CX_LIMITED_RANGEHandler - "\#pragma STDC CX_LIMITED_RANGE ...".
132struct PragmaSTDC_CX_LIMITED_RANGEHandler : public PragmaHandler {
133 PragmaSTDC_CX_LIMITED_RANGEHandler() : PragmaHandler("CX_LIMITED_RANGE") {}
134
135 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
136 Token &Tok) override {
137 tok::OnOffSwitch OOS;
138 PP.LexOnOffSwitch(OOS);
139 }
140};
141
142/// Handler for "\#pragma STDC FENV_ROUND ...".
143struct PragmaSTDC_FENV_ROUNDHandler : public PragmaHandler {
144 PragmaSTDC_FENV_ROUNDHandler() : PragmaHandler("FENV_ROUND") {}
145
146 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
147 Token &Tok) override;
148};
149
150/// PragmaSTDC_UnknownHandler - "\#pragma STDC ...".
151struct PragmaSTDC_UnknownHandler : public PragmaHandler {
152 PragmaSTDC_UnknownHandler() = default;
153
154 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
155 Token &UnknownTok) override {
156 // C99 6.10.6p2, unknown forms are not allowed.
157 PP.Diag(UnknownTok, diag::ext_stdc_pragma_ignored);
158 }
159};
160
161struct PragmaFPHandler : public PragmaHandler {
162 PragmaFPHandler() : PragmaHandler("fp") {}
163 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
164 Token &FirstToken) override;
165};
166
167struct PragmaNoOpenMPHandler : public PragmaHandler {
168 PragmaNoOpenMPHandler() : PragmaHandler("omp") { }
169 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
170 Token &FirstToken) override;
171};
172
173struct PragmaOpenMPHandler : public PragmaHandler {
174 PragmaOpenMPHandler() : PragmaHandler("omp") { }
175 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
176 Token &FirstToken) override;
177};
178
179/// PragmaCommentHandler - "\#pragma comment ...".
180struct PragmaCommentHandler : public PragmaHandler {
181 PragmaCommentHandler(Sema &Actions)
182 : PragmaHandler("comment"), Actions(Actions) {}
183 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
184 Token &FirstToken) override;
185
186private:
187 Sema &Actions;
188};
189
190struct PragmaDetectMismatchHandler : public PragmaHandler {
191 PragmaDetectMismatchHandler(Sema &Actions)
192 : PragmaHandler("detect_mismatch"), Actions(Actions) {}
193 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
194 Token &FirstToken) override;
195
196private:
197 Sema &Actions;
198};
199
200struct PragmaFloatControlHandler : public PragmaHandler {
201 PragmaFloatControlHandler(Sema &Actions)
202 : PragmaHandler("float_control") {}
203 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
204 Token &FirstToken) override;
205};
206
207struct PragmaMSPointersToMembers : public PragmaHandler {
208 explicit PragmaMSPointersToMembers() : PragmaHandler("pointers_to_members") {}
209 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
210 Token &FirstToken) override;
211};
212
213struct PragmaMSVtorDisp : public PragmaHandler {
214 explicit PragmaMSVtorDisp() : PragmaHandler("vtordisp") {}
215 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
216 Token &FirstToken) override;
217};
218
219struct PragmaMSPragma : public PragmaHandler {
220 explicit PragmaMSPragma(const char *name) : PragmaHandler(name) {}
221 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
222 Token &FirstToken) override;
223};
224
225/// PragmaOptimizeHandler - "\#pragma clang optimize on/off".
226struct PragmaOptimizeHandler : public PragmaHandler {
227 PragmaOptimizeHandler(Sema &S)
228 : PragmaHandler("optimize"), Actions(S) {}
229 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
230 Token &FirstToken) override;
231
232private:
233 Sema &Actions;
234};
235
236struct PragmaLoopHintHandler : public PragmaHandler {
237 PragmaLoopHintHandler() : PragmaHandler("loop") {}
238 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
239 Token &FirstToken) override;
240};
241
242struct PragmaUnrollHintHandler : public PragmaHandler {
243 PragmaUnrollHintHandler(const char *name) : PragmaHandler(name) {}
244 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
245 Token &FirstToken) override;
246};
247
248struct PragmaMSRuntimeChecksHandler : public EmptyPragmaHandler {
249 PragmaMSRuntimeChecksHandler() : EmptyPragmaHandler("runtime_checks") {}
250};
251
252struct PragmaMSIntrinsicHandler : public PragmaHandler {
253 PragmaMSIntrinsicHandler() : PragmaHandler("intrinsic") {}
254 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
255 Token &FirstToken) override;
256};
257
258struct PragmaMSOptimizeHandler : public PragmaHandler {
259 PragmaMSOptimizeHandler() : PragmaHandler("optimize") {}
260 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
261 Token &FirstToken) override;
262};
263
264struct PragmaForceCUDAHostDeviceHandler : public PragmaHandler {
265 PragmaForceCUDAHostDeviceHandler(Sema &Actions)
266 : PragmaHandler("force_cuda_host_device"), Actions(Actions) {}
267 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
268 Token &FirstToken) override;
269
270private:
271 Sema &Actions;
272};
273
274/// PragmaAttributeHandler - "\#pragma clang attribute ...".
275struct PragmaAttributeHandler : public PragmaHandler {
276 PragmaAttributeHandler(AttributeFactory &AttrFactory)
277 : PragmaHandler("attribute"), AttributesForPragmaAttribute(AttrFactory) {}
278 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
279 Token &FirstToken) override;
280
281 /// A pool of attributes that were parsed in \#pragma clang attribute.
282 ParsedAttributes AttributesForPragmaAttribute;
283};
284
285struct PragmaMaxTokensHereHandler : public PragmaHandler {
286 PragmaMaxTokensHereHandler() : PragmaHandler("max_tokens_here") {}
287 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
288 Token &FirstToken) override;
289};
290
291struct PragmaMaxTokensTotalHandler : public PragmaHandler {
292 PragmaMaxTokensTotalHandler() : PragmaHandler("max_tokens_total") {}
293 void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
294 Token &FirstToken) override;
295};
296
297void markAsReinjectedForRelexing(llvm::MutableArrayRef<clang::Token> Toks) {
298 for (auto &T : Toks)
299 T.setFlag(clang::Token::IsReinjected);
300}
301} // end namespace
302
303void Parser::initializePragmaHandlers() {
304 AlignHandler = std::make_unique<PragmaAlignHandler>();
305 PP.AddPragmaHandler(AlignHandler.get());
306
307 GCCVisibilityHandler = std::make_unique<PragmaGCCVisibilityHandler>();
308 PP.AddPragmaHandler("GCC", GCCVisibilityHandler.get());
309
310 OptionsHandler = std::make_unique<PragmaOptionsHandler>();
311 PP.AddPragmaHandler(OptionsHandler.get());
312
313 PackHandler = std::make_unique<PragmaPackHandler>();
314 PP.AddPragmaHandler(PackHandler.get());
315
316 MSStructHandler = std::make_unique<PragmaMSStructHandler>();
317 PP.AddPragmaHandler(MSStructHandler.get());
318
319 UnusedHandler = std::make_unique<PragmaUnusedHandler>();
320 PP.AddPragmaHandler(UnusedHandler.get());
321
322 WeakHandler = std::make_unique<PragmaWeakHandler>();
323 PP.AddPragmaHandler(WeakHandler.get());
324
325 RedefineExtnameHandler = std::make_unique<PragmaRedefineExtnameHandler>();
326 PP.AddPragmaHandler(RedefineExtnameHandler.get());
327
328 FPContractHandler = std::make_unique<PragmaFPContractHandler>();
329 PP.AddPragmaHandler("STDC", FPContractHandler.get());
330
331 STDCFenvAccessHandler = std::make_unique<PragmaSTDC_FENV_ACCESSHandler>();
332 PP.AddPragmaHandler("STDC", STDCFenvAccessHandler.get());
333
334 STDCFenvRoundHandler = std::make_unique<PragmaSTDC_FENV_ROUNDHandler>();
335 PP.AddPragmaHandler("STDC", STDCFenvRoundHandler.get());
336
337 STDCCXLIMITHandler = std::make_unique<PragmaSTDC_CX_LIMITED_RANGEHandler>();
338 PP.AddPragmaHandler("STDC", STDCCXLIMITHandler.get());
339
340 STDCUnknownHandler = std::make_unique<PragmaSTDC_UnknownHandler>();
341 PP.AddPragmaHandler("STDC", STDCUnknownHandler.get());
342
343 PCSectionHandler = std::make_unique<PragmaClangSectionHandler>(Actions);
344 PP.AddPragmaHandler("clang", PCSectionHandler.get());
345
346 if (getLangOpts().OpenCL) {
347 OpenCLExtensionHandler = std::make_unique<PragmaOpenCLExtensionHandler>();
348 PP.AddPragmaHandler("OPENCL", OpenCLExtensionHandler.get());
349
350 PP.AddPragmaHandler("OPENCL", FPContractHandler.get());
351 }
352 if (getLangOpts().OpenMP)
353 OpenMPHandler = std::make_unique<PragmaOpenMPHandler>();
354 else
355 OpenMPHandler = std::make_unique<PragmaNoOpenMPHandler>();
356 PP.AddPragmaHandler(OpenMPHandler.get());
357
358 if (getLangOpts().MicrosoftExt ||
359 getTargetInfo().getTriple().isOSBinFormatELF()) {
360 MSCommentHandler = std::make_unique<PragmaCommentHandler>(Actions);
361 PP.AddPragmaHandler(MSCommentHandler.get());
362 }
363
364 FloatControlHandler = std::make_unique<PragmaFloatControlHandler>(Actions);
365 PP.AddPragmaHandler(FloatControlHandler.get());
366 if (getLangOpts().MicrosoftExt) {
367 MSDetectMismatchHandler =
368 std::make_unique<PragmaDetectMismatchHandler>(Actions);
369 PP.AddPragmaHandler(MSDetectMismatchHandler.get());
370 MSPointersToMembers = std::make_unique<PragmaMSPointersToMembers>();
371 PP.AddPragmaHandler(MSPointersToMembers.get());
372 MSVtorDisp = std::make_unique<PragmaMSVtorDisp>();
373 PP.AddPragmaHandler(MSVtorDisp.get());
374 MSInitSeg = std::make_unique<PragmaMSPragma>("init_seg");
375 PP.AddPragmaHandler(MSInitSeg.get());
376 MSDataSeg = std::make_unique<PragmaMSPragma>("data_seg");
377 PP.AddPragmaHandler(MSDataSeg.get());
378 MSBSSSeg = std::make_unique<PragmaMSPragma>("bss_seg");
379 PP.AddPragmaHandler(MSBSSSeg.get());
380 MSConstSeg = std::make_unique<PragmaMSPragma>("const_seg");
381 PP.AddPragmaHandler(MSConstSeg.get());
382 MSCodeSeg = std::make_unique<PragmaMSPragma>("code_seg");
383 PP.AddPragmaHandler(MSCodeSeg.get());
384 MSSection = std::make_unique<PragmaMSPragma>("section");
385 PP.AddPragmaHandler(MSSection.get());
386 MSRuntimeChecks = std::make_unique<PragmaMSRuntimeChecksHandler>();
387 PP.AddPragmaHandler(MSRuntimeChecks.get());
388 MSIntrinsic = std::make_unique<PragmaMSIntrinsicHandler>();
389 PP.AddPragmaHandler(MSIntrinsic.get());
390 MSOptimize = std::make_unique<PragmaMSOptimizeHandler>();
391 PP.AddPragmaHandler(MSOptimize.get());
392 }
393
394 if (getLangOpts().CUDA) {
395 CUDAForceHostDeviceHandler =
396 std::make_unique<PragmaForceCUDAHostDeviceHandler>(Actions);
397 PP.AddPragmaHandler("clang", CUDAForceHostDeviceHandler.get());
398 }
399
400 OptimizeHandler = std::make_unique<PragmaOptimizeHandler>(Actions);
401 PP.AddPragmaHandler("clang", OptimizeHandler.get());
402
403 LoopHintHandler = std::make_unique<PragmaLoopHintHandler>();
404 PP.AddPragmaHandler("clang", LoopHintHandler.get());
405
406 UnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("unroll");
407 PP.AddPragmaHandler(UnrollHintHandler.get());
408 PP.AddPragmaHandler("GCC", UnrollHintHandler.get());
409
410 NoUnrollHintHandler = std::make_unique<PragmaUnrollHintHandler>("nounroll");
411 PP.AddPragmaHandler(NoUnrollHintHandler.get());
412 PP.AddPragmaHandler("GCC", NoUnrollHintHandler.get());
413
414 UnrollAndJamHintHandler =
415 std::make_unique<PragmaUnrollHintHandler>("unroll_and_jam");
416 PP.AddPragmaHandler(UnrollAndJamHintHandler.get());
417
418 NoUnrollAndJamHintHandler =
419 std::make_unique<PragmaUnrollHintHandler>("nounroll_and_jam");
420 PP.AddPragmaHandler(NoUnrollAndJamHintHandler.get());
421
422 FPHandler = std::make_unique<PragmaFPHandler>();
423 PP.AddPragmaHandler("clang", FPHandler.get());
424
425 AttributePragmaHandler =
426 std::make_unique<PragmaAttributeHandler>(AttrFactory);
427 PP.AddPragmaHandler("clang", AttributePragmaHandler.get());
428
429 MaxTokensHerePragmaHandler = std::make_unique<PragmaMaxTokensHereHandler>();
430 PP.AddPragmaHandler("clang", MaxTokensHerePragmaHandler.get());
431
432 MaxTokensTotalPragmaHandler = std::make_unique<PragmaMaxTokensTotalHandler>();
433 PP.AddPragmaHandler("clang", MaxTokensTotalPragmaHandler.get());
434}
435
436void Parser::resetPragmaHandlers() {
437 // Remove the pragma handlers we installed.
438 PP.RemovePragmaHandler(AlignHandler.get());
439 AlignHandler.reset();
440 PP.RemovePragmaHandler("GCC", GCCVisibilityHandler.get());
441 GCCVisibilityHandler.reset();
442 PP.RemovePragmaHandler(OptionsHandler.get());
443 OptionsHandler.reset();
444 PP.RemovePragmaHandler(PackHandler.get());
445 PackHandler.reset();
446 PP.RemovePragmaHandler(MSStructHandler.get());
447 MSStructHandler.reset();
448 PP.RemovePragmaHandler(UnusedHandler.get());
449 UnusedHandler.reset();
450 PP.RemovePragmaHandler(WeakHandler.get());
451 WeakHandler.reset();
452 PP.RemovePragmaHandler(RedefineExtnameHandler.get());
453 RedefineExtnameHandler.reset();
454
455 if (getLangOpts().OpenCL) {
456 PP.RemovePragmaHandler("OPENCL", OpenCLExtensionHandler.get());
457 OpenCLExtensionHandler.reset();
458 PP.RemovePragmaHandler("OPENCL", FPContractHandler.get());
459 }
460 PP.RemovePragmaHandler(OpenMPHandler.get());
461 OpenMPHandler.reset();
462
463 if (getLangOpts().MicrosoftExt ||
464 getTargetInfo().getTriple().isOSBinFormatELF()) {
465 PP.RemovePragmaHandler(MSCommentHandler.get());
466 MSCommentHandler.reset();
467 }
468
469 PP.RemovePragmaHandler("clang", PCSectionHandler.get());
470 PCSectionHandler.reset();
471
472 PP.RemovePragmaHandler(FloatControlHandler.get());
473 FloatControlHandler.reset();
474 if (getLangOpts().MicrosoftExt) {
475 PP.RemovePragmaHandler(MSDetectMismatchHandler.get());
476 MSDetectMismatchHandler.reset();
477 PP.RemovePragmaHandler(MSPointersToMembers.get());
478 MSPointersToMembers.reset();
479 PP.RemovePragmaHandler(MSVtorDisp.get());
480 MSVtorDisp.reset();
481 PP.RemovePragmaHandler(MSInitSeg.get());
482 MSInitSeg.reset();
483 PP.RemovePragmaHandler(MSDataSeg.get());
484 MSDataSeg.reset();
485 PP.RemovePragmaHandler(MSBSSSeg.get());
486 MSBSSSeg.reset();
487 PP.RemovePragmaHandler(MSConstSeg.get());
488 MSConstSeg.reset();
489 PP.RemovePragmaHandler(MSCodeSeg.get());
490 MSCodeSeg.reset();
491 PP.RemovePragmaHandler(MSSection.get());
492 MSSection.reset();
493 PP.RemovePragmaHandler(MSRuntimeChecks.get());
494 MSRuntimeChecks.reset();
495 PP.RemovePragmaHandler(MSIntrinsic.get());
496 MSIntrinsic.reset();
497 PP.RemovePragmaHandler(MSOptimize.get());
498 MSOptimize.reset();
499 }
500
501 if (getLangOpts().CUDA) {
502 PP.RemovePragmaHandler("clang", CUDAForceHostDeviceHandler.get());
503 CUDAForceHostDeviceHandler.reset();
504 }
505
506 PP.RemovePragmaHandler("STDC", FPContractHandler.get());
507 FPContractHandler.reset();
508
509 PP.RemovePragmaHandler("STDC", STDCFenvAccessHandler.get());
510 STDCFenvAccessHandler.reset();
511
512 PP.RemovePragmaHandler("STDC", STDCFenvRoundHandler.get());
513 STDCFenvRoundHandler.reset();
514
515 PP.RemovePragmaHandler("STDC", STDCCXLIMITHandler.get());
516 STDCCXLIMITHandler.reset();
517
518 PP.RemovePragmaHandler("STDC", STDCUnknownHandler.get());
519 STDCUnknownHandler.reset();
520
521 PP.RemovePragmaHandler("clang", OptimizeHandler.get());
522 OptimizeHandler.reset();
523
524 PP.RemovePragmaHandler("clang", LoopHintHandler.get());
525 LoopHintHandler.reset();
526
527 PP.RemovePragmaHandler(UnrollHintHandler.get());
528 PP.RemovePragmaHandler("GCC", UnrollHintHandler.get());
529 UnrollHintHandler.reset();
530
531 PP.RemovePragmaHandler(NoUnrollHintHandler.get());
532 PP.RemovePragmaHandler("GCC", NoUnrollHintHandler.get());
533 NoUnrollHintHandler.reset();
534
535 PP.RemovePragmaHandler(UnrollAndJamHintHandler.get());
536 UnrollAndJamHintHandler.reset();
537
538 PP.RemovePragmaHandler(NoUnrollAndJamHintHandler.get());
539 NoUnrollAndJamHintHandler.reset();
540
541 PP.RemovePragmaHandler("clang", FPHandler.get());
542 FPHandler.reset();
543
544 PP.RemovePragmaHandler("clang", AttributePragmaHandler.get());
545 AttributePragmaHandler.reset();
546
547 PP.RemovePragmaHandler("clang", MaxTokensHerePragmaHandler.get());
548 MaxTokensHerePragmaHandler.reset();
549
550 PP.RemovePragmaHandler("clang", MaxTokensTotalPragmaHandler.get());
551 MaxTokensTotalPragmaHandler.reset();
552}
553
554/// Handle the annotation token produced for #pragma unused(...)
555///
556/// Each annot_pragma_unused is followed by the argument token so e.g.
557/// "#pragma unused(x,y)" becomes:
558/// annot_pragma_unused 'x' annot_pragma_unused 'y'
559void Parser::HandlePragmaUnused() {
560 assert(Tok.is(tok::annot_pragma_unused))(static_cast <bool> (Tok.is(tok::annot_pragma_unused)) ?
void (0) : __assert_fail ("Tok.is(tok::annot_pragma_unused)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 560, __extension__ __PRETTY_FUNCTION__))
;
561 SourceLocation UnusedLoc = ConsumeAnnotationToken();
562 Actions.ActOnPragmaUnused(Tok, getCurScope(), UnusedLoc);
563 ConsumeToken(); // The argument token.
564}
565
566void Parser::HandlePragmaVisibility() {
567 assert(Tok.is(tok::annot_pragma_vis))(static_cast <bool> (Tok.is(tok::annot_pragma_vis)) ? void
(0) : __assert_fail ("Tok.is(tok::annot_pragma_vis)", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 567, __extension__ __PRETTY_FUNCTION__))
;
568 const IdentifierInfo *VisType =
569 static_cast<IdentifierInfo *>(Tok.getAnnotationValue());
570 SourceLocation VisLoc = ConsumeAnnotationToken();
571 Actions.ActOnPragmaVisibility(VisType, VisLoc);
572}
573
574namespace {
575struct PragmaPackInfo {
576 Sema::PragmaMsStackAction Action;
577 StringRef SlotLabel;
578 Token Alignment;
579};
580} // end anonymous namespace
581
582void Parser::HandlePragmaPack() {
583 assert(Tok.is(tok::annot_pragma_pack))(static_cast <bool> (Tok.is(tok::annot_pragma_pack)) ? void
(0) : __assert_fail ("Tok.is(tok::annot_pragma_pack)", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 583, __extension__ __PRETTY_FUNCTION__))
;
584 PragmaPackInfo *Info =
585 static_cast<PragmaPackInfo *>(Tok.getAnnotationValue());
586 SourceLocation PragmaLoc = Tok.getLocation();
587 ExprResult Alignment;
588 if (Info->Alignment.is(tok::numeric_constant)) {
589 Alignment = Actions.ActOnNumericConstant(Info->Alignment);
590 if (Alignment.isInvalid()) {
591 ConsumeAnnotationToken();
592 return;
593 }
594 }
595 Actions.ActOnPragmaPack(PragmaLoc, Info->Action, Info->SlotLabel,
596 Alignment.get());
597 // Consume the token after processing the pragma to enable pragma-specific
598 // #include warnings.
599 ConsumeAnnotationToken();
600}
601
602void Parser::HandlePragmaMSStruct() {
603 assert(Tok.is(tok::annot_pragma_msstruct))(static_cast <bool> (Tok.is(tok::annot_pragma_msstruct)
) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_msstruct)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 603, __extension__ __PRETTY_FUNCTION__))
;
604 PragmaMSStructKind Kind = static_cast<PragmaMSStructKind>(
605 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
606 Actions.ActOnPragmaMSStruct(Kind);
607 ConsumeAnnotationToken();
608}
609
610void Parser::HandlePragmaAlign() {
611 assert(Tok.is(tok::annot_pragma_align))(static_cast <bool> (Tok.is(tok::annot_pragma_align)) ?
void (0) : __assert_fail ("Tok.is(tok::annot_pragma_align)",
"/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 611, __extension__ __PRETTY_FUNCTION__))
;
612 Sema::PragmaOptionsAlignKind Kind =
613 static_cast<Sema::PragmaOptionsAlignKind>(
614 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
615 Actions.ActOnPragmaOptionsAlign(Kind, Tok.getLocation());
616 // Consume the token after processing the pragma to enable pragma-specific
617 // #include warnings.
618 ConsumeAnnotationToken();
619}
620
621void Parser::HandlePragmaDump() {
622 assert(Tok.is(tok::annot_pragma_dump))(static_cast <bool> (Tok.is(tok::annot_pragma_dump)) ? void
(0) : __assert_fail ("Tok.is(tok::annot_pragma_dump)", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 622, __extension__ __PRETTY_FUNCTION__))
;
623 IdentifierInfo *II =
624 reinterpret_cast<IdentifierInfo *>(Tok.getAnnotationValue());
625 Actions.ActOnPragmaDump(getCurScope(), Tok.getLocation(), II);
626 ConsumeAnnotationToken();
627}
628
629void Parser::HandlePragmaWeak() {
630 assert(Tok.is(tok::annot_pragma_weak))(static_cast <bool> (Tok.is(tok::annot_pragma_weak)) ? void
(0) : __assert_fail ("Tok.is(tok::annot_pragma_weak)", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 630, __extension__ __PRETTY_FUNCTION__))
;
631 SourceLocation PragmaLoc = ConsumeAnnotationToken();
632 Actions.ActOnPragmaWeakID(Tok.getIdentifierInfo(), PragmaLoc,
633 Tok.getLocation());
634 ConsumeToken(); // The weak name.
635}
636
637void Parser::HandlePragmaWeakAlias() {
638 assert(Tok.is(tok::annot_pragma_weakalias))(static_cast <bool> (Tok.is(tok::annot_pragma_weakalias
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_weakalias)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 638, __extension__ __PRETTY_FUNCTION__))
;
639 SourceLocation PragmaLoc = ConsumeAnnotationToken();
640 IdentifierInfo *WeakName = Tok.getIdentifierInfo();
641 SourceLocation WeakNameLoc = Tok.getLocation();
642 ConsumeToken();
643 IdentifierInfo *AliasName = Tok.getIdentifierInfo();
644 SourceLocation AliasNameLoc = Tok.getLocation();
645 ConsumeToken();
646 Actions.ActOnPragmaWeakAlias(WeakName, AliasName, PragmaLoc,
647 WeakNameLoc, AliasNameLoc);
648
649}
650
651void Parser::HandlePragmaRedefineExtname() {
652 assert(Tok.is(tok::annot_pragma_redefine_extname))(static_cast <bool> (Tok.is(tok::annot_pragma_redefine_extname
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_redefine_extname)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 652, __extension__ __PRETTY_FUNCTION__))
;
653 SourceLocation RedefLoc = ConsumeAnnotationToken();
654 IdentifierInfo *RedefName = Tok.getIdentifierInfo();
655 SourceLocation RedefNameLoc = Tok.getLocation();
656 ConsumeToken();
657 IdentifierInfo *AliasName = Tok.getIdentifierInfo();
658 SourceLocation AliasNameLoc = Tok.getLocation();
659 ConsumeToken();
660 Actions.ActOnPragmaRedefineExtname(RedefName, AliasName, RedefLoc,
661 RedefNameLoc, AliasNameLoc);
662}
663
664void Parser::HandlePragmaFPContract() {
665 assert(Tok.is(tok::annot_pragma_fp_contract))(static_cast <bool> (Tok.is(tok::annot_pragma_fp_contract
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_fp_contract)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 665, __extension__ __PRETTY_FUNCTION__))
;
666 tok::OnOffSwitch OOS =
667 static_cast<tok::OnOffSwitch>(
668 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
669
670 LangOptions::FPModeKind FPC;
671 switch (OOS) {
672 case tok::OOS_ON:
673 FPC = LangOptions::FPM_On;
674 break;
675 case tok::OOS_OFF:
676 FPC = LangOptions::FPM_Off;
677 break;
678 case tok::OOS_DEFAULT:
679 FPC = getLangOpts().getDefaultFPContractMode();
680 break;
681 }
682
683 SourceLocation PragmaLoc = ConsumeAnnotationToken();
684 Actions.ActOnPragmaFPContract(PragmaLoc, FPC);
685}
686
687void Parser::HandlePragmaFloatControl() {
688 assert(Tok.is(tok::annot_pragma_float_control))(static_cast <bool> (Tok.is(tok::annot_pragma_float_control
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_float_control)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 688, __extension__ __PRETTY_FUNCTION__))
;
689
690 // The value that is held on the PragmaFloatControlStack encodes
691 // the PragmaFloatControl kind and the MSStackAction kind
692 // into a single 32-bit word. The MsStackAction is the high 16 bits
693 // and the FloatControl is the lower 16 bits. Use shift and bit-and
694 // to decode the parts.
695 uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
696 Sema::PragmaMsStackAction Action =
697 static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
698 PragmaFloatControlKind Kind = PragmaFloatControlKind(Value & 0xFFFF);
699 SourceLocation PragmaLoc = ConsumeAnnotationToken();
700 Actions.ActOnPragmaFloatControl(PragmaLoc, Action, Kind);
701}
702
703void Parser::HandlePragmaFEnvAccess() {
704 assert(Tok.is(tok::annot_pragma_fenv_access))(static_cast <bool> (Tok.is(tok::annot_pragma_fenv_access
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_fenv_access)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 704, __extension__ __PRETTY_FUNCTION__))
;
705 tok::OnOffSwitch OOS =
706 static_cast<tok::OnOffSwitch>(
707 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
708
709 bool IsEnabled;
710 switch (OOS) {
711 case tok::OOS_ON:
712 IsEnabled = true;
713 break;
714 case tok::OOS_OFF:
715 IsEnabled = false;
716 break;
717 case tok::OOS_DEFAULT: // FIXME: Add this cli option when it makes sense.
718 IsEnabled = false;
719 break;
720 }
721
722 SourceLocation PragmaLoc = ConsumeAnnotationToken();
723 Actions.ActOnPragmaFEnvAccess(PragmaLoc, IsEnabled);
724}
725
726void Parser::HandlePragmaFEnvRound() {
727 assert(Tok.is(tok::annot_pragma_fenv_round))(static_cast <bool> (Tok.is(tok::annot_pragma_fenv_round
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_fenv_round)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 727, __extension__ __PRETTY_FUNCTION__))
;
728 auto RM = static_cast<llvm::RoundingMode>(
729 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
730
731 SourceLocation PragmaLoc = ConsumeAnnotationToken();
732 Actions.setRoundingMode(PragmaLoc, RM);
733}
734
735StmtResult Parser::HandlePragmaCaptured()
736{
737 assert(Tok.is(tok::annot_pragma_captured))(static_cast <bool> (Tok.is(tok::annot_pragma_captured)
) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_captured)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 737, __extension__ __PRETTY_FUNCTION__))
;
738 ConsumeAnnotationToken();
739
740 if (Tok.isNot(tok::l_brace)) {
741 PP.Diag(Tok, diag::err_expected) << tok::l_brace;
742 return StmtError();
743 }
744
745 SourceLocation Loc = Tok.getLocation();
746
747 ParseScope CapturedRegionScope(this, Scope::FnScope | Scope::DeclScope |
748 Scope::CompoundStmtScope);
749 Actions.ActOnCapturedRegionStart(Loc, getCurScope(), CR_Default,
750 /*NumParams=*/1);
751
752 StmtResult R = ParseCompoundStatement();
753 CapturedRegionScope.Exit();
754
755 if (R.isInvalid()) {
756 Actions.ActOnCapturedRegionError();
757 return StmtError();
758 }
759
760 return Actions.ActOnCapturedRegionEnd(R.get());
761}
762
763namespace {
764 enum OpenCLExtState : char {
765 Disable, Enable, Begin, End
766 };
767 typedef std::pair<const IdentifierInfo *, OpenCLExtState> OpenCLExtData;
768}
769
770void Parser::HandlePragmaOpenCLExtension() {
771 assert(Tok.is(tok::annot_pragma_opencl_extension))(static_cast <bool> (Tok.is(tok::annot_pragma_opencl_extension
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_opencl_extension)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 771, __extension__ __PRETTY_FUNCTION__))
;
772 OpenCLExtData *Data = static_cast<OpenCLExtData*>(Tok.getAnnotationValue());
773 auto State = Data->second;
774 auto Ident = Data->first;
775 SourceLocation NameLoc = Tok.getLocation();
776 ConsumeAnnotationToken();
777
778 auto &Opt = Actions.getOpenCLOptions();
779 auto Name = Ident->getName();
780 // OpenCL 1.1 9.1: "The all variant sets the behavior for all extensions,
781 // overriding all previously issued extension directives, but only if the
782 // behavior is set to disable."
783 if (Name == "all") {
784 if (State == Disable)
785 Opt.disableAll();
786 else
787 PP.Diag(NameLoc, diag::warn_pragma_expected_predicate) << 1;
788 } else if (State == Begin) {
789 if (!Opt.isKnown(Name) || !Opt.isSupported(Name, getLangOpts())) {
790 Opt.support(Name);
791 // FIXME: Default behavior of the extension pragma is not defined.
792 // Therefore, it should never be added by default.
793 Opt.acceptsPragma(Name);
794 }
795 Actions.setCurrentOpenCLExtension(Name);
796 } else if (State == End) {
797 if (Name != Actions.getCurrentOpenCLExtension())
798 PP.Diag(NameLoc, diag::warn_pragma_begin_end_mismatch);
799 Actions.setCurrentOpenCLExtension("");
800 } else if (!Opt.isKnown(Name) || !Opt.isWithPragma(Name))
801 PP.Diag(NameLoc, diag::warn_pragma_unknown_extension) << Ident;
802 else if (Opt.isSupportedExtension(Name, getLangOpts()))
803 Opt.enable(Name, State == Enable);
804 else if (Opt.isSupportedCoreOrOptionalCore(Name, getLangOpts()))
805 PP.Diag(NameLoc, diag::warn_pragma_extension_is_core) << Ident;
806 else
807 PP.Diag(NameLoc, diag::warn_pragma_unsupported_extension) << Ident;
808}
809
810void Parser::HandlePragmaMSPointersToMembers() {
811 assert(Tok.is(tok::annot_pragma_ms_pointers_to_members))(static_cast <bool> (Tok.is(tok::annot_pragma_ms_pointers_to_members
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_ms_pointers_to_members)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 811, __extension__ __PRETTY_FUNCTION__))
;
812 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod =
813 static_cast<LangOptions::PragmaMSPointersToMembersKind>(
814 reinterpret_cast<uintptr_t>(Tok.getAnnotationValue()));
815 SourceLocation PragmaLoc = ConsumeAnnotationToken();
816 Actions.ActOnPragmaMSPointersToMembers(RepresentationMethod, PragmaLoc);
817}
818
819void Parser::HandlePragmaMSVtorDisp() {
820 assert(Tok.is(tok::annot_pragma_ms_vtordisp))(static_cast <bool> (Tok.is(tok::annot_pragma_ms_vtordisp
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_ms_vtordisp)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 820, __extension__ __PRETTY_FUNCTION__))
;
821 uintptr_t Value = reinterpret_cast<uintptr_t>(Tok.getAnnotationValue());
822 Sema::PragmaMsStackAction Action =
823 static_cast<Sema::PragmaMsStackAction>((Value >> 16) & 0xFFFF);
824 MSVtorDispMode Mode = MSVtorDispMode(Value & 0xFFFF);
825 SourceLocation PragmaLoc = ConsumeAnnotationToken();
826 Actions.ActOnPragmaMSVtorDisp(Action, PragmaLoc, Mode);
827}
828
829void Parser::HandlePragmaMSPragma() {
830 assert(Tok.is(tok::annot_pragma_ms_pragma))(static_cast <bool> (Tok.is(tok::annot_pragma_ms_pragma
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_ms_pragma)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 830, __extension__ __PRETTY_FUNCTION__))
;
831 // Grab the tokens out of the annotation and enter them into the stream.
832 auto TheTokens =
833 (std::pair<std::unique_ptr<Token[]>, size_t> *)Tok.getAnnotationValue();
834 PP.EnterTokenStream(std::move(TheTokens->first), TheTokens->second, true,
835 /*IsReinject=*/true);
836 SourceLocation PragmaLocation = ConsumeAnnotationToken();
837 assert(Tok.isAnyIdentifier())(static_cast <bool> (Tok.isAnyIdentifier()) ? void (0) :
__assert_fail ("Tok.isAnyIdentifier()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 837, __extension__ __PRETTY_FUNCTION__))
;
838 StringRef PragmaName = Tok.getIdentifierInfo()->getName();
839 PP.Lex(Tok); // pragma kind
840
841 // Figure out which #pragma we're dealing with. The switch has no default
842 // because lex shouldn't emit the annotation token for unrecognized pragmas.
843 typedef bool (Parser::*PragmaHandler)(StringRef, SourceLocation);
844 PragmaHandler Handler = llvm::StringSwitch<PragmaHandler>(PragmaName)
845 .Case("data_seg", &Parser::HandlePragmaMSSegment)
846 .Case("bss_seg", &Parser::HandlePragmaMSSegment)
847 .Case("const_seg", &Parser::HandlePragmaMSSegment)
848 .Case("code_seg", &Parser::HandlePragmaMSSegment)
849 .Case("section", &Parser::HandlePragmaMSSection)
850 .Case("init_seg", &Parser::HandlePragmaMSInitSeg);
851
852 if (!(this->*Handler)(PragmaName, PragmaLocation)) {
853 // Pragma handling failed, and has been diagnosed. Slurp up the tokens
854 // until eof (really end of line) to prevent follow-on errors.
855 while (Tok.isNot(tok::eof))
856 PP.Lex(Tok);
857 PP.Lex(Tok);
858 }
859}
860
861bool Parser::HandlePragmaMSSection(StringRef PragmaName,
862 SourceLocation PragmaLocation) {
863 if (Tok.isNot(tok::l_paren)) {
864 PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
865 return false;
866 }
867 PP.Lex(Tok); // (
868 // Parsing code for pragma section
869 if (Tok.isNot(tok::string_literal)) {
870 PP.Diag(PragmaLocation, diag::warn_pragma_expected_section_name)
871 << PragmaName;
872 return false;
873 }
874 ExprResult StringResult = ParseStringLiteralExpression();
875 if (StringResult.isInvalid())
876 return false; // Already diagnosed.
877 StringLiteral *SegmentName = cast<StringLiteral>(StringResult.get());
878 if (SegmentName->getCharByteWidth() != 1) {
879 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
880 << PragmaName;
881 return false;
882 }
883 int SectionFlags = ASTContext::PSF_Read;
884 bool SectionFlagsAreDefault = true;
885 while (Tok.is(tok::comma)) {
886 PP.Lex(Tok); // ,
887 // Ignore "long" and "short".
888 // They are undocumented, but widely used, section attributes which appear
889 // to do nothing.
890 if (Tok.is(tok::kw_long) || Tok.is(tok::kw_short)) {
891 PP.Lex(Tok); // long/short
892 continue;
893 }
894
895 if (!Tok.isAnyIdentifier()) {
896 PP.Diag(PragmaLocation, diag::warn_pragma_expected_action_or_r_paren)
897 << PragmaName;
898 return false;
899 }
900 ASTContext::PragmaSectionFlag Flag =
901 llvm::StringSwitch<ASTContext::PragmaSectionFlag>(
902 Tok.getIdentifierInfo()->getName())
903 .Case("read", ASTContext::PSF_Read)
904 .Case("write", ASTContext::PSF_Write)
905 .Case("execute", ASTContext::PSF_Execute)
906 .Case("shared", ASTContext::PSF_Invalid)
907 .Case("nopage", ASTContext::PSF_Invalid)
908 .Case("nocache", ASTContext::PSF_Invalid)
909 .Case("discard", ASTContext::PSF_Invalid)
910 .Case("remove", ASTContext::PSF_Invalid)
911 .Default(ASTContext::PSF_None);
912 if (Flag == ASTContext::PSF_None || Flag == ASTContext::PSF_Invalid) {
913 PP.Diag(PragmaLocation, Flag == ASTContext::PSF_None
914 ? diag::warn_pragma_invalid_specific_action
915 : diag::warn_pragma_unsupported_action)
916 << PragmaName << Tok.getIdentifierInfo()->getName();
917 return false;
918 }
919 SectionFlags |= Flag;
920 SectionFlagsAreDefault = false;
921 PP.Lex(Tok); // Identifier
922 }
923 // If no section attributes are specified, the section will be marked as
924 // read/write.
925 if (SectionFlagsAreDefault)
926 SectionFlags |= ASTContext::PSF_Write;
927 if (Tok.isNot(tok::r_paren)) {
928 PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
929 return false;
930 }
931 PP.Lex(Tok); // )
932 if (Tok.isNot(tok::eof)) {
933 PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
934 << PragmaName;
935 return false;
936 }
937 PP.Lex(Tok); // eof
938 Actions.ActOnPragmaMSSection(PragmaLocation, SectionFlags, SegmentName);
939 return true;
940}
941
942bool Parser::HandlePragmaMSSegment(StringRef PragmaName,
943 SourceLocation PragmaLocation) {
944 if (Tok.isNot(tok::l_paren)) {
945 PP.Diag(PragmaLocation, diag::warn_pragma_expected_lparen) << PragmaName;
946 return false;
947 }
948 PP.Lex(Tok); // (
949 Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
950 StringRef SlotLabel;
951 if (Tok.isAnyIdentifier()) {
952 StringRef PushPop = Tok.getIdentifierInfo()->getName();
953 if (PushPop == "push")
954 Action = Sema::PSK_Push;
955 else if (PushPop == "pop")
956 Action = Sema::PSK_Pop;
957 else {
958 PP.Diag(PragmaLocation,
959 diag::warn_pragma_expected_section_push_pop_or_name)
960 << PragmaName;
961 return false;
962 }
963 if (Action != Sema::PSK_Reset) {
964 PP.Lex(Tok); // push | pop
965 if (Tok.is(tok::comma)) {
966 PP.Lex(Tok); // ,
967 // If we've got a comma, we either need a label or a string.
968 if (Tok.isAnyIdentifier()) {
969 SlotLabel = Tok.getIdentifierInfo()->getName();
970 PP.Lex(Tok); // identifier
971 if (Tok.is(tok::comma))
972 PP.Lex(Tok);
973 else if (Tok.isNot(tok::r_paren)) {
974 PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc)
975 << PragmaName;
976 return false;
977 }
978 }
979 } else if (Tok.isNot(tok::r_paren)) {
980 PP.Diag(PragmaLocation, diag::warn_pragma_expected_punc) << PragmaName;
981 return false;
982 }
983 }
984 }
985 // Grab the string literal for our section name.
986 StringLiteral *SegmentName = nullptr;
987 if (Tok.isNot(tok::r_paren)) {
988 if (Tok.isNot(tok::string_literal)) {
989 unsigned DiagID = Action != Sema::PSK_Reset ? !SlotLabel.empty() ?
990 diag::warn_pragma_expected_section_name :
991 diag::warn_pragma_expected_section_label_or_name :
992 diag::warn_pragma_expected_section_push_pop_or_name;
993 PP.Diag(PragmaLocation, DiagID) << PragmaName;
994 return false;
995 }
996 ExprResult StringResult = ParseStringLiteralExpression();
997 if (StringResult.isInvalid())
998 return false; // Already diagnosed.
999 SegmentName = cast<StringLiteral>(StringResult.get());
1000 if (SegmentName->getCharByteWidth() != 1) {
1001 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
1002 << PragmaName;
1003 return false;
1004 }
1005 // Setting section "" has no effect
1006 if (SegmentName->getLength())
1007 Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
1008 }
1009 if (Tok.isNot(tok::r_paren)) {
1010 PP.Diag(PragmaLocation, diag::warn_pragma_expected_rparen) << PragmaName;
1011 return false;
1012 }
1013 PP.Lex(Tok); // )
1014 if (Tok.isNot(tok::eof)) {
1015 PP.Diag(PragmaLocation, diag::warn_pragma_extra_tokens_at_eol)
1016 << PragmaName;
1017 return false;
1018 }
1019 PP.Lex(Tok); // eof
1020 Actions.ActOnPragmaMSSeg(PragmaLocation, Action, SlotLabel,
1021 SegmentName, PragmaName);
1022 return true;
1023}
1024
1025// #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} )
1026bool Parser::HandlePragmaMSInitSeg(StringRef PragmaName,
1027 SourceLocation PragmaLocation) {
1028 if (getTargetInfo().getTriple().getEnvironment() != llvm::Triple::MSVC) {
1029 PP.Diag(PragmaLocation, diag::warn_pragma_init_seg_unsupported_target);
1030 return false;
1031 }
1032
1033 if (ExpectAndConsume(tok::l_paren, diag::warn_pragma_expected_lparen,
1034 PragmaName))
1035 return false;
1036
1037 // Parse either the known section names or the string section name.
1038 StringLiteral *SegmentName = nullptr;
1039 if (Tok.isAnyIdentifier()) {
1040 auto *II = Tok.getIdentifierInfo();
1041 StringRef Section = llvm::StringSwitch<StringRef>(II->getName())
1042 .Case("compiler", "\".CRT$XCC\"")
1043 .Case("lib", "\".CRT$XCL\"")
1044 .Case("user", "\".CRT$XCU\"")
1045 .Default("");
1046
1047 if (!Section.empty()) {
1048 // Pretend the user wrote the appropriate string literal here.
1049 Token Toks[1];
1050 Toks[0].startToken();
1051 Toks[0].setKind(tok::string_literal);
1052 Toks[0].setLocation(Tok.getLocation());
1053 Toks[0].setLiteralData(Section.data());
1054 Toks[0].setLength(Section.size());
1055 SegmentName =
1056 cast<StringLiteral>(Actions.ActOnStringLiteral(Toks, nullptr).get());
1057 PP.Lex(Tok);
1058 }
1059 } else if (Tok.is(tok::string_literal)) {
1060 ExprResult StringResult = ParseStringLiteralExpression();
1061 if (StringResult.isInvalid())
1062 return false;
1063 SegmentName = cast<StringLiteral>(StringResult.get());
1064 if (SegmentName->getCharByteWidth() != 1) {
1065 PP.Diag(PragmaLocation, diag::warn_pragma_expected_non_wide_string)
1066 << PragmaName;
1067 return false;
1068 }
1069 // FIXME: Add support for the '[, func-name]' part of the pragma.
1070 }
1071
1072 if (!SegmentName) {
1073 PP.Diag(PragmaLocation, diag::warn_pragma_expected_init_seg) << PragmaName;
1074 return false;
1075 }
1076
1077 if (ExpectAndConsume(tok::r_paren, diag::warn_pragma_expected_rparen,
1078 PragmaName) ||
1079 ExpectAndConsume(tok::eof, diag::warn_pragma_extra_tokens_at_eol,
1080 PragmaName))
1081 return false;
1082
1083 Actions.ActOnPragmaMSInitSeg(PragmaLocation, SegmentName);
1084 return true;
1085}
1086
1087namespace {
1088struct PragmaLoopHintInfo {
1089 Token PragmaName;
1090 Token Option;
1091 ArrayRef<Token> Toks;
1092};
1093} // end anonymous namespace
1094
1095static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
1096 StringRef Str = PragmaName.getIdentifierInfo()->getName();
1097 std::string ClangLoopStr = (llvm::Twine("clang loop ") + Str).str();
1098 return std::string(llvm::StringSwitch<StringRef>(Str)
1099 .Case("loop", ClangLoopStr)
1100 .Case("unroll_and_jam", Str)
1101 .Case("unroll", Str)
1102 .Default(""));
1103}
1104
1105bool Parser::HandlePragmaLoopHint(LoopHint &Hint) {
1106 assert(Tok.is(tok::annot_pragma_loop_hint))(static_cast <bool> (Tok.is(tok::annot_pragma_loop_hint
)) ? void (0) : __assert_fail ("Tok.is(tok::annot_pragma_loop_hint)"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1106, __extension__ __PRETTY_FUNCTION__))
;
1107 PragmaLoopHintInfo *Info =
1108 static_cast<PragmaLoopHintInfo *>(Tok.getAnnotationValue());
1109
1110 IdentifierInfo *PragmaNameInfo = Info->PragmaName.getIdentifierInfo();
1111 Hint.PragmaNameLoc = IdentifierLoc::create(
1112 Actions.Context, Info->PragmaName.getLocation(), PragmaNameInfo);
1113
1114 // It is possible that the loop hint has no option identifier, such as
1115 // #pragma unroll(4).
1116 IdentifierInfo *OptionInfo = Info->Option.is(tok::identifier)
1117 ? Info->Option.getIdentifierInfo()
1118 : nullptr;
1119 Hint.OptionLoc = IdentifierLoc::create(
1120 Actions.Context, Info->Option.getLocation(), OptionInfo);
1121
1122 llvm::ArrayRef<Token> Toks = Info->Toks;
1123
1124 // Return a valid hint if pragma unroll or nounroll were specified
1125 // without an argument.
1126 auto IsLoopHint = llvm::StringSwitch<bool>(PragmaNameInfo->getName())
1127 .Cases("unroll", "nounroll", "unroll_and_jam",
1128 "nounroll_and_jam", true)
1129 .Default(false);
1130
1131 if (Toks.empty() && IsLoopHint) {
1132 ConsumeAnnotationToken();
1133 Hint.Range = Info->PragmaName.getLocation();
1134 return true;
1135 }
1136
1137 // The constant expression is always followed by an eof token, which increases
1138 // the TokSize by 1.
1139 assert(!Toks.empty() &&(static_cast <bool> (!Toks.empty() && "PragmaLoopHintInfo::Toks must contain at least one token."
) ? void (0) : __assert_fail ("!Toks.empty() && \"PragmaLoopHintInfo::Toks must contain at least one token.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1140, __extension__ __PRETTY_FUNCTION__))
1140 "PragmaLoopHintInfo::Toks must contain at least one token.")(static_cast <bool> (!Toks.empty() && "PragmaLoopHintInfo::Toks must contain at least one token."
) ? void (0) : __assert_fail ("!Toks.empty() && \"PragmaLoopHintInfo::Toks must contain at least one token.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1140, __extension__ __PRETTY_FUNCTION__))
;
1141
1142 // If no option is specified the argument is assumed to be a constant expr.
1143 bool OptionUnroll = false;
1144 bool OptionUnrollAndJam = false;
1145 bool OptionDistribute = false;
1146 bool OptionPipelineDisabled = false;
1147 bool StateOption = false;
1148 if (OptionInfo) { // Pragma Unroll does not specify an option.
1149 OptionUnroll = OptionInfo->isStr("unroll");
1150 OptionUnrollAndJam = OptionInfo->isStr("unroll_and_jam");
1151 OptionDistribute = OptionInfo->isStr("distribute");
1152 OptionPipelineDisabled = OptionInfo->isStr("pipeline");
1153 StateOption = llvm::StringSwitch<bool>(OptionInfo->getName())
1154 .Case("vectorize", true)
1155 .Case("interleave", true)
1156 .Case("vectorize_predicate", true)
1157 .Default(false) ||
1158 OptionUnroll || OptionUnrollAndJam || OptionDistribute ||
1159 OptionPipelineDisabled;
1160 }
1161
1162 bool AssumeSafetyArg = !OptionUnroll && !OptionUnrollAndJam &&
1163 !OptionDistribute && !OptionPipelineDisabled;
1164 // Verify loop hint has an argument.
1165 if (Toks[0].is(tok::eof)) {
1166 ConsumeAnnotationToken();
1167 Diag(Toks[0].getLocation(), diag::err_pragma_loop_missing_argument)
1168 << /*StateArgument=*/StateOption
1169 << /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
1170 << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
1171 return false;
1172 }
1173
1174 // Validate the argument.
1175 if (StateOption) {
1176 ConsumeAnnotationToken();
1177 SourceLocation StateLoc = Toks[0].getLocation();
1178 IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
1179
1180 bool Valid = StateInfo &&
1181 llvm::StringSwitch<bool>(StateInfo->getName())
1182 .Case("disable", true)
1183 .Case("enable", !OptionPipelineDisabled)
1184 .Case("full", OptionUnroll || OptionUnrollAndJam)
1185 .Case("assume_safety", AssumeSafetyArg)
1186 .Default(false);
1187 if (!Valid) {
1188 if (OptionPipelineDisabled) {
1189 Diag(Toks[0].getLocation(), diag::err_pragma_pipeline_invalid_keyword);
1190 } else {
1191 Diag(Toks[0].getLocation(), diag::err_pragma_invalid_keyword)
1192 << /*FullKeyword=*/(OptionUnroll || OptionUnrollAndJam)
1193 << /*AssumeSafetyKeyword=*/AssumeSafetyArg;
1194 }
1195 return false;
1196 }
1197 if (Toks.size() > 2)
1198 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1199 << PragmaLoopHintString(Info->PragmaName, Info->Option);
1200 Hint.StateLoc = IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
1201 } else if (OptionInfo && OptionInfo->getName() == "vectorize_width") {
1202 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
1203 /*IsReinject=*/false);
1204 ConsumeAnnotationToken();
1205
1206 SourceLocation StateLoc = Toks[0].getLocation();
1207 IdentifierInfo *StateInfo = Toks[0].getIdentifierInfo();
1208 StringRef IsScalableStr = StateInfo ? StateInfo->getName() : "";
1209
1210 // Look for vectorize_width(fixed|scalable)
1211 if (IsScalableStr == "scalable" || IsScalableStr == "fixed") {
1212 PP.Lex(Tok); // Identifier
1213
1214 if (Toks.size() > 2) {
1215 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1216 << PragmaLoopHintString(Info->PragmaName, Info->Option);
1217 while (Tok.isNot(tok::eof))
1218 ConsumeAnyToken();
1219 }
1220
1221 Hint.StateLoc =
1222 IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
1223
1224 ConsumeToken(); // Consume the constant expression eof terminator.
1225 } else {
1226 // Enter constant expression including eof terminator into token stream.
1227 ExprResult R = ParseConstantExpression();
1228
1229 if (R.isInvalid() && !Tok.is(tok::comma))
1230 Diag(Toks[0].getLocation(),
1231 diag::note_pragma_loop_invalid_vectorize_option);
1232
1233 bool Arg2Error = false;
1234 if (Tok.is(tok::comma)) {
1235 PP.Lex(Tok); // ,
1236
1237 StateInfo = Tok.getIdentifierInfo();
1238 IsScalableStr = StateInfo->getName();
1239
1240 if (IsScalableStr != "scalable" && IsScalableStr != "fixed") {
1241 Diag(Tok.getLocation(),
1242 diag::err_pragma_loop_invalid_vectorize_option);
1243 Arg2Error = true;
1244 } else
1245 Hint.StateLoc =
1246 IdentifierLoc::create(Actions.Context, StateLoc, StateInfo);
1247
1248 PP.Lex(Tok); // Identifier
1249 }
1250
1251 // Tokens following an error in an ill-formed constant expression will
1252 // remain in the token stream and must be removed.
1253 if (Tok.isNot(tok::eof)) {
1254 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1255 << PragmaLoopHintString(Info->PragmaName, Info->Option);
1256 while (Tok.isNot(tok::eof))
1257 ConsumeAnyToken();
1258 }
1259
1260 ConsumeToken(); // Consume the constant expression eof terminator.
1261
1262 if (Arg2Error || R.isInvalid() ||
1263 Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
1264 return false;
1265
1266 // Argument is a constant expression with an integer type.
1267 Hint.ValueExpr = R.get();
1268 }
1269 } else {
1270 // Enter constant expression including eof terminator into token stream.
1271 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/false,
1272 /*IsReinject=*/false);
1273 ConsumeAnnotationToken();
1274 ExprResult R = ParseConstantExpression();
1275
1276 // Tokens following an error in an ill-formed constant expression will
1277 // remain in the token stream and must be removed.
1278 if (Tok.isNot(tok::eof)) {
1279 Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1280 << PragmaLoopHintString(Info->PragmaName, Info->Option);
1281 while (Tok.isNot(tok::eof))
1282 ConsumeAnyToken();
1283 }
1284
1285 ConsumeToken(); // Consume the constant expression eof terminator.
1286
1287 if (R.isInvalid() ||
1288 Actions.CheckLoopHintExpr(R.get(), Toks[0].getLocation()))
1289 return false;
1290
1291 // Argument is a constant expression with an integer type.
1292 Hint.ValueExpr = R.get();
1293 }
1294
1295 Hint.Range = SourceRange(Info->PragmaName.getLocation(),
1296 Info->Toks.back().getLocation());
1297 return true;
1298}
1299
1300namespace {
1301struct PragmaAttributeInfo {
1302 enum ActionType { Push, Pop, Attribute };
1303 ParsedAttributes &Attributes;
1304 ActionType Action;
1305 const IdentifierInfo *Namespace = nullptr;
1306 ArrayRef<Token> Tokens;
1307
1308 PragmaAttributeInfo(ParsedAttributes &Attributes) : Attributes(Attributes) {}
1309};
1310
1311#include "clang/Parse/AttrSubMatchRulesParserStringSwitches.inc"
1312
1313} // end anonymous namespace
1314
1315static StringRef getIdentifier(const Token &Tok) {
1316 if (Tok.is(tok::identifier))
1317 return Tok.getIdentifierInfo()->getName();
1318 const char *S = tok::getKeywordSpelling(Tok.getKind());
1319 if (!S)
1320 return "";
1321 return S;
1322}
1323
1324static bool isAbstractAttrMatcherRule(attr::SubjectMatchRule Rule) {
1325 using namespace attr;
1326 switch (Rule) {
1327#define ATTR_MATCH_RULE(Value, Spelling, IsAbstract) \
1328 case Value: \
1329 return IsAbstract;
1330#include "clang/Basic/AttrSubMatchRulesList.inc"
1331 }
1332 llvm_unreachable("Invalid attribute subject match rule")::llvm::llvm_unreachable_internal("Invalid attribute subject match rule"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1332)
;
1333 return false;
1334}
1335
1336static void diagnoseExpectedAttributeSubjectSubRule(
1337 Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
1338 SourceLocation SubRuleLoc) {
1339 auto Diagnostic =
1340 PRef.Diag(SubRuleLoc,
1341 diag::err_pragma_attribute_expected_subject_sub_identifier)
1342 << PrimaryRuleName;
1343 if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
1344 Diagnostic << /*SubRulesSupported=*/1 << SubRules;
1345 else
1346 Diagnostic << /*SubRulesSupported=*/0;
1347}
1348
1349static void diagnoseUnknownAttributeSubjectSubRule(
1350 Parser &PRef, attr::SubjectMatchRule PrimaryRule, StringRef PrimaryRuleName,
1351 StringRef SubRuleName, SourceLocation SubRuleLoc) {
1352
1353 auto Diagnostic =
1354 PRef.Diag(SubRuleLoc, diag::err_pragma_attribute_unknown_subject_sub_rule)
1355 << SubRuleName << PrimaryRuleName;
1356 if (const char *SubRules = validAttributeSubjectMatchSubRules(PrimaryRule))
1357 Diagnostic << /*SubRulesSupported=*/1 << SubRules;
1358 else
1359 Diagnostic << /*SubRulesSupported=*/0;
1360}
1361
1362bool Parser::ParsePragmaAttributeSubjectMatchRuleSet(
1363 attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc,
1364 SourceLocation &LastMatchRuleEndLoc) {
1365 bool IsAny = false;
1366 BalancedDelimiterTracker AnyParens(*this, tok::l_paren);
1367 if (getIdentifier(Tok) == "any") {
1368 AnyLoc = ConsumeToken();
1369 IsAny = true;
1370 if (AnyParens.expectAndConsume())
1371 return true;
1372 }
1373
1374 do {
1375 // Parse the subject matcher rule.
1376 StringRef Name = getIdentifier(Tok);
1377 if (Name.empty()) {
1378 Diag(Tok, diag::err_pragma_attribute_expected_subject_identifier);
1379 return true;
1380 }
1381 std::pair<Optional<attr::SubjectMatchRule>,
1382 Optional<attr::SubjectMatchRule> (*)(StringRef, bool)>
1383 Rule = isAttributeSubjectMatchRule(Name);
1384 if (!Rule.first) {
1385 Diag(Tok, diag::err_pragma_attribute_unknown_subject_rule) << Name;
1386 return true;
1387 }
1388 attr::SubjectMatchRule PrimaryRule = *Rule.first;
1389 SourceLocation RuleLoc = ConsumeToken();
1390
1391 BalancedDelimiterTracker Parens(*this, tok::l_paren);
1392 if (isAbstractAttrMatcherRule(PrimaryRule)) {
1393 if (Parens.expectAndConsume())
1394 return true;
1395 } else if (Parens.consumeOpen()) {
1396 if (!SubjectMatchRules
1397 .insert(
1398 std::make_pair(PrimaryRule, SourceRange(RuleLoc, RuleLoc)))
1399 .second)
1400 Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
1401 << Name
1402 << FixItHint::CreateRemoval(SourceRange(
1403 RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleLoc));
1404 LastMatchRuleEndLoc = RuleLoc;
1405 continue;
1406 }
1407
1408 // Parse the sub-rules.
1409 StringRef SubRuleName = getIdentifier(Tok);
1410 if (SubRuleName.empty()) {
1411 diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
1412 Tok.getLocation());
1413 return true;
1414 }
1415 attr::SubjectMatchRule SubRule;
1416 if (SubRuleName == "unless") {
1417 SourceLocation SubRuleLoc = ConsumeToken();
1418 BalancedDelimiterTracker Parens(*this, tok::l_paren);
1419 if (Parens.expectAndConsume())
1420 return true;
1421 SubRuleName = getIdentifier(Tok);
1422 if (SubRuleName.empty()) {
1423 diagnoseExpectedAttributeSubjectSubRule(*this, PrimaryRule, Name,
1424 SubRuleLoc);
1425 return true;
1426 }
1427 auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/true);
1428 if (!SubRuleOrNone) {
1429 std::string SubRuleUnlessName = "unless(" + SubRuleName.str() + ")";
1430 diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
1431 SubRuleUnlessName, SubRuleLoc);
1432 return true;
1433 }
1434 SubRule = *SubRuleOrNone;
1435 ConsumeToken();
1436 if (Parens.consumeClose())
1437 return true;
1438 } else {
1439 auto SubRuleOrNone = Rule.second(SubRuleName, /*IsUnless=*/false);
1440 if (!SubRuleOrNone) {
1441 diagnoseUnknownAttributeSubjectSubRule(*this, PrimaryRule, Name,
1442 SubRuleName, Tok.getLocation());
1443 return true;
1444 }
1445 SubRule = *SubRuleOrNone;
1446 ConsumeToken();
1447 }
1448 SourceLocation RuleEndLoc = Tok.getLocation();
1449 LastMatchRuleEndLoc = RuleEndLoc;
1450 if (Parens.consumeClose())
1451 return true;
1452 if (!SubjectMatchRules
1453 .insert(std::make_pair(SubRule, SourceRange(RuleLoc, RuleEndLoc)))
1454 .second) {
1455 Diag(RuleLoc, diag::err_pragma_attribute_duplicate_subject)
1456 << attr::getSubjectMatchRuleSpelling(SubRule)
1457 << FixItHint::CreateRemoval(SourceRange(
1458 RuleLoc, Tok.is(tok::comma) ? Tok.getLocation() : RuleEndLoc));
1459 continue;
1460 }
1461 } while (IsAny && TryConsumeToken(tok::comma));
1462
1463 if (IsAny)
1464 if (AnyParens.consumeClose())
1465 return true;
1466
1467 return false;
1468}
1469
1470namespace {
1471
1472/// Describes the stage at which attribute subject rule parsing was interrupted.
1473enum class MissingAttributeSubjectRulesRecoveryPoint {
1474 Comma,
1475 ApplyTo,
1476 Equals,
1477 Any,
1478 None,
1479};
1480
1481MissingAttributeSubjectRulesRecoveryPoint
1482getAttributeSubjectRulesRecoveryPointForToken(const Token &Tok) {
1483 if (const auto *II = Tok.getIdentifierInfo()) {
1484 if (II->isStr("apply_to"))
1485 return MissingAttributeSubjectRulesRecoveryPoint::ApplyTo;
1486 if (II->isStr("any"))
1487 return MissingAttributeSubjectRulesRecoveryPoint::Any;
1488 }
1489 if (Tok.is(tok::equal))
1490 return MissingAttributeSubjectRulesRecoveryPoint::Equals;
1491 return MissingAttributeSubjectRulesRecoveryPoint::None;
1492}
1493
1494/// Creates a diagnostic for the attribute subject rule parsing diagnostic that
1495/// suggests the possible attribute subject rules in a fix-it together with
1496/// any other missing tokens.
1497DiagnosticBuilder createExpectedAttributeSubjectRulesTokenDiagnostic(
1498 unsigned DiagID, ParsedAttr &Attribute,
1499 MissingAttributeSubjectRulesRecoveryPoint Point, Parser &PRef) {
1500 SourceLocation Loc = PRef.getEndOfPreviousToken();
1501 if (Loc.isInvalid())
18
Taking false branch
1502 Loc = PRef.getCurToken().getLocation();
1503 auto Diagnostic = PRef.Diag(Loc, DiagID);
1504 std::string FixIt;
1505 MissingAttributeSubjectRulesRecoveryPoint EndPoint =
1506 getAttributeSubjectRulesRecoveryPointForToken(PRef.getCurToken());
1507 if (Point
18.1
'Point' is equal to Comma
18.1
'Point' is equal to Comma
== MissingAttributeSubjectRulesRecoveryPoint::Comma)
19
Taking true branch
1508 FixIt = ", ";
1509 if (Point
19.1
'Point' is <= ApplyTo
19.1
'Point' is <= ApplyTo
<= MissingAttributeSubjectRulesRecoveryPoint::ApplyTo &&
20
Taking true branch
1510 EndPoint
19.2
'EndPoint' is > ApplyTo
19.2
'EndPoint' is > ApplyTo
> MissingAttributeSubjectRulesRecoveryPoint::ApplyTo)
1511 FixIt += "apply_to";
1512 if (Point
20.1
'Point' is <= Equals
20.1
'Point' is <= Equals
<= MissingAttributeSubjectRulesRecoveryPoint::Equals &&
21
Taking true branch
1513 EndPoint
20.2
'EndPoint' is > Equals
20.2
'EndPoint' is > Equals
> MissingAttributeSubjectRulesRecoveryPoint::Equals)
1514 FixIt += " = ";
1515 SourceRange FixItRange(Loc);
1516 if (EndPoint
21.1
'EndPoint' is equal to None
21.1
'EndPoint' is equal to None
== MissingAttributeSubjectRulesRecoveryPoint::None) {
22
Taking true branch
1517 // Gather the subject match rules that are supported by the attribute.
1518 SmallVector<std::pair<attr::SubjectMatchRule, bool>, 4> SubjectMatchRuleSet;
1519 Attribute.getMatchRules(PRef.getLangOpts(), SubjectMatchRuleSet);
1520 if (SubjectMatchRuleSet.empty()) {
23
Taking true branch
1521 // FIXME: We can emit a "fix-it" with a subject list placeholder when
1522 // placeholders will be supported by the fix-its.
1523 return Diagnostic;
24
Calling '~DiagnosticBuilder'
39
Returning from '~DiagnosticBuilder'
1524 }
1525 FixIt += "any(";
1526 bool NeedsComma = false;
1527 for (const auto &I : SubjectMatchRuleSet) {
1528 // Ensure that the missing rule is reported in the fix-it only when it's
1529 // supported in the current language mode.
1530 if (!I.second)
1531 continue;
1532 if (NeedsComma)
1533 FixIt += ", ";
1534 else
1535 NeedsComma = true;
1536 FixIt += attr::getSubjectMatchRuleSpelling(I.first);
1537 }
1538 FixIt += ")";
1539 // Check if we need to remove the range
1540 PRef.SkipUntil(tok::eof, Parser::StopBeforeMatch);
1541 FixItRange.setEnd(PRef.getCurToken().getLocation());
1542 }
1543 if (FixItRange.getBegin() == FixItRange.getEnd())
1544 Diagnostic << FixItHint::CreateInsertion(FixItRange.getBegin(), FixIt);
1545 else
1546 Diagnostic << FixItHint::CreateReplacement(
1547 CharSourceRange::getCharRange(FixItRange), FixIt);
1548 return Diagnostic;
1549}
1550
1551} // end anonymous namespace
1552
1553void Parser::HandlePragmaAttribute() {
1554 assert(Tok.is(tok::annot_pragma_attribute) &&(static_cast <bool> (Tok.is(tok::annot_pragma_attribute
) && "Expected #pragma attribute annotation token") ?
void (0) : __assert_fail ("Tok.is(tok::annot_pragma_attribute) && \"Expected #pragma attribute annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1555, __extension__ __PRETTY_FUNCTION__))
1
'?' condition is true
1555 "Expected #pragma attribute annotation token")(static_cast <bool> (Tok.is(tok::annot_pragma_attribute
) && "Expected #pragma attribute annotation token") ?
void (0) : __assert_fail ("Tok.is(tok::annot_pragma_attribute) && \"Expected #pragma attribute annotation token\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1555, __extension__ __PRETTY_FUNCTION__))
;
1556 SourceLocation PragmaLoc = Tok.getLocation();
1557 auto *Info = static_cast<PragmaAttributeInfo *>(Tok.getAnnotationValue());
1558 if (Info->Action == PragmaAttributeInfo::Pop) {
2
Assuming field 'Action' is not equal to Pop
3
Taking false branch
1559 ConsumeAnnotationToken();
1560 Actions.ActOnPragmaAttributePop(PragmaLoc, Info->Namespace);
1561 return;
1562 }
1563 // Parse the actual attribute with its arguments.
1564 assert((Info->Action == PragmaAttributeInfo::Push ||(static_cast <bool> ((Info->Action == PragmaAttributeInfo
::Push || Info->Action == PragmaAttributeInfo::Attribute) &&
"Unexpected #pragma attribute command") ? void (0) : __assert_fail
("(Info->Action == PragmaAttributeInfo::Push || Info->Action == PragmaAttributeInfo::Attribute) && \"Unexpected #pragma attribute command\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1566, __extension__ __PRETTY_FUNCTION__))
4
Assuming field 'Action' is not equal to Push
5
Assuming field 'Action' is equal to Attribute
6
'?' condition is true
1565 Info->Action == PragmaAttributeInfo::Attribute) &&(static_cast <bool> ((Info->Action == PragmaAttributeInfo
::Push || Info->Action == PragmaAttributeInfo::Attribute) &&
"Unexpected #pragma attribute command") ? void (0) : __assert_fail
("(Info->Action == PragmaAttributeInfo::Push || Info->Action == PragmaAttributeInfo::Attribute) && \"Unexpected #pragma attribute command\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1566, __extension__ __PRETTY_FUNCTION__))
1566 "Unexpected #pragma attribute command")(static_cast <bool> ((Info->Action == PragmaAttributeInfo
::Push || Info->Action == PragmaAttributeInfo::Attribute) &&
"Unexpected #pragma attribute command") ? void (0) : __assert_fail
("(Info->Action == PragmaAttributeInfo::Push || Info->Action == PragmaAttributeInfo::Attribute) && \"Unexpected #pragma attribute command\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 1566, __extension__ __PRETTY_FUNCTION__))
;
1567
1568 if (Info->Action
6.1
Field 'Action' is not equal to Push
6.1
Field 'Action' is not equal to Push
== PragmaAttributeInfo::Push && Info->Tokens.empty()) {
1569 ConsumeAnnotationToken();
1570 Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
1571 return;
1572 }
1573
1574 PP.EnterTokenStream(Info->Tokens, /*DisableMacroExpansion=*/false,
1575 /*IsReinject=*/false);
1576 ConsumeAnnotationToken();
1577
1578 ParsedAttributes &Attrs = Info->Attributes;
1579 Attrs.clearListOnly();
1580
1581 auto SkipToEnd = [this]() {
1582 SkipUntil(tok::eof, StopBeforeMatch);
1583 ConsumeToken();
1584 };
1585
1586 if (Tok.is(tok::l_square) && NextToken().is(tok::l_square)) {
1587 // Parse the CXX11 style attribute.
1588 ParseCXX11AttributeSpecifier(Attrs);
1589 } else if (Tok.is(tok::kw___attribute)) {
7
Taking false branch
1590 ConsumeToken();
1591 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after,
1592 "attribute"))
1593 return SkipToEnd();
1594 if (ExpectAndConsume(tok::l_paren, diag::err_expected_lparen_after, "("))
1595 return SkipToEnd();
1596
1597 if (Tok.isNot(tok::identifier)) {
1598 Diag(Tok, diag::err_pragma_attribute_expected_attribute_name);
1599 SkipToEnd();
1600 return;
1601 }
1602 IdentifierInfo *AttrName = Tok.getIdentifierInfo();
1603 SourceLocation AttrNameLoc = ConsumeToken();
1604
1605 if (Tok.isNot(tok::l_paren))
1606 Attrs.addNew(AttrName, AttrNameLoc, nullptr, AttrNameLoc, nullptr, 0,
1607 ParsedAttr::AS_GNU);
1608 else
1609 ParseGNUAttributeArgs(AttrName, AttrNameLoc, Attrs, /*EndLoc=*/nullptr,
1610 /*ScopeName=*/nullptr,
1611 /*ScopeLoc=*/SourceLocation(), ParsedAttr::AS_GNU,
1612 /*Declarator=*/nullptr);
1613
1614 if (ExpectAndConsume(tok::r_paren))
1615 return SkipToEnd();
1616 if (ExpectAndConsume(tok::r_paren))
1617 return SkipToEnd();
1618 } else if (Tok.is(tok::kw___declspec)) {
8
Taking true branch
1619 ParseMicrosoftDeclSpecs(Attrs);
1620 } else {
1621 Diag(Tok, diag::err_pragma_attribute_expected_attribute_syntax);
1622 if (Tok.getIdentifierInfo()) {
1623 // If we suspect that this is an attribute suggest the use of
1624 // '__attribute__'.
1625 if (ParsedAttr::getParsedKind(
1626 Tok.getIdentifierInfo(), /*ScopeName=*/nullptr,
1627 ParsedAttr::AS_GNU) != ParsedAttr::UnknownAttribute) {
1628 SourceLocation InsertStartLoc = Tok.getLocation();
1629 ConsumeToken();
1630 if (Tok.is(tok::l_paren)) {
1631 ConsumeAnyToken();
1632 SkipUntil(tok::r_paren, StopBeforeMatch);
1633 if (Tok.isNot(tok::r_paren))
1634 return SkipToEnd();
1635 }
1636 Diag(Tok, diag::note_pragma_attribute_use_attribute_kw)
1637 << FixItHint::CreateInsertion(InsertStartLoc, "__attribute__((")
1638 << FixItHint::CreateInsertion(Tok.getEndLoc(), "))");
1639 }
1640 }
1641 SkipToEnd();
1642 return;
1643 }
1644
1645 if (Attrs.empty() || Attrs.begin()->isInvalid()) {
9
Assuming the condition is false
10
Assuming the condition is false
11
Taking false branch
1646 SkipToEnd();
1647 return;
1648 }
1649
1650 // Ensure that we don't have more than one attribute.
1651 if (Attrs.size() > 1) {
12
Assuming the condition is false
13
Taking false branch
1652 SourceLocation Loc = Attrs[1].getLoc();
1653 Diag(Loc, diag::err_pragma_attribute_multiple_attributes);
1654 SkipToEnd();
1655 return;
1656 }
1657
1658 ParsedAttr &Attribute = *Attrs.begin();
1659 if (!Attribute.isSupportedByPragmaAttribute()) {
14
Assuming the condition is false
15
Taking false branch
1660 Diag(PragmaLoc, diag::err_pragma_attribute_unsupported_attribute)
1661 << Attribute;
1662 SkipToEnd();
1663 return;
1664 }
1665
1666 // Parse the subject-list.
1667 if (!TryConsumeToken(tok::comma)) {
16
Taking true branch
1668 createExpectedAttributeSubjectRulesTokenDiagnostic(
17
Calling 'createExpectedAttributeSubjectRulesTokenDiagnostic'
40
Returning; memory was released
41
Calling 'DiagnosticBuilder::operator<<'
1669 diag::err_expected, Attribute,
1670 MissingAttributeSubjectRulesRecoveryPoint::Comma, *this)
1671 << tok::comma;
1672 SkipToEnd();
1673 return;
1674 }
1675
1676 if (Tok.isNot(tok::identifier)) {
1677 createExpectedAttributeSubjectRulesTokenDiagnostic(
1678 diag::err_pragma_attribute_invalid_subject_set_specifier, Attribute,
1679 MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
1680 SkipToEnd();
1681 return;
1682 }
1683 const IdentifierInfo *II = Tok.getIdentifierInfo();
1684 if (!II->isStr("apply_to")) {
1685 createExpectedAttributeSubjectRulesTokenDiagnostic(
1686 diag::err_pragma_attribute_invalid_subject_set_specifier, Attribute,
1687 MissingAttributeSubjectRulesRecoveryPoint::ApplyTo, *this);
1688 SkipToEnd();
1689 return;
1690 }
1691 ConsumeToken();
1692
1693 if (!TryConsumeToken(tok::equal)) {
1694 createExpectedAttributeSubjectRulesTokenDiagnostic(
1695 diag::err_expected, Attribute,
1696 MissingAttributeSubjectRulesRecoveryPoint::Equals, *this)
1697 << tok::equal;
1698 SkipToEnd();
1699 return;
1700 }
1701
1702 attr::ParsedSubjectMatchRuleSet SubjectMatchRules;
1703 SourceLocation AnyLoc, LastMatchRuleEndLoc;
1704 if (ParsePragmaAttributeSubjectMatchRuleSet(SubjectMatchRules, AnyLoc,
1705 LastMatchRuleEndLoc)) {
1706 SkipToEnd();
1707 return;
1708 }
1709
1710 // Tokens following an ill-formed attribute will remain in the token stream
1711 // and must be removed.
1712 if (Tok.isNot(tok::eof)) {
1713 Diag(Tok, diag::err_pragma_attribute_extra_tokens_after_attribute);
1714 SkipToEnd();
1715 return;
1716 }
1717
1718 // Consume the eof terminator token.
1719 ConsumeToken();
1720
1721 // Handle a mixed push/attribute by desurging to a push, then an attribute.
1722 if (Info->Action == PragmaAttributeInfo::Push)
1723 Actions.ActOnPragmaAttributeEmptyPush(PragmaLoc, Info->Namespace);
1724
1725 Actions.ActOnPragmaAttributeAttribute(Attribute, PragmaLoc,
1726 std::move(SubjectMatchRules));
1727}
1728
1729// #pragma GCC visibility comes in two variants:
1730// 'push' '(' [visibility] ')'
1731// 'pop'
1732void PragmaGCCVisibilityHandler::HandlePragma(Preprocessor &PP,
1733 PragmaIntroducer Introducer,
1734 Token &VisTok) {
1735 SourceLocation VisLoc = VisTok.getLocation();
1736
1737 Token Tok;
1738 PP.LexUnexpandedToken(Tok);
1739
1740 const IdentifierInfo *PushPop = Tok.getIdentifierInfo();
1741
1742 const IdentifierInfo *VisType;
1743 if (PushPop && PushPop->isStr("pop")) {
1744 VisType = nullptr;
1745 } else if (PushPop && PushPop->isStr("push")) {
1746 PP.LexUnexpandedToken(Tok);
1747 if (Tok.isNot(tok::l_paren)) {
1748 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
1749 << "visibility";
1750 return;
1751 }
1752 PP.LexUnexpandedToken(Tok);
1753 VisType = Tok.getIdentifierInfo();
1754 if (!VisType) {
1755 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1756 << "visibility";
1757 return;
1758 }
1759 PP.LexUnexpandedToken(Tok);
1760 if (Tok.isNot(tok::r_paren)) {
1761 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
1762 << "visibility";
1763 return;
1764 }
1765 } else {
1766 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
1767 << "visibility";
1768 return;
1769 }
1770 SourceLocation EndLoc = Tok.getLocation();
1771 PP.LexUnexpandedToken(Tok);
1772 if (Tok.isNot(tok::eod)) {
1773 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1774 << "visibility";
1775 return;
1776 }
1777
1778 auto Toks = std::make_unique<Token[]>(1);
1779 Toks[0].startToken();
1780 Toks[0].setKind(tok::annot_pragma_vis);
1781 Toks[0].setLocation(VisLoc);
1782 Toks[0].setAnnotationEndLoc(EndLoc);
1783 Toks[0].setAnnotationValue(
1784 const_cast<void *>(static_cast<const void *>(VisType)));
1785 PP.EnterTokenStream(std::move(Toks), 1, /*DisableMacroExpansion=*/true,
1786 /*IsReinject=*/false);
1787}
1788
1789// #pragma pack(...) comes in the following delicious flavors:
1790// pack '(' [integer] ')'
1791// pack '(' 'show' ')'
1792// pack '(' ('push' | 'pop') [',' identifier] [, integer] ')'
1793void PragmaPackHandler::HandlePragma(Preprocessor &PP,
1794 PragmaIntroducer Introducer,
1795 Token &PackTok) {
1796 SourceLocation PackLoc = PackTok.getLocation();
1797
1798 Token Tok;
1799 PP.Lex(Tok);
1800 if (Tok.isNot(tok::l_paren)) {
1801 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "pack";
1802 return;
1803 }
1804
1805 Sema::PragmaMsStackAction Action = Sema::PSK_Reset;
1806 StringRef SlotLabel;
1807 Token Alignment;
1808 Alignment.startToken();
1809 PP.Lex(Tok);
1810 if (Tok.is(tok::numeric_constant)) {
1811 Alignment = Tok;
1812
1813 PP.Lex(Tok);
1814
1815 // In MSVC/gcc, #pragma pack(4) sets the alignment without affecting
1816 // the push/pop stack.
1817 // In Apple gcc/XL, #pragma pack(4) is equivalent to #pragma pack(push, 4)
1818 Action = (PP.getLangOpts().ApplePragmaPack || PP.getLangOpts().XLPragmaPack)
1819 ? Sema::PSK_Push_Set
1820 : Sema::PSK_Set;
1821 } else if (Tok.is(tok::identifier)) {
1822 const IdentifierInfo *II = Tok.getIdentifierInfo();
1823 if (II->isStr("show")) {
1824 Action = Sema::PSK_Show;
1825 PP.Lex(Tok);
1826 } else {
1827 if (II->isStr("push")) {
1828 Action = Sema::PSK_Push;
1829 } else if (II->isStr("pop")) {
1830 Action = Sema::PSK_Pop;
1831 } else {
1832 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action) << "pack";
1833 return;
1834 }
1835 PP.Lex(Tok);
1836
1837 if (Tok.is(tok::comma)) {
1838 PP.Lex(Tok);
1839
1840 if (Tok.is(tok::numeric_constant)) {
1841 Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
1842 Alignment = Tok;
1843
1844 PP.Lex(Tok);
1845 } else if (Tok.is(tok::identifier)) {
1846 SlotLabel = Tok.getIdentifierInfo()->getName();
1847 PP.Lex(Tok);
1848
1849 if (Tok.is(tok::comma)) {
1850 PP.Lex(Tok);
1851
1852 if (Tok.isNot(tok::numeric_constant)) {
1853 PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1854 return;
1855 }
1856
1857 Action = (Sema::PragmaMsStackAction)(Action | Sema::PSK_Set);
1858 Alignment = Tok;
1859
1860 PP.Lex(Tok);
1861 }
1862 } else {
1863 PP.Diag(Tok.getLocation(), diag::warn_pragma_pack_malformed);
1864 return;
1865 }
1866 }
1867 }
1868 } else if (PP.getLangOpts().ApplePragmaPack ||
1869 PP.getLangOpts().XLPragmaPack) {
1870 // In MSVC/gcc, #pragma pack() resets the alignment without affecting
1871 // the push/pop stack.
1872 // In Apple gcc and IBM XL, #pragma pack() is equivalent to #pragma
1873 // pack(pop).
1874 Action = Sema::PSK_Pop;
1875 }
1876
1877 if (Tok.isNot(tok::r_paren)) {
1878 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "pack";
1879 return;
1880 }
1881
1882 SourceLocation RParenLoc = Tok.getLocation();
1883 PP.Lex(Tok);
1884 if (Tok.isNot(tok::eod)) {
1885 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "pack";
1886 return;
1887 }
1888
1889 PragmaPackInfo *Info =
1890 PP.getPreprocessorAllocator().Allocate<PragmaPackInfo>(1);
1891 Info->Action = Action;
1892 Info->SlotLabel = SlotLabel;
1893 Info->Alignment = Alignment;
1894
1895 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1896 1);
1897 Toks[0].startToken();
1898 Toks[0].setKind(tok::annot_pragma_pack);
1899 Toks[0].setLocation(PackLoc);
1900 Toks[0].setAnnotationEndLoc(RParenLoc);
1901 Toks[0].setAnnotationValue(static_cast<void*>(Info));
1902 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1903 /*IsReinject=*/false);
1904}
1905
1906// #pragma ms_struct on
1907// #pragma ms_struct off
1908void PragmaMSStructHandler::HandlePragma(Preprocessor &PP,
1909 PragmaIntroducer Introducer,
1910 Token &MSStructTok) {
1911 PragmaMSStructKind Kind = PMSST_OFF;
1912
1913 Token Tok;
1914 PP.Lex(Tok);
1915 if (Tok.isNot(tok::identifier)) {
1916 PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1917 return;
1918 }
1919 SourceLocation EndLoc = Tok.getLocation();
1920 const IdentifierInfo *II = Tok.getIdentifierInfo();
1921 if (II->isStr("on")) {
1922 Kind = PMSST_ON;
1923 PP.Lex(Tok);
1924 }
1925 else if (II->isStr("off") || II->isStr("reset"))
1926 PP.Lex(Tok);
1927 else {
1928 PP.Diag(Tok.getLocation(), diag::warn_pragma_ms_struct);
1929 return;
1930 }
1931
1932 if (Tok.isNot(tok::eod)) {
1933 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
1934 << "ms_struct";
1935 return;
1936 }
1937
1938 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
1939 1);
1940 Toks[0].startToken();
1941 Toks[0].setKind(tok::annot_pragma_msstruct);
1942 Toks[0].setLocation(MSStructTok.getLocation());
1943 Toks[0].setAnnotationEndLoc(EndLoc);
1944 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
1945 static_cast<uintptr_t>(Kind)));
1946 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1947 /*IsReinject=*/false);
1948}
1949
1950// #pragma clang section bss="abc" data="" rodata="def" text="" relro=""
1951void PragmaClangSectionHandler::HandlePragma(Preprocessor &PP,
1952 PragmaIntroducer Introducer,
1953 Token &FirstToken) {
1954
1955 Token Tok;
1956 auto SecKind = Sema::PragmaClangSectionKind::PCSK_Invalid;
1957
1958 PP.Lex(Tok); // eat 'section'
1959 while (Tok.isNot(tok::eod)) {
1960 if (Tok.isNot(tok::identifier)) {
1961 PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
1962 return;
1963 }
1964
1965 const IdentifierInfo *SecType = Tok.getIdentifierInfo();
1966 if (SecType->isStr("bss"))
1967 SecKind = Sema::PragmaClangSectionKind::PCSK_BSS;
1968 else if (SecType->isStr("data"))
1969 SecKind = Sema::PragmaClangSectionKind::PCSK_Data;
1970 else if (SecType->isStr("rodata"))
1971 SecKind = Sema::PragmaClangSectionKind::PCSK_Rodata;
1972 else if (SecType->isStr("relro"))
1973 SecKind = Sema::PragmaClangSectionKind::PCSK_Relro;
1974 else if (SecType->isStr("text"))
1975 SecKind = Sema::PragmaClangSectionKind::PCSK_Text;
1976 else {
1977 PP.Diag(Tok.getLocation(), diag::err_pragma_expected_clang_section_name) << "clang section";
1978 return;
1979 }
1980
1981 SourceLocation PragmaLocation = Tok.getLocation();
1982 PP.Lex(Tok); // eat ['bss'|'data'|'rodata'|'text']
1983 if (Tok.isNot(tok::equal)) {
1984 PP.Diag(Tok.getLocation(), diag::err_pragma_clang_section_expected_equal) << SecKind;
1985 return;
1986 }
1987
1988 std::string SecName;
1989 if (!PP.LexStringLiteral(Tok, SecName, "pragma clang section", false))
1990 return;
1991
1992 Actions.ActOnPragmaClangSection(
1993 PragmaLocation,
1994 (SecName.size() ? Sema::PragmaClangSectionAction::PCSA_Set
1995 : Sema::PragmaClangSectionAction::PCSA_Clear),
1996 SecKind, SecName);
1997 }
1998}
1999
2000// #pragma 'align' '=' {'native','natural','mac68k','power','reset'}
2001// #pragma 'options 'align' '=' {'native','natural','mac68k','power','reset'}
2002// #pragma 'align' '(' {'native','natural','mac68k','power','reset'} ')'
2003static void ParseAlignPragma(Preprocessor &PP, Token &FirstTok,
2004 bool IsOptions) {
2005 Token Tok;
2006
2007 if (IsOptions) {
2008 PP.Lex(Tok);
2009 if (Tok.isNot(tok::identifier) ||
2010 !Tok.getIdentifierInfo()->isStr("align")) {
2011 PP.Diag(Tok.getLocation(), diag::warn_pragma_options_expected_align);
2012 return;
2013 }
2014 }
2015
2016 PP.Lex(Tok);
2017 if (PP.getLangOpts().XLPragmaPack) {
2018 if (Tok.isNot(tok::l_paren)) {
2019 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "align";
2020 return;
2021 }
2022 } else if (Tok.isNot(tok::equal)) {
2023 PP.Diag(Tok.getLocation(), diag::warn_pragma_align_expected_equal)
2024 << IsOptions;
2025 return;
2026 }
2027
2028 PP.Lex(Tok);
2029 if (Tok.isNot(tok::identifier)) {
2030 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2031 << (IsOptions ? "options" : "align");
2032 return;
2033 }
2034
2035 Sema::PragmaOptionsAlignKind Kind = Sema::POAK_Natural;
2036 const IdentifierInfo *II = Tok.getIdentifierInfo();
2037 if (II->isStr("native"))
2038 Kind = Sema::POAK_Native;
2039 else if (II->isStr("natural"))
2040 Kind = Sema::POAK_Natural;
2041 else if (II->isStr("packed"))
2042 Kind = Sema::POAK_Packed;
2043 else if (II->isStr("power"))
2044 Kind = Sema::POAK_Power;
2045 else if (II->isStr("mac68k"))
2046 Kind = Sema::POAK_Mac68k;
2047 else if (II->isStr("reset"))
2048 Kind = Sema::POAK_Reset;
2049 else {
2050 PP.Diag(Tok.getLocation(), diag::warn_pragma_align_invalid_option)
2051 << IsOptions;
2052 return;
2053 }
2054
2055 if (PP.getLangOpts().XLPragmaPack) {
2056 PP.Lex(Tok);
2057 if (Tok.isNot(tok::r_paren)) {
2058 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "align";
2059 return;
2060 }
2061 }
2062
2063 SourceLocation EndLoc = Tok.getLocation();
2064 PP.Lex(Tok);
2065 if (Tok.isNot(tok::eod)) {
2066 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2067 << (IsOptions ? "options" : "align");
2068 return;
2069 }
2070
2071 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2072 1);
2073 Toks[0].startToken();
2074 Toks[0].setKind(tok::annot_pragma_align);
2075 Toks[0].setLocation(FirstTok.getLocation());
2076 Toks[0].setAnnotationEndLoc(EndLoc);
2077 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
2078 static_cast<uintptr_t>(Kind)));
2079 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2080 /*IsReinject=*/false);
2081}
2082
2083void PragmaAlignHandler::HandlePragma(Preprocessor &PP,
2084 PragmaIntroducer Introducer,
2085 Token &AlignTok) {
2086 ParseAlignPragma(PP, AlignTok, /*IsOptions=*/false);
2087}
2088
2089void PragmaOptionsHandler::HandlePragma(Preprocessor &PP,
2090 PragmaIntroducer Introducer,
2091 Token &OptionsTok) {
2092 ParseAlignPragma(PP, OptionsTok, /*IsOptions=*/true);
2093}
2094
2095// #pragma unused(identifier)
2096void PragmaUnusedHandler::HandlePragma(Preprocessor &PP,
2097 PragmaIntroducer Introducer,
2098 Token &UnusedTok) {
2099 // FIXME: Should we be expanding macros here? My guess is no.
2100 SourceLocation UnusedLoc = UnusedTok.getLocation();
2101
2102 // Lex the left '('.
2103 Token Tok;
2104 PP.Lex(Tok);
2105 if (Tok.isNot(tok::l_paren)) {
2106 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "unused";
2107 return;
2108 }
2109
2110 // Lex the declaration reference(s).
2111 SmallVector<Token, 5> Identifiers;
2112 SourceLocation RParenLoc;
2113 bool LexID = true;
2114
2115 while (true) {
2116 PP.Lex(Tok);
2117
2118 if (LexID) {
2119 if (Tok.is(tok::identifier)) {
2120 Identifiers.push_back(Tok);
2121 LexID = false;
2122 continue;
2123 }
2124
2125 // Illegal token!
2126 PP.Diag(Tok.getLocation(), diag::warn_pragma_unused_expected_var);
2127 return;
2128 }
2129
2130 // We are execting a ')' or a ','.
2131 if (Tok.is(tok::comma)) {
2132 LexID = true;
2133 continue;
2134 }
2135
2136 if (Tok.is(tok::r_paren)) {
2137 RParenLoc = Tok.getLocation();
2138 break;
2139 }
2140
2141 // Illegal token!
2142 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_punc) << "unused";
2143 return;
2144 }
2145
2146 PP.Lex(Tok);
2147 if (Tok.isNot(tok::eod)) {
2148 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
2149 "unused";
2150 return;
2151 }
2152
2153 // Verify that we have a location for the right parenthesis.
2154 assert(RParenLoc.isValid() && "Valid '#pragma unused' must have ')'")(static_cast <bool> (RParenLoc.isValid() && "Valid '#pragma unused' must have ')'"
) ? void (0) : __assert_fail ("RParenLoc.isValid() && \"Valid '#pragma unused' must have ')'\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 2154, __extension__ __PRETTY_FUNCTION__))
;
2155 assert(!Identifiers.empty() && "Valid '#pragma unused' must have arguments")(static_cast <bool> (!Identifiers.empty() && "Valid '#pragma unused' must have arguments"
) ? void (0) : __assert_fail ("!Identifiers.empty() && \"Valid '#pragma unused' must have arguments\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 2155, __extension__ __PRETTY_FUNCTION__))
;
2156
2157 // For each identifier token, insert into the token stream a
2158 // annot_pragma_unused token followed by the identifier token.
2159 // This allows us to cache a "#pragma unused" that occurs inside an inline
2160 // C++ member function.
2161
2162 MutableArrayRef<Token> Toks(
2163 PP.getPreprocessorAllocator().Allocate<Token>(2 * Identifiers.size()),
2164 2 * Identifiers.size());
2165 for (unsigned i=0; i != Identifiers.size(); i++) {
2166 Token &pragmaUnusedTok = Toks[2*i], &idTok = Toks[2*i+1];
2167 pragmaUnusedTok.startToken();
2168 pragmaUnusedTok.setKind(tok::annot_pragma_unused);
2169 pragmaUnusedTok.setLocation(UnusedLoc);
2170 idTok = Identifiers[i];
2171 }
2172 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2173 /*IsReinject=*/false);
2174}
2175
2176// #pragma weak identifier
2177// #pragma weak identifier '=' identifier
2178void PragmaWeakHandler::HandlePragma(Preprocessor &PP,
2179 PragmaIntroducer Introducer,
2180 Token &WeakTok) {
2181 SourceLocation WeakLoc = WeakTok.getLocation();
2182
2183 Token Tok;
2184 PP.Lex(Tok);
2185 if (Tok.isNot(tok::identifier)) {
2186 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) << "weak";
2187 return;
2188 }
2189
2190 Token WeakName = Tok;
2191 bool HasAlias = false;
2192 Token AliasName;
2193
2194 PP.Lex(Tok);
2195 if (Tok.is(tok::equal)) {
2196 HasAlias = true;
2197 PP.Lex(Tok);
2198 if (Tok.isNot(tok::identifier)) {
2199 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2200 << "weak";
2201 return;
2202 }
2203 AliasName = Tok;
2204 PP.Lex(Tok);
2205 }
2206
2207 if (Tok.isNot(tok::eod)) {
2208 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) << "weak";
2209 return;
2210 }
2211
2212 if (HasAlias) {
2213 MutableArrayRef<Token> Toks(
2214 PP.getPreprocessorAllocator().Allocate<Token>(3), 3);
2215 Token &pragmaUnusedTok = Toks[0];
2216 pragmaUnusedTok.startToken();
2217 pragmaUnusedTok.setKind(tok::annot_pragma_weakalias);
2218 pragmaUnusedTok.setLocation(WeakLoc);
2219 pragmaUnusedTok.setAnnotationEndLoc(AliasName.getLocation());
2220 Toks[1] = WeakName;
2221 Toks[2] = AliasName;
2222 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2223 /*IsReinject=*/false);
2224 } else {
2225 MutableArrayRef<Token> Toks(
2226 PP.getPreprocessorAllocator().Allocate<Token>(2), 2);
2227 Token &pragmaUnusedTok = Toks[0];
2228 pragmaUnusedTok.startToken();
2229 pragmaUnusedTok.setKind(tok::annot_pragma_weak);
2230 pragmaUnusedTok.setLocation(WeakLoc);
2231 pragmaUnusedTok.setAnnotationEndLoc(WeakLoc);
2232 Toks[1] = WeakName;
2233 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2234 /*IsReinject=*/false);
2235 }
2236}
2237
2238// #pragma redefine_extname identifier identifier
2239void PragmaRedefineExtnameHandler::HandlePragma(Preprocessor &PP,
2240 PragmaIntroducer Introducer,
2241 Token &RedefToken) {
2242 SourceLocation RedefLoc = RedefToken.getLocation();
2243
2244 Token Tok;
2245 PP.Lex(Tok);
2246 if (Tok.isNot(tok::identifier)) {
2247 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
2248 "redefine_extname";
2249 return;
2250 }
2251
2252 Token RedefName = Tok;
2253 PP.Lex(Tok);
2254
2255 if (Tok.isNot(tok::identifier)) {
2256 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2257 << "redefine_extname";
2258 return;
2259 }
2260
2261 Token AliasName = Tok;
2262 PP.Lex(Tok);
2263
2264 if (Tok.isNot(tok::eod)) {
2265 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
2266 "redefine_extname";
2267 return;
2268 }
2269
2270 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(3),
2271 3);
2272 Token &pragmaRedefTok = Toks[0];
2273 pragmaRedefTok.startToken();
2274 pragmaRedefTok.setKind(tok::annot_pragma_redefine_extname);
2275 pragmaRedefTok.setLocation(RedefLoc);
2276 pragmaRedefTok.setAnnotationEndLoc(AliasName.getLocation());
2277 Toks[1] = RedefName;
2278 Toks[2] = AliasName;
2279 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2280 /*IsReinject=*/false);
2281}
2282
2283void PragmaFPContractHandler::HandlePragma(Preprocessor &PP,
2284 PragmaIntroducer Introducer,
2285 Token &Tok) {
2286 tok::OnOffSwitch OOS;
2287 if (PP.LexOnOffSwitch(OOS))
2288 return;
2289
2290 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2291 1);
2292 Toks[0].startToken();
2293 Toks[0].setKind(tok::annot_pragma_fp_contract);
2294 Toks[0].setLocation(Tok.getLocation());
2295 Toks[0].setAnnotationEndLoc(Tok.getLocation());
2296 Toks[0].setAnnotationValue(reinterpret_cast<void*>(
2297 static_cast<uintptr_t>(OOS)));
2298 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2299 /*IsReinject=*/false);
2300}
2301
2302void PragmaOpenCLExtensionHandler::HandlePragma(Preprocessor &PP,
2303 PragmaIntroducer Introducer,
2304 Token &Tok) {
2305 PP.LexUnexpandedToken(Tok);
2306 if (Tok.isNot(tok::identifier)) {
2307 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier) <<
2308 "OPENCL";
2309 return;
2310 }
2311 IdentifierInfo *Ext = Tok.getIdentifierInfo();
2312 SourceLocation NameLoc = Tok.getLocation();
2313
2314 PP.Lex(Tok);
2315 if (Tok.isNot(tok::colon)) {
2316 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_colon) << Ext;
2317 return;
2318 }
2319
2320 PP.Lex(Tok);
2321 if (Tok.isNot(tok::identifier)) {
2322 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate) << 0;
2323 return;
2324 }
2325 IdentifierInfo *Pred = Tok.getIdentifierInfo();
2326
2327 OpenCLExtState State;
2328 if (Pred->isStr("enable")) {
2329 State = Enable;
2330 } else if (Pred->isStr("disable")) {
2331 State = Disable;
2332 } else if (Pred->isStr("begin"))
2333 State = Begin;
2334 else if (Pred->isStr("end"))
2335 State = End;
2336 else {
2337 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_predicate)
2338 << Ext->isStr("all");
2339 return;
2340 }
2341 SourceLocation StateLoc = Tok.getLocation();
2342
2343 PP.Lex(Tok);
2344 if (Tok.isNot(tok::eod)) {
2345 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol) <<
2346 "OPENCL EXTENSION";
2347 return;
2348 }
2349
2350 auto Info = PP.getPreprocessorAllocator().Allocate<OpenCLExtData>(1);
2351 Info->first = Ext;
2352 Info->second = State;
2353 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
2354 1);
2355 Toks[0].startToken();
2356 Toks[0].setKind(tok::annot_pragma_opencl_extension);
2357 Toks[0].setLocation(NameLoc);
2358 Toks[0].setAnnotationValue(static_cast<void*>(Info));
2359 Toks[0].setAnnotationEndLoc(StateLoc);
2360 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
2361 /*IsReinject=*/false);
2362
2363 if (PP.getPPCallbacks())
2364 PP.getPPCallbacks()->PragmaOpenCLExtension(NameLoc, Ext,
2365 StateLoc, State);
2366}
2367
2368/// Handle '#pragma omp ...' when OpenMP is disabled.
2369///
2370void PragmaNoOpenMPHandler::HandlePragma(Preprocessor &PP,
2371 PragmaIntroducer Introducer,
2372 Token &FirstTok) {
2373 if (!PP.getDiagnostics().isIgnored(diag::warn_pragma_omp_ignored,
2374 FirstTok.getLocation())) {
2375 PP.Diag(FirstTok, diag::warn_pragma_omp_ignored);
2376 PP.getDiagnostics().setSeverity(diag::warn_pragma_omp_ignored,
2377 diag::Severity::Ignored, SourceLocation());
2378 }
2379 PP.DiscardUntilEndOfDirective();
2380}
2381
2382/// Handle '#pragma omp ...' when OpenMP is enabled.
2383///
2384void PragmaOpenMPHandler::HandlePragma(Preprocessor &PP,
2385 PragmaIntroducer Introducer,
2386 Token &FirstTok) {
2387 SmallVector<Token, 16> Pragma;
2388 Token Tok;
2389 Tok.startToken();
2390 Tok.setKind(tok::annot_pragma_openmp);
2391 Tok.setLocation(Introducer.Loc);
2392
2393 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) {
2394 Pragma.push_back(Tok);
2395 PP.Lex(Tok);
2396 if (Tok.is(tok::annot_pragma_openmp)) {
2397 PP.Diag(Tok, diag::err_omp_unexpected_directive) << 0;
2398 unsigned InnerPragmaCnt = 1;
2399 while (InnerPragmaCnt != 0) {
2400 PP.Lex(Tok);
2401 if (Tok.is(tok::annot_pragma_openmp))
2402 ++InnerPragmaCnt;
2403 else if (Tok.is(tok::annot_pragma_openmp_end))
2404 --InnerPragmaCnt;
2405 }
2406 PP.Lex(Tok);
2407 }
2408 }
2409 SourceLocation EodLoc = Tok.getLocation();
2410 Tok.startToken();
2411 Tok.setKind(tok::annot_pragma_openmp_end);
2412 Tok.setLocation(EodLoc);
2413 Pragma.push_back(Tok);
2414
2415 auto Toks = std::make_unique<Token[]>(Pragma.size());
2416 std::copy(Pragma.begin(), Pragma.end(), Toks.get());
2417 PP.EnterTokenStream(std::move(Toks), Pragma.size(),
2418 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
2419}
2420
2421/// Handle '#pragma pointers_to_members'
2422// The grammar for this pragma is as follows:
2423//
2424// <inheritance model> ::= ('single' | 'multiple' | 'virtual') '_inheritance'
2425//
2426// #pragma pointers_to_members '(' 'best_case' ')'
2427// #pragma pointers_to_members '(' 'full_generality' [',' inheritance-model] ')'
2428// #pragma pointers_to_members '(' inheritance-model ')'
2429void PragmaMSPointersToMembers::HandlePragma(Preprocessor &PP,
2430 PragmaIntroducer Introducer,
2431 Token &Tok) {
2432 SourceLocation PointersToMembersLoc = Tok.getLocation();
2433 PP.Lex(Tok);
2434 if (Tok.isNot(tok::l_paren)) {
2435 PP.Diag(PointersToMembersLoc, diag::warn_pragma_expected_lparen)
2436 << "pointers_to_members";
2437 return;
2438 }
2439 PP.Lex(Tok);
2440 const IdentifierInfo *Arg = Tok.getIdentifierInfo();
2441 if (!Arg) {
2442 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
2443 << "pointers_to_members";
2444 return;
2445 }
2446 PP.Lex(Tok);
2447
2448 LangOptions::PragmaMSPointersToMembersKind RepresentationMethod;
2449 if (Arg->isStr("best_case")) {
2450 RepresentationMethod = LangOptions::PPTMK_BestCase;
2451 } else {
2452 if (Arg->isStr("full_generality")) {
2453 if (Tok.is(tok::comma)) {
2454 PP.Lex(Tok);
2455
2456 Arg = Tok.getIdentifierInfo();
2457 if (!Arg) {
2458 PP.Diag(Tok.getLocation(),
2459 diag::err_pragma_pointers_to_members_unknown_kind)
2460 << Tok.getKind() << /*OnlyInheritanceModels*/ 0;
2461 return;
2462 }
2463 PP.Lex(Tok);
2464 } else if (Tok.is(tok::r_paren)) {
2465 // #pragma pointers_to_members(full_generality) implicitly specifies
2466 // virtual_inheritance.
2467 Arg = nullptr;
2468 RepresentationMethod = LangOptions::PPTMK_FullGeneralityVirtualInheritance;
2469 } else {
2470 PP.Diag(Tok.getLocation(), diag::err_expected_punc)
2471 << "full_generality";
2472 return;
2473 }
2474 }
2475
2476 if (Arg) {
2477 if (Arg->isStr("single_inheritance")) {
2478 RepresentationMethod =
2479 LangOptions::PPTMK_FullGeneralitySingleInheritance;
2480 } else if (Arg->isStr("multiple_inheritance")) {
2481 RepresentationMethod =
2482 LangOptions::PPTMK_FullGeneralityMultipleInheritance;
2483 } else if (Arg->isStr("virtual_inheritance")) {
2484 RepresentationMethod =
2485 LangOptions::PPTMK_FullGeneralityVirtualInheritance;
2486 } else {
2487 PP.Diag(Tok.getLocation(),
2488 diag::err_pragma_pointers_to_members_unknown_kind)
2489 << Arg << /*HasPointerDeclaration*/ 1;
2490 return;
2491 }
2492 }
2493 }
2494
2495 if (Tok.isNot(tok::r_paren)) {
2496 PP.Diag(Tok.getLocation(), diag::err_expected_rparen_after)
2497 << (Arg ? Arg->getName() : "full_generality");
2498 return;
2499 }
2500
2501 SourceLocation EndLoc = Tok.getLocation();
2502 PP.Lex(Tok);
2503 if (Tok.isNot(tok::eod)) {
2504 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2505 << "pointers_to_members";
2506 return;
2507 }
2508
2509 Token AnnotTok;
2510 AnnotTok.startToken();
2511 AnnotTok.setKind(tok::annot_pragma_ms_pointers_to_members);
2512 AnnotTok.setLocation(PointersToMembersLoc);
2513 AnnotTok.setAnnotationEndLoc(EndLoc);
2514 AnnotTok.setAnnotationValue(
2515 reinterpret_cast<void *>(static_cast<uintptr_t>(RepresentationMethod)));
2516 PP.EnterToken(AnnotTok, /*IsReinject=*/true);
2517}
2518
2519/// Handle '#pragma vtordisp'
2520// The grammar for this pragma is as follows:
2521//
2522// <vtordisp-mode> ::= ('off' | 'on' | '0' | '1' | '2' )
2523//
2524// #pragma vtordisp '(' ['push' ','] vtordisp-mode ')'
2525// #pragma vtordisp '(' 'pop' ')'
2526// #pragma vtordisp '(' ')'
2527void PragmaMSVtorDisp::HandlePragma(Preprocessor &PP,
2528 PragmaIntroducer Introducer, Token &Tok) {
2529 SourceLocation VtorDispLoc = Tok.getLocation();
2530 PP.Lex(Tok);
2531 if (Tok.isNot(tok::l_paren)) {
2532 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_lparen) << "vtordisp";
2533 return;
2534 }
2535 PP.Lex(Tok);
2536
2537 Sema::PragmaMsStackAction Action = Sema::PSK_Set;
2538 const IdentifierInfo *II = Tok.getIdentifierInfo();
2539 if (II) {
2540 if (II->isStr("push")) {
2541 // #pragma vtordisp(push, mode)
2542 PP.Lex(Tok);
2543 if (Tok.isNot(tok::comma)) {
2544 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_punc) << "vtordisp";
2545 return;
2546 }
2547 PP.Lex(Tok);
2548 Action = Sema::PSK_Push_Set;
2549 // not push, could be on/off
2550 } else if (II->isStr("pop")) {
2551 // #pragma vtordisp(pop)
2552 PP.Lex(Tok);
2553 Action = Sema::PSK_Pop;
2554 }
2555 // not push or pop, could be on/off
2556 } else {
2557 if (Tok.is(tok::r_paren)) {
2558 // #pragma vtordisp()
2559 Action = Sema::PSK_Reset;
2560 }
2561 }
2562
2563
2564 uint64_t Value = 0;
2565 if (Action & Sema::PSK_Push || Action & Sema::PSK_Set) {
2566 const IdentifierInfo *II = Tok.getIdentifierInfo();
2567 if (II && II->isStr("off")) {
2568 PP.Lex(Tok);
2569 Value = 0;
2570 } else if (II && II->isStr("on")) {
2571 PP.Lex(Tok);
2572 Value = 1;
2573 } else if (Tok.is(tok::numeric_constant) &&
2574 PP.parseSimpleIntegerLiteral(Tok, Value)) {
2575 if (Value > 2) {
2576 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_integer)
2577 << 0 << 2 << "vtordisp";
2578 return;
2579 }
2580 } else {
2581 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_action)
2582 << "vtordisp";
2583 return;
2584 }
2585 }
2586
2587 // Finish the pragma: ')' $
2588 if (Tok.isNot(tok::r_paren)) {
2589 PP.Diag(VtorDispLoc, diag::warn_pragma_expected_rparen) << "vtordisp";
2590 return;
2591 }
2592 SourceLocation EndLoc = Tok.getLocation();
2593 PP.Lex(Tok);
2594 if (Tok.isNot(tok::eod)) {
2595 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2596 << "vtordisp";
2597 return;
2598 }
2599
2600 // Enter the annotation.
2601 Token AnnotTok;
2602 AnnotTok.startToken();
2603 AnnotTok.setKind(tok::annot_pragma_ms_vtordisp);
2604 AnnotTok.setLocation(VtorDispLoc);
2605 AnnotTok.setAnnotationEndLoc(EndLoc);
2606 AnnotTok.setAnnotationValue(reinterpret_cast<void *>(
2607 static_cast<uintptr_t>((Action << 16) | (Value & 0xFFFF))));
2608 PP.EnterToken(AnnotTok, /*IsReinject=*/false);
2609}
2610
2611/// Handle all MS pragmas. Simply forwards the tokens after inserting
2612/// an annotation token.
2613void PragmaMSPragma::HandlePragma(Preprocessor &PP,
2614 PragmaIntroducer Introducer, Token &Tok) {
2615 Token EoF, AnnotTok;
2616 EoF.startToken();
2617 EoF.setKind(tok::eof);
2618 AnnotTok.startToken();
2619 AnnotTok.setKind(tok::annot_pragma_ms_pragma);
2620 AnnotTok.setLocation(Tok.getLocation());
2621 AnnotTok.setAnnotationEndLoc(Tok.getLocation());
2622 SmallVector<Token, 8> TokenVector;
2623 // Suck up all of the tokens before the eod.
2624 for (; Tok.isNot(tok::eod); PP.Lex(Tok)) {
2625 TokenVector.push_back(Tok);
2626 AnnotTok.setAnnotationEndLoc(Tok.getLocation());
2627 }
2628 // Add a sentinel EoF token to the end of the list.
2629 TokenVector.push_back(EoF);
2630 // We must allocate this array with new because EnterTokenStream is going to
2631 // delete it later.
2632 markAsReinjectedForRelexing(TokenVector);
2633 auto TokenArray = std::make_unique<Token[]>(TokenVector.size());
2634 std::copy(TokenVector.begin(), TokenVector.end(), TokenArray.get());
2635 auto Value = new (PP.getPreprocessorAllocator())
2636 std::pair<std::unique_ptr<Token[]>, size_t>(std::move(TokenArray),
2637 TokenVector.size());
2638 AnnotTok.setAnnotationValue(Value);
2639 PP.EnterToken(AnnotTok, /*IsReinject*/ false);
2640}
2641
2642/// Handle the \#pragma float_control extension.
2643///
2644/// The syntax is:
2645/// \code
2646/// #pragma float_control(keyword[, setting] [,push])
2647/// \endcode
2648/// Where 'keyword' and 'setting' are identifiers.
2649// 'keyword' can be: precise, except, push, pop
2650// 'setting' can be: on, off
2651/// The optional arguments 'setting' and 'push' are supported only
2652/// when the keyword is 'precise' or 'except'.
2653void PragmaFloatControlHandler::HandlePragma(Preprocessor &PP,
2654 PragmaIntroducer Introducer,
2655 Token &Tok) {
2656 Sema::PragmaMsStackAction Action = Sema::PSK_Set;
2657 SourceLocation FloatControlLoc = Tok.getLocation();
2658 Token PragmaName = Tok;
2659 if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
2660 PP.Diag(Tok.getLocation(), diag::warn_pragma_fp_ignored)
2661 << PragmaName.getIdentifierInfo()->getName();
2662 return;
2663 }
2664 PP.Lex(Tok);
2665 if (Tok.isNot(tok::l_paren)) {
2666 PP.Diag(FloatControlLoc, diag::err_expected) << tok::l_paren;
2667 return;
2668 }
2669
2670 // Read the identifier.
2671 PP.Lex(Tok);
2672 if (Tok.isNot(tok::identifier)) {
2673 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2674 return;
2675 }
2676
2677 // Verify that this is one of the float control options.
2678 IdentifierInfo *II = Tok.getIdentifierInfo();
2679 PragmaFloatControlKind Kind =
2680 llvm::StringSwitch<PragmaFloatControlKind>(II->getName())
2681 .Case("precise", PFC_Precise)
2682 .Case("except", PFC_Except)
2683 .Case("push", PFC_Push)
2684 .Case("pop", PFC_Pop)
2685 .Default(PFC_Unknown);
2686 PP.Lex(Tok); // the identifier
2687 if (Kind == PFC_Unknown) {
2688 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2689 return;
2690 } else if (Kind == PFC_Push || Kind == PFC_Pop) {
2691 if (Tok.isNot(tok::r_paren)) {
2692 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2693 return;
2694 }
2695 PP.Lex(Tok); // Eat the r_paren
2696 Action = (Kind == PFC_Pop) ? Sema::PSK_Pop : Sema::PSK_Push;
2697 } else {
2698 if (Tok.is(tok::r_paren))
2699 // Selecting Precise or Except
2700 PP.Lex(Tok); // the r_paren
2701 else if (Tok.isNot(tok::comma)) {
2702 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2703 return;
2704 } else {
2705 PP.Lex(Tok); // ,
2706 if (!Tok.isAnyIdentifier()) {
2707 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2708 return;
2709 }
2710 StringRef PushOnOff = Tok.getIdentifierInfo()->getName();
2711 if (PushOnOff == "on")
2712 // Kind is set correctly
2713 ;
2714 else if (PushOnOff == "off") {
2715 if (Kind == PFC_Precise)
2716 Kind = PFC_NoPrecise;
2717 if (Kind == PFC_Except)
2718 Kind = PFC_NoExcept;
2719 } else if (PushOnOff == "push") {
2720 Action = Sema::PSK_Push_Set;
2721 } else {
2722 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2723 return;
2724 }
2725 PP.Lex(Tok); // the identifier
2726 if (Tok.is(tok::comma)) {
2727 PP.Lex(Tok); // ,
2728 if (!Tok.isAnyIdentifier()) {
2729 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2730 return;
2731 }
2732 StringRef ExpectedPush = Tok.getIdentifierInfo()->getName();
2733 if (ExpectedPush == "push") {
2734 Action = Sema::PSK_Push_Set;
2735 } else {
2736 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2737 return;
2738 }
2739 PP.Lex(Tok); // the push identifier
2740 }
2741 if (Tok.isNot(tok::r_paren)) {
2742 PP.Diag(Tok.getLocation(), diag::err_pragma_float_control_malformed);
2743 return;
2744 }
2745 PP.Lex(Tok); // the r_paren
2746 }
2747 }
2748 SourceLocation EndLoc = Tok.getLocation();
2749 if (Tok.isNot(tok::eod)) {
2750 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
2751 << "float_control";
2752 return;
2753 }
2754
2755 // Note: there is no accomodation for PP callback for this pragma.
2756
2757 // Enter the annotation.
2758 auto TokenArray = std::make_unique<Token[]>(1);
2759 TokenArray[0].startToken();
2760 TokenArray[0].setKind(tok::annot_pragma_float_control);
2761 TokenArray[0].setLocation(FloatControlLoc);
2762 TokenArray[0].setAnnotationEndLoc(EndLoc);
2763 // Create an encoding of Action and Value by shifting the Action into
2764 // the high 16 bits then union with the Kind.
2765 TokenArray[0].setAnnotationValue(reinterpret_cast<void *>(
2766 static_cast<uintptr_t>((Action << 16) | (Kind & 0xFFFF))));
2767 PP.EnterTokenStream(std::move(TokenArray), 1,
2768 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
2769}
2770
2771/// Handle the Microsoft \#pragma detect_mismatch extension.
2772///
2773/// The syntax is:
2774/// \code
2775/// #pragma detect_mismatch("name", "value")
2776/// \endcode
2777/// Where 'name' and 'value' are quoted strings. The values are embedded in
2778/// the object file and passed along to the linker. If the linker detects a
2779/// mismatch in the object file's values for the given name, a LNK2038 error
2780/// is emitted. See MSDN for more details.
2781void PragmaDetectMismatchHandler::HandlePragma(Preprocessor &PP,
2782 PragmaIntroducer Introducer,
2783 Token &Tok) {
2784 SourceLocation DetectMismatchLoc = Tok.getLocation();
2785 PP.Lex(Tok);
2786 if (Tok.isNot(tok::l_paren)) {
2787 PP.Diag(DetectMismatchLoc, diag::err_expected) << tok::l_paren;
2788 return;
2789 }
2790
2791 // Read the name to embed, which must be a string literal.
2792 std::string NameString;
2793 if (!PP.LexStringLiteral(Tok, NameString,
2794 "pragma detect_mismatch",
2795 /*AllowMacroExpansion=*/true))
2796 return;
2797
2798 // Read the comma followed by a second string literal.
2799 std::string ValueString;
2800 if (Tok.isNot(tok::comma)) {
2801 PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
2802 return;
2803 }
2804
2805 if (!PP.LexStringLiteral(Tok, ValueString, "pragma detect_mismatch",
2806 /*AllowMacroExpansion=*/true))
2807 return;
2808
2809 if (Tok.isNot(tok::r_paren)) {
2810 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
2811 return;
2812 }
2813 PP.Lex(Tok); // Eat the r_paren.
2814
2815 if (Tok.isNot(tok::eod)) {
2816 PP.Diag(Tok.getLocation(), diag::err_pragma_detect_mismatch_malformed);
2817 return;
2818 }
2819
2820 // If the pragma is lexically sound, notify any interested PPCallbacks.
2821 if (PP.getPPCallbacks())
2822 PP.getPPCallbacks()->PragmaDetectMismatch(DetectMismatchLoc, NameString,
2823 ValueString);
2824
2825 Actions.ActOnPragmaDetectMismatch(DetectMismatchLoc, NameString, ValueString);
2826}
2827
2828/// Handle the microsoft \#pragma comment extension.
2829///
2830/// The syntax is:
2831/// \code
2832/// #pragma comment(linker, "foo")
2833/// \endcode
2834/// 'linker' is one of five identifiers: compiler, exestr, lib, linker, user.
2835/// "foo" is a string, which is fully macro expanded, and permits string
2836/// concatenation, embedded escape characters etc. See MSDN for more details.
2837void PragmaCommentHandler::HandlePragma(Preprocessor &PP,
2838 PragmaIntroducer Introducer,
2839 Token &Tok) {
2840 SourceLocation CommentLoc = Tok.getLocation();
2841 PP.Lex(Tok);
2842 if (Tok.isNot(tok::l_paren)) {
2843 PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
2844 return;
2845 }
2846
2847 // Read the identifier.
2848 PP.Lex(Tok);
2849 if (Tok.isNot(tok::identifier)) {
2850 PP.Diag(CommentLoc, diag::err_pragma_comment_malformed);
2851 return;
2852 }
2853
2854 // Verify that this is one of the 5 explicitly listed options.
2855 IdentifierInfo *II = Tok.getIdentifierInfo();
2856 PragmaMSCommentKind Kind =
2857 llvm::StringSwitch<PragmaMSCommentKind>(II->getName())
2858 .Case("linker", PCK_Linker)
2859 .Case("lib", PCK_Lib)
2860 .Case("compiler", PCK_Compiler)
2861 .Case("exestr", PCK_ExeStr)
2862 .Case("user", PCK_User)
2863 .Default(PCK_Unknown);
2864 if (Kind == PCK_Unknown) {
2865 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind);
2866 return;
2867 }
2868
2869 if (PP.getTargetInfo().getTriple().isOSBinFormatELF() && Kind != PCK_Lib) {
2870 PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
2871 << II->getName();
2872 return;
2873 }
2874
2875 // On PS4, issue a warning about any pragma comments other than
2876 // #pragma comment lib.
2877 if (PP.getTargetInfo().getTriple().isPS4() && Kind != PCK_Lib) {
2878 PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_ignored)
2879 << II->getName();
2880 return;
2881 }
2882
2883 // Read the optional string if present.
2884 PP.Lex(Tok);
2885 std::string ArgumentString;
2886 if (Tok.is(tok::comma) && !PP.LexStringLiteral(Tok, ArgumentString,
2887 "pragma comment",
2888 /*AllowMacroExpansion=*/true))
2889 return;
2890
2891 // FIXME: warn that 'exestr' is deprecated.
2892 // FIXME: If the kind is "compiler" warn if the string is present (it is
2893 // ignored).
2894 // The MSDN docs say that "lib" and "linker" require a string and have a short
2895 // list of linker options they support, but in practice MSVC doesn't
2896 // issue a diagnostic. Therefore neither does clang.
2897
2898 if (Tok.isNot(tok::r_paren)) {
2899 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
2900 return;
2901 }
2902 PP.Lex(Tok); // eat the r_paren.
2903
2904 if (Tok.isNot(tok::eod)) {
2905 PP.Diag(Tok.getLocation(), diag::err_pragma_comment_malformed);
2906 return;
2907 }
2908
2909 // If the pragma is lexically sound, notify any interested PPCallbacks.
2910 if (PP.getPPCallbacks())
2911 PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString);
2912
2913 Actions.ActOnPragmaMSComment(CommentLoc, Kind, ArgumentString);
2914}
2915
2916// #pragma clang optimize off
2917// #pragma clang optimize on
2918void PragmaOptimizeHandler::HandlePragma(Preprocessor &PP,
2919 PragmaIntroducer Introducer,
2920 Token &FirstToken) {
2921 Token Tok;
2922 PP.Lex(Tok);
2923 if (Tok.is(tok::eod)) {
2924 PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
2925 << "clang optimize" << /*Expected=*/true << "'on' or 'off'";
2926 return;
2927 }
2928 if (Tok.isNot(tok::identifier)) {
2929 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
2930 << PP.getSpelling(Tok);
2931 return;
2932 }
2933 const IdentifierInfo *II = Tok.getIdentifierInfo();
2934 // The only accepted values are 'on' or 'off'.
2935 bool IsOn = false;
2936 if (II->isStr("on")) {
2937 IsOn = true;
2938 } else if (!II->isStr("off")) {
2939 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_invalid_argument)
2940 << PP.getSpelling(Tok);
2941 return;
2942 }
2943 PP.Lex(Tok);
2944
2945 if (Tok.isNot(tok::eod)) {
2946 PP.Diag(Tok.getLocation(), diag::err_pragma_optimize_extra_argument)
2947 << PP.getSpelling(Tok);
2948 return;
2949 }
2950
2951 Actions.ActOnPragmaOptimize(IsOn, FirstToken.getLocation());
2952}
2953
2954namespace {
2955/// Used as the annotation value for tok::annot_pragma_fp.
2956struct TokFPAnnotValue {
2957 enum FlagKinds { Contract, Reassociate, Exceptions };
2958 enum FlagValues { On, Off, Fast };
2959
2960 llvm::Optional<LangOptions::FPModeKind> ContractValue;
2961 llvm::Optional<LangOptions::FPModeKind> ReassociateValue;
2962 llvm::Optional<LangOptions::FPExceptionModeKind> ExceptionsValue;
2963};
2964} // end anonymous namespace
2965
2966void PragmaFPHandler::HandlePragma(Preprocessor &PP,
2967 PragmaIntroducer Introducer, Token &Tok) {
2968 // fp
2969 Token PragmaName = Tok;
2970 SmallVector<Token, 1> TokenList;
2971
2972 PP.Lex(Tok);
2973 if (Tok.isNot(tok::identifier)) {
2974 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
2975 << /*MissingOption=*/true << "";
2976 return;
2977 }
2978
2979 auto *AnnotValue = new (PP.getPreprocessorAllocator()) TokFPAnnotValue;
2980 while (Tok.is(tok::identifier)) {
2981 IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
2982
2983 auto FlagKind =
2984 llvm::StringSwitch<llvm::Optional<TokFPAnnotValue::FlagKinds>>(
2985 OptionInfo->getName())
2986 .Case("contract", TokFPAnnotValue::Contract)
2987 .Case("reassociate", TokFPAnnotValue::Reassociate)
2988 .Case("exceptions", TokFPAnnotValue::Exceptions)
2989 .Default(None);
2990 if (!FlagKind) {
2991 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_option)
2992 << /*MissingOption=*/false << OptionInfo;
2993 return;
2994 }
2995 PP.Lex(Tok);
2996
2997 // Read '('
2998 if (Tok.isNot(tok::l_paren)) {
2999 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
3000 return;
3001 }
3002 PP.Lex(Tok);
3003
3004 if (Tok.isNot(tok::identifier)) {
3005 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3006 << PP.getSpelling(Tok) << OptionInfo->getName()
3007 << static_cast<int>(*FlagKind);
3008 return;
3009 }
3010 const IdentifierInfo *II = Tok.getIdentifierInfo();
3011
3012 if (FlagKind == TokFPAnnotValue::Contract) {
3013 AnnotValue->ContractValue =
3014 llvm::StringSwitch<llvm::Optional<LangOptions::FPModeKind>>(
3015 II->getName())
3016 .Case("on", LangOptions::FPModeKind::FPM_On)
3017 .Case("off", LangOptions::FPModeKind::FPM_Off)
3018 .Case("fast", LangOptions::FPModeKind::FPM_Fast)
3019 .Default(llvm::None);
3020 if (!AnnotValue->ContractValue) {
3021 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3022 << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3023 return;
3024 }
3025 } else if (FlagKind == TokFPAnnotValue::Reassociate) {
3026 AnnotValue->ReassociateValue =
3027 llvm::StringSwitch<llvm::Optional<LangOptions::FPModeKind>>(
3028 II->getName())
3029 .Case("on", LangOptions::FPModeKind::FPM_On)
3030 .Case("off", LangOptions::FPModeKind::FPM_Off)
3031 .Default(llvm::None);
3032 if (!AnnotValue->ReassociateValue) {
3033 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3034 << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3035 return;
3036 }
3037 } else if (FlagKind == TokFPAnnotValue::Exceptions) {
3038 AnnotValue->ExceptionsValue =
3039 llvm::StringSwitch<llvm::Optional<LangOptions::FPExceptionModeKind>>(
3040 II->getName())
3041 .Case("ignore", LangOptions::FPE_Ignore)
3042 .Case("maytrap", LangOptions::FPE_MayTrap)
3043 .Case("strict", LangOptions::FPE_Strict)
3044 .Default(llvm::None);
3045 if (!AnnotValue->ExceptionsValue) {
3046 PP.Diag(Tok.getLocation(), diag::err_pragma_fp_invalid_argument)
3047 << PP.getSpelling(Tok) << OptionInfo->getName() << *FlagKind;
3048 return;
3049 }
3050 }
3051 PP.Lex(Tok);
3052
3053 // Read ')'
3054 if (Tok.isNot(tok::r_paren)) {
3055 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
3056 return;
3057 }
3058 PP.Lex(Tok);
3059 }
3060
3061 if (Tok.isNot(tok::eod)) {
3062 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3063 << "clang fp";
3064 return;
3065 }
3066
3067 Token FPTok;
3068 FPTok.startToken();
3069 FPTok.setKind(tok::annot_pragma_fp);
3070 FPTok.setLocation(PragmaName.getLocation());
3071 FPTok.setAnnotationEndLoc(PragmaName.getLocation());
3072 FPTok.setAnnotationValue(reinterpret_cast<void *>(AnnotValue));
3073 TokenList.push_back(FPTok);
3074
3075 auto TokenArray = std::make_unique<Token[]>(TokenList.size());
3076 std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
3077
3078 PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
3079 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3080}
3081
3082void PragmaSTDC_FENV_ROUNDHandler::HandlePragma(Preprocessor &PP,
3083 PragmaIntroducer Introducer,
3084 Token &Tok) {
3085 Token PragmaName = Tok;
3086 SmallVector<Token, 1> TokenList;
3087 if (!PP.getTargetInfo().hasStrictFP() && !PP.getLangOpts().ExpStrictFP) {
3088 PP.Diag(Tok.getLocation(), diag::warn_pragma_fp_ignored)
3089 << PragmaName.getIdentifierInfo()->getName();
3090 return;
3091 }
3092
3093 PP.Lex(Tok);
3094 if (Tok.isNot(tok::identifier)) {
3095 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
3096 << PragmaName.getIdentifierInfo()->getName();
3097 return;
3098 }
3099 IdentifierInfo *II = Tok.getIdentifierInfo();
3100
3101 auto RM =
3102 llvm::StringSwitch<llvm::RoundingMode>(II->getName())
3103 .Case("FE_TOWARDZERO", llvm::RoundingMode::TowardZero)
3104 .Case("FE_TONEAREST", llvm::RoundingMode::NearestTiesToEven)
3105 .Case("FE_UPWARD", llvm::RoundingMode::TowardPositive)
3106 .Case("FE_DOWNWARD", llvm::RoundingMode::TowardNegative)
3107 .Case("FE_TONEARESTFROMZERO", llvm::RoundingMode::NearestTiesToAway)
3108 .Case("FE_DYNAMIC", llvm::RoundingMode::Dynamic)
3109 .Default(llvm::RoundingMode::Invalid);
3110 if (RM == llvm::RoundingMode::Invalid) {
3111 PP.Diag(Tok.getLocation(), diag::warn_stdc_unknown_rounding_mode);
3112 return;
3113 }
3114 PP.Lex(Tok);
3115
3116 if (Tok.isNot(tok::eod)) {
3117 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3118 << "STDC FENV_ROUND";
3119 return;
3120 }
3121
3122 // Until the pragma is fully implemented, issue a warning.
3123 PP.Diag(Tok.getLocation(), diag::warn_stdc_fenv_round_not_supported);
3124
3125 MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(1),
3126 1);
3127 Toks[0].startToken();
3128 Toks[0].setKind(tok::annot_pragma_fenv_round);
3129 Toks[0].setLocation(Tok.getLocation());
3130 Toks[0].setAnnotationEndLoc(Tok.getLocation());
3131 Toks[0].setAnnotationValue(
3132 reinterpret_cast<void *>(static_cast<uintptr_t>(RM)));
3133 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
3134 /*IsReinject=*/false);
3135}
3136
3137void Parser::HandlePragmaFP() {
3138 assert(Tok.is(tok::annot_pragma_fp))(static_cast <bool> (Tok.is(tok::annot_pragma_fp)) ? void
(0) : __assert_fail ("Tok.is(tok::annot_pragma_fp)", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Parse/ParsePragma.cpp"
, 3138, __extension__ __PRETTY_FUNCTION__))
;
3139 auto *AnnotValue =
3140 reinterpret_cast<TokFPAnnotValue *>(Tok.getAnnotationValue());
3141
3142 if (AnnotValue->ReassociateValue)
3143 Actions.ActOnPragmaFPReassociate(Tok.getLocation(),
3144 *AnnotValue->ReassociateValue ==
3145 LangOptions::FPModeKind::FPM_On);
3146 if (AnnotValue->ContractValue)
3147 Actions.ActOnPragmaFPContract(Tok.getLocation(),
3148 *AnnotValue->ContractValue);
3149 if (AnnotValue->ExceptionsValue)
3150 Actions.ActOnPragmaFPExceptions(Tok.getLocation(),
3151 *AnnotValue->ExceptionsValue);
3152 ConsumeAnnotationToken();
3153}
3154
3155/// Parses loop or unroll pragma hint value and fills in Info.
3156static bool ParseLoopHintValue(Preprocessor &PP, Token &Tok, Token PragmaName,
3157 Token Option, bool ValueInParens,
3158 PragmaLoopHintInfo &Info) {
3159 SmallVector<Token, 1> ValueList;
3160 int OpenParens = ValueInParens ? 1 : 0;
3161 // Read constant expression.
3162 while (Tok.isNot(tok::eod)) {
3163 if (Tok.is(tok::l_paren))
3164 OpenParens++;
3165 else if (Tok.is(tok::r_paren)) {
3166 OpenParens--;
3167 if (OpenParens == 0 && ValueInParens)
3168 break;
3169 }
3170
3171 ValueList.push_back(Tok);
3172 PP.Lex(Tok);
3173 }
3174
3175 if (ValueInParens) {
3176 // Read ')'
3177 if (Tok.isNot(tok::r_paren)) {
3178 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
3179 return true;
3180 }
3181 PP.Lex(Tok);
3182 }
3183
3184 Token EOFTok;
3185 EOFTok.startToken();
3186 EOFTok.setKind(tok::eof);
3187 EOFTok.setLocation(Tok.getLocation());
3188 ValueList.push_back(EOFTok); // Terminates expression for parsing.
3189
3190 markAsReinjectedForRelexing(ValueList);
3191 Info.Toks = llvm::makeArrayRef(ValueList).copy(PP.getPreprocessorAllocator());
3192
3193 Info.PragmaName = PragmaName;
3194 Info.Option = Option;
3195 return false;
3196}
3197
3198/// Handle the \#pragma clang loop directive.
3199/// #pragma clang 'loop' loop-hints
3200///
3201/// loop-hints:
3202/// loop-hint loop-hints[opt]
3203///
3204/// loop-hint:
3205/// 'vectorize' '(' loop-hint-keyword ')'
3206/// 'interleave' '(' loop-hint-keyword ')'
3207/// 'unroll' '(' unroll-hint-keyword ')'
3208/// 'vectorize_predicate' '(' loop-hint-keyword ')'
3209/// 'vectorize_width' '(' loop-hint-value ')'
3210/// 'interleave_count' '(' loop-hint-value ')'
3211/// 'unroll_count' '(' loop-hint-value ')'
3212/// 'pipeline' '(' disable ')'
3213/// 'pipeline_initiation_interval' '(' loop-hint-value ')'
3214///
3215/// loop-hint-keyword:
3216/// 'enable'
3217/// 'disable'
3218/// 'assume_safety'
3219///
3220/// unroll-hint-keyword:
3221/// 'enable'
3222/// 'disable'
3223/// 'full'
3224///
3225/// loop-hint-value:
3226/// constant-expression
3227///
3228/// Specifying vectorize(enable) or vectorize_width(_value_) instructs llvm to
3229/// try vectorizing the instructions of the loop it precedes. Specifying
3230/// interleave(enable) or interleave_count(_value_) instructs llvm to try
3231/// interleaving multiple iterations of the loop it precedes. The width of the
3232/// vector instructions is specified by vectorize_width() and the number of
3233/// interleaved loop iterations is specified by interleave_count(). Specifying a
3234/// value of 1 effectively disables vectorization/interleaving, even if it is
3235/// possible and profitable, and 0 is invalid. The loop vectorizer currently
3236/// only works on inner loops.
3237///
3238/// The unroll and unroll_count directives control the concatenation
3239/// unroller. Specifying unroll(enable) instructs llvm to unroll the loop
3240/// completely if the trip count is known at compile time and unroll partially
3241/// if the trip count is not known. Specifying unroll(full) is similar to
3242/// unroll(enable) but will unroll the loop only if the trip count is known at
3243/// compile time. Specifying unroll(disable) disables unrolling for the
3244/// loop. Specifying unroll_count(_value_) instructs llvm to try to unroll the
3245/// loop the number of times indicated by the value.
3246void PragmaLoopHintHandler::HandlePragma(Preprocessor &PP,
3247 PragmaIntroducer Introducer,
3248 Token &Tok) {
3249 // Incoming token is "loop" from "#pragma clang loop".
3250 Token PragmaName = Tok;
3251 SmallVector<Token, 1> TokenList;
3252
3253 // Lex the optimization option and verify it is an identifier.
3254 PP.Lex(Tok);
3255 if (Tok.isNot(tok::identifier)) {
3256 PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
3257 << /*MissingOption=*/true << "";
3258 return;
3259 }
3260
3261 while (Tok.is(tok::identifier)) {
3262 Token Option = Tok;
3263 IdentifierInfo *OptionInfo = Tok.getIdentifierInfo();
3264
3265 bool OptionValid = llvm::StringSwitch<bool>(OptionInfo->getName())
3266 .Case("vectorize", true)
3267 .Case("interleave", true)
3268 .Case("unroll", true)
3269 .Case("distribute", true)
3270 .Case("vectorize_predicate", true)
3271 .Case("vectorize_width", true)
3272 .Case("interleave_count", true)
3273 .Case("unroll_count", true)
3274 .Case("pipeline", true)
3275 .Case("pipeline_initiation_interval", true)
3276 .Default(false);
3277 if (!OptionValid) {
3278 PP.Diag(Tok.getLocation(), diag::err_pragma_loop_invalid_option)
3279 << /*MissingOption=*/false << OptionInfo;
3280 return;
3281 }
3282 PP.Lex(Tok);
3283
3284 // Read '('
3285 if (Tok.isNot(tok::l_paren)) {
3286 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
3287 return;
3288 }
3289 PP.Lex(Tok);
3290
3291 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
3292 if (ParseLoopHintValue(PP, Tok, PragmaName, Option, /*ValueInParens=*/true,
3293 *Info))
3294 return;
3295
3296 // Generate the loop hint token.
3297 Token LoopHintTok;
3298 LoopHintTok.startToken();
3299 LoopHintTok.setKind(tok::annot_pragma_loop_hint);
3300 LoopHintTok.setLocation(Introducer.Loc);
3301 LoopHintTok.setAnnotationEndLoc(PragmaName.getLocation());
3302 LoopHintTok.setAnnotationValue(static_cast<void *>(Info));
3303 TokenList.push_back(LoopHintTok);
3304 }
3305
3306 if (Tok.isNot(tok::eod)) {
3307 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3308 << "clang loop";
3309 return;
3310 }
3311
3312 auto TokenArray = std::make_unique<Token[]>(TokenList.size());
3313 std::copy(TokenList.begin(), TokenList.end(), TokenArray.get());
3314
3315 PP.EnterTokenStream(std::move(TokenArray), TokenList.size(),
3316 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3317}
3318
3319/// Handle the loop unroll optimization pragmas.
3320/// #pragma unroll
3321/// #pragma unroll unroll-hint-value
3322/// #pragma unroll '(' unroll-hint-value ')'
3323/// #pragma nounroll
3324/// #pragma unroll_and_jam
3325/// #pragma unroll_and_jam unroll-hint-value
3326/// #pragma unroll_and_jam '(' unroll-hint-value ')'
3327/// #pragma nounroll_and_jam
3328///
3329/// unroll-hint-value:
3330/// constant-expression
3331///
3332/// Loop unrolling hints can be specified with '#pragma unroll' or
3333/// '#pragma nounroll'. '#pragma unroll' can take a numeric argument optionally
3334/// contained in parentheses. With no argument the directive instructs llvm to
3335/// try to unroll the loop completely. A positive integer argument can be
3336/// specified to indicate the number of times the loop should be unrolled. To
3337/// maximize compatibility with other compilers the unroll count argument can be
3338/// specified with or without parentheses. Specifying, '#pragma nounroll'
3339/// disables unrolling of the loop.
3340void PragmaUnrollHintHandler::HandlePragma(Preprocessor &PP,
3341 PragmaIntroducer Introducer,
3342 Token &Tok) {
3343 // Incoming token is "unroll" for "#pragma unroll", or "nounroll" for
3344 // "#pragma nounroll".
3345 Token PragmaName = Tok;
3346 PP.Lex(Tok);
3347 auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
3348 if (Tok.is(tok::eod)) {
3349 // nounroll or unroll pragma without an argument.
3350 Info->PragmaName = PragmaName;
3351 Info->Option.startToken();
3352 } else if (PragmaName.getIdentifierInfo()->getName() == "nounroll" ||
3353 PragmaName.getIdentifierInfo()->getName() == "nounroll_and_jam") {
3354 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3355 << PragmaName.getIdentifierInfo()->getName();
3356 return;
3357 } else {
3358 // Unroll pragma with an argument: "#pragma unroll N" or
3359 // "#pragma unroll(N)".
3360 // Read '(' if it exists.
3361 bool ValueInParens = Tok.is(tok::l_paren);
3362 if (ValueInParens)
3363 PP.Lex(Tok);
3364
3365 Token Option;
3366 Option.startToken();
3367 if (ParseLoopHintValue(PP, Tok, PragmaName, Option, ValueInParens, *Info))
3368 return;
3369
3370 // In CUDA, the argument to '#pragma unroll' should not be contained in
3371 // parentheses.
3372 if (PP.getLangOpts().CUDA && ValueInParens)
3373 PP.Diag(Info->Toks[0].getLocation(),
3374 diag::warn_pragma_unroll_cuda_value_in_parens);
3375
3376 if (Tok.isNot(tok::eod)) {
3377 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3378 << "unroll";
3379 return;
3380 }
3381 }
3382
3383 // Generate the hint token.
3384 auto TokenArray = std::make_unique<Token[]>(1);
3385 TokenArray[0].startToken();
3386 TokenArray[0].setKind(tok::annot_pragma_loop_hint);
3387 TokenArray[0].setLocation(Introducer.Loc);
3388 TokenArray[0].setAnnotationEndLoc(PragmaName.getLocation());
3389 TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
3390 PP.EnterTokenStream(std::move(TokenArray), 1,
3391 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3392}
3393
3394/// Handle the Microsoft \#pragma intrinsic extension.
3395///
3396/// The syntax is:
3397/// \code
3398/// #pragma intrinsic(memset)
3399/// #pragma intrinsic(strlen, memcpy)
3400/// \endcode
3401///
3402/// Pragma intrisic tells the compiler to use a builtin version of the
3403/// function. Clang does it anyway, so the pragma doesn't really do anything.
3404/// Anyway, we emit a warning if the function specified in \#pragma intrinsic
3405/// isn't an intrinsic in clang and suggest to include intrin.h.
3406void PragmaMSIntrinsicHandler::HandlePragma(Preprocessor &PP,
3407 PragmaIntroducer Introducer,
3408 Token &Tok) {
3409 PP.Lex(Tok);
3410
3411 if (Tok.isNot(tok::l_paren)) {
3412 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen)
3413 << "intrinsic";
3414 return;
3415 }
3416 PP.Lex(Tok);
3417
3418 bool SuggestIntrinH = !PP.isMacroDefined("__INTRIN_H");
3419
3420 while (Tok.is(tok::identifier)) {
3421 IdentifierInfo *II = Tok.getIdentifierInfo();
3422 if (!II->getBuiltinID())
3423 PP.Diag(Tok.getLocation(), diag::warn_pragma_intrinsic_builtin)
3424 << II << SuggestIntrinH;
3425
3426 PP.Lex(Tok);
3427 if (Tok.isNot(tok::comma))
3428 break;
3429 PP.Lex(Tok);
3430 }
3431
3432 if (Tok.isNot(tok::r_paren)) {
3433 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen)
3434 << "intrinsic";
3435 return;
3436 }
3437 PP.Lex(Tok);
3438
3439 if (Tok.isNot(tok::eod))
3440 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3441 << "intrinsic";
3442}
3443
3444// #pragma optimize("gsty", on|off)
3445void PragmaMSOptimizeHandler::HandlePragma(Preprocessor &PP,
3446 PragmaIntroducer Introducer,
3447 Token &Tok) {
3448 SourceLocation StartLoc = Tok.getLocation();
3449 PP.Lex(Tok);
3450
3451 if (Tok.isNot(tok::l_paren)) {
3452 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "optimize";
3453 return;
3454 }
3455 PP.Lex(Tok);
3456
3457 if (Tok.isNot(tok::string_literal)) {
3458 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_string) << "optimize";
3459 return;
3460 }
3461 // We could syntax check the string but it's probably not worth the effort.
3462 PP.Lex(Tok);
3463
3464 if (Tok.isNot(tok::comma)) {
3465 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_comma) << "optimize";
3466 return;
3467 }
3468 PP.Lex(Tok);
3469
3470 if (Tok.is(tok::eod) || Tok.is(tok::r_paren)) {
3471 PP.Diag(Tok.getLocation(), diag::warn_pragma_missing_argument)
3472 << "optimize" << /*Expected=*/true << "'on' or 'off'";
3473 return;
3474 }
3475 IdentifierInfo *II = Tok.getIdentifierInfo();
3476 if (!II || (!II->isStr("on") && !II->isStr("off"))) {
3477 PP.Diag(Tok.getLocation(), diag::warn_pragma_invalid_argument)
3478 << PP.getSpelling(Tok) << "optimize" << /*Expected=*/true
3479 << "'on' or 'off'";
3480 return;
3481 }
3482 PP.Lex(Tok);
3483
3484 if (Tok.isNot(tok::r_paren)) {
3485 PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "optimize";
3486 return;
3487 }
3488 PP.Lex(Tok);
3489
3490 if (Tok.isNot(tok::eod)) {
3491 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3492 << "optimize";
3493 return;
3494 }
3495 PP.Diag(StartLoc, diag::warn_pragma_optimize);
3496}
3497
3498void PragmaForceCUDAHostDeviceHandler::HandlePragma(
3499 Preprocessor &PP, PragmaIntroducer Introducer, Token &Tok) {
3500 Token FirstTok = Tok;
3501
3502 PP.Lex(Tok);
3503 IdentifierInfo *Info = Tok.getIdentifierInfo();
3504 if (!Info || (!Info->isStr("begin") && !Info->isStr("end"))) {
3505 PP.Diag(FirstTok.getLocation(),
3506 diag::warn_pragma_force_cuda_host_device_bad_arg);
3507 return;
3508 }
3509
3510 if (Info->isStr("begin"))
3511 Actions.PushForceCUDAHostDevice();
3512 else if (!Actions.PopForceCUDAHostDevice())
3513 PP.Diag(FirstTok.getLocation(),
3514 diag::err_pragma_cannot_end_force_cuda_host_device);
3515
3516 PP.Lex(Tok);
3517 if (!Tok.is(tok::eod))
3518 PP.Diag(FirstTok.getLocation(),
3519 diag::warn_pragma_force_cuda_host_device_bad_arg);
3520}
3521
3522/// Handle the #pragma clang attribute directive.
3523///
3524/// The syntax is:
3525/// \code
3526/// #pragma clang attribute push (attribute, subject-set)
3527/// #pragma clang attribute push
3528/// #pragma clang attribute (attribute, subject-set)
3529/// #pragma clang attribute pop
3530/// \endcode
3531///
3532/// There are also 'namespace' variants of push and pop directives. The bare
3533/// '#pragma clang attribute (attribute, subject-set)' version doesn't require a
3534/// namespace, since it always applies attributes to the most recently pushed
3535/// group, regardless of namespace.
3536/// \code
3537/// #pragma clang attribute namespace.push (attribute, subject-set)
3538/// #pragma clang attribute namespace.push
3539/// #pragma clang attribute namespace.pop
3540/// \endcode
3541///
3542/// The subject-set clause defines the set of declarations which receive the
3543/// attribute. Its exact syntax is described in the LanguageExtensions document
3544/// in Clang's documentation.
3545///
3546/// This directive instructs the compiler to begin/finish applying the specified
3547/// attribute to the set of attribute-specific declarations in the active range
3548/// of the pragma.
3549void PragmaAttributeHandler::HandlePragma(Preprocessor &PP,
3550 PragmaIntroducer Introducer,
3551 Token &FirstToken) {
3552 Token Tok;
3553 PP.Lex(Tok);
3554 auto *Info = new (PP.getPreprocessorAllocator())
3555 PragmaAttributeInfo(AttributesForPragmaAttribute);
3556
3557 // Parse the optional namespace followed by a period.
3558 if (Tok.is(tok::identifier)) {
3559 IdentifierInfo *II = Tok.getIdentifierInfo();
3560 if (!II->isStr("push") && !II->isStr("pop")) {
3561 Info->Namespace = II;
3562 PP.Lex(Tok);
3563
3564 if (!Tok.is(tok::period)) {
3565 PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_period)
3566 << II;
3567 return;
3568 }
3569 PP.Lex(Tok);
3570 }
3571 }
3572
3573 if (!Tok.isOneOf(tok::identifier, tok::l_paren)) {
3574 PP.Diag(Tok.getLocation(),
3575 diag::err_pragma_attribute_expected_push_pop_paren);
3576 return;
3577 }
3578
3579 // Determine what action this pragma clang attribute represents.
3580 if (Tok.is(tok::l_paren)) {
3581 if (Info->Namespace) {
3582 PP.Diag(Tok.getLocation(),
3583 diag::err_pragma_attribute_namespace_on_attribute);
3584 PP.Diag(Tok.getLocation(),
3585 diag::note_pragma_attribute_namespace_on_attribute);
3586 return;
3587 }
3588 Info->Action = PragmaAttributeInfo::Attribute;
3589 } else {
3590 const IdentifierInfo *II = Tok.getIdentifierInfo();
3591 if (II->isStr("push"))
3592 Info->Action = PragmaAttributeInfo::Push;
3593 else if (II->isStr("pop"))
3594 Info->Action = PragmaAttributeInfo::Pop;
3595 else {
3596 PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_invalid_argument)
3597 << PP.getSpelling(Tok);
3598 return;
3599 }
3600
3601 PP.Lex(Tok);
3602 }
3603
3604 // Parse the actual attribute.
3605 if ((Info->Action == PragmaAttributeInfo::Push && Tok.isNot(tok::eod)) ||
3606 Info->Action == PragmaAttributeInfo::Attribute) {
3607 if (Tok.isNot(tok::l_paren)) {
3608 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::l_paren;
3609 return;
3610 }
3611 PP.Lex(Tok);
3612
3613 // Lex the attribute tokens.
3614 SmallVector<Token, 16> AttributeTokens;
3615 int OpenParens = 1;
3616 while (Tok.isNot(tok::eod)) {
3617 if (Tok.is(tok::l_paren))
3618 OpenParens++;
3619 else if (Tok.is(tok::r_paren)) {
3620 OpenParens--;
3621 if (OpenParens == 0)
3622 break;
3623 }
3624
3625 AttributeTokens.push_back(Tok);
3626 PP.Lex(Tok);
3627 }
3628
3629 if (AttributeTokens.empty()) {
3630 PP.Diag(Tok.getLocation(), diag::err_pragma_attribute_expected_attribute);
3631 return;
3632 }
3633 if (Tok.isNot(tok::r_paren)) {
3634 PP.Diag(Tok.getLocation(), diag::err_expected) << tok::r_paren;
3635 return;
3636 }
3637 SourceLocation EndLoc = Tok.getLocation();
3638 PP.Lex(Tok);
3639
3640 // Terminate the attribute for parsing.
3641 Token EOFTok;
3642 EOFTok.startToken();
3643 EOFTok.setKind(tok::eof);
3644 EOFTok.setLocation(EndLoc);
3645 AttributeTokens.push_back(EOFTok);
3646
3647 markAsReinjectedForRelexing(AttributeTokens);
3648 Info->Tokens =
3649 llvm::makeArrayRef(AttributeTokens).copy(PP.getPreprocessorAllocator());
3650 }
3651
3652 if (Tok.isNot(tok::eod))
3653 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3654 << "clang attribute";
3655
3656 // Generate the annotated pragma token.
3657 auto TokenArray = std::make_unique<Token[]>(1);
3658 TokenArray[0].startToken();
3659 TokenArray[0].setKind(tok::annot_pragma_attribute);
3660 TokenArray[0].setLocation(FirstToken.getLocation());
3661 TokenArray[0].setAnnotationEndLoc(FirstToken.getLocation());
3662 TokenArray[0].setAnnotationValue(static_cast<void *>(Info));
3663 PP.EnterTokenStream(std::move(TokenArray), 1,
3664 /*DisableMacroExpansion=*/false, /*IsReinject=*/false);
3665}
3666
3667// Handle '#pragma clang max_tokens 12345'.
3668void PragmaMaxTokensHereHandler::HandlePragma(Preprocessor &PP,
3669 PragmaIntroducer Introducer,
3670 Token &Tok) {
3671 PP.Lex(Tok);
3672 if (Tok.is(tok::eod)) {
3673 PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
3674 << "clang max_tokens_here" << /*Expected=*/true << "integer";
3675 return;
3676 }
3677
3678 SourceLocation Loc = Tok.getLocation();
3679 uint64_t MaxTokens;
3680 if (Tok.isNot(tok::numeric_constant) ||
3681 !PP.parseSimpleIntegerLiteral(Tok, MaxTokens)) {
3682 PP.Diag(Tok.getLocation(), diag::err_pragma_expected_integer)
3683 << "clang max_tokens_here";
3684 return;
3685 }
3686
3687 if (Tok.isNot(tok::eod)) {
3688 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3689 << "clang max_tokens_here";
3690 return;
3691 }
3692
3693 if (PP.getTokenCount() > MaxTokens) {
3694 PP.Diag(Loc, diag::warn_max_tokens)
3695 << PP.getTokenCount() << (unsigned)MaxTokens;
3696 }
3697}
3698
3699// Handle '#pragma clang max_tokens_total 12345'.
3700void PragmaMaxTokensTotalHandler::HandlePragma(Preprocessor &PP,
3701 PragmaIntroducer Introducer,
3702 Token &Tok) {
3703 PP.Lex(Tok);
3704 if (Tok.is(tok::eod)) {
3705 PP.Diag(Tok.getLocation(), diag::err_pragma_missing_argument)
3706 << "clang max_tokens_total" << /*Expected=*/true << "integer";
3707 return;
3708 }
3709
3710 SourceLocation Loc = Tok.getLocation();
3711 uint64_t MaxTokens;
3712 if (Tok.isNot(tok::numeric_constant) ||
3713 !PP.parseSimpleIntegerLiteral(Tok, MaxTokens)) {
3714 PP.Diag(Tok.getLocation(), diag::err_pragma_expected_integer)
3715 << "clang max_tokens_total";
3716 return;
3717 }
3718
3719 if (Tok.isNot(tok::eod)) {
3720 PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
3721 << "clang max_tokens_total";
3722 return;
3723 }
3724
3725 PP.overrideMaxTokens(MaxTokens, Loc);
3726}

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h

1//===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
15#define LLVM_CLANG_BASIC_DIAGNOSTIC_H
16
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/SourceLocation.h"
20#include "clang/Basic/Specifiers.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/IntrusiveRefCntPtr.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Compiler.h"
29#include <cassert>
30#include <cstdint>
31#include <limits>
32#include <list>
33#include <map>
34#include <memory>
35#include <string>
36#include <type_traits>
37#include <utility>
38#include <vector>
39
40namespace llvm {
41class Error;
42}
43
44namespace clang {
45
46class DeclContext;
47class DiagnosticBuilder;
48class DiagnosticConsumer;
49class IdentifierInfo;
50class LangOptions;
51class Preprocessor;
52class SourceManager;
53class StoredDiagnostic;
54
55namespace tok {
56
57enum TokenKind : unsigned short;
58
59} // namespace tok
60
61/// Annotates a diagnostic with some code that should be
62/// inserted, removed, or replaced to fix the problem.
63///
64/// This kind of hint should be used when we are certain that the
65/// introduction, removal, or modification of a particular (small!)
66/// amount of code will correct a compilation error. The compiler
67/// should also provide full recovery from such errors, such that
68/// suppressing the diagnostic output can still result in successful
69/// compilation.
70class FixItHint {
71public:
72 /// Code that should be replaced to correct the error. Empty for an
73 /// insertion hint.
74 CharSourceRange RemoveRange;
75
76 /// Code in the specific range that should be inserted in the insertion
77 /// location.
78 CharSourceRange InsertFromRange;
79
80 /// The actual code to insert at the insertion location, as a
81 /// string.
82 std::string CodeToInsert;
83
84 bool BeforePreviousInsertions = false;
85
86 /// Empty code modification hint, indicating that no code
87 /// modification is known.
88 FixItHint() = default;
89
90 bool isNull() const {
91 return !RemoveRange.isValid();
92 }
93
94 /// Create a code modification hint that inserts the given
95 /// code string at a specific location.
96 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
97 StringRef Code,
98 bool BeforePreviousInsertions = false) {
99 FixItHint Hint;
100 Hint.RemoveRange =
101 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
102 Hint.CodeToInsert = std::string(Code);
103 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
104 return Hint;
105 }
106
107 /// Create a code modification hint that inserts the given
108 /// code from \p FromRange at a specific location.
109 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
110 CharSourceRange FromRange,
111 bool BeforePreviousInsertions = false) {
112 FixItHint Hint;
113 Hint.RemoveRange =
114 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
115 Hint.InsertFromRange = FromRange;
116 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
117 return Hint;
118 }
119
120 /// Create a code modification hint that removes the given
121 /// source range.
122 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
123 FixItHint Hint;
124 Hint.RemoveRange = RemoveRange;
125 return Hint;
126 }
127 static FixItHint CreateRemoval(SourceRange RemoveRange) {
128 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
129 }
130
131 /// Create a code modification hint that replaces the given
132 /// source range with the given code string.
133 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
134 StringRef Code) {
135 FixItHint Hint;
136 Hint.RemoveRange = RemoveRange;
137 Hint.CodeToInsert = std::string(Code);
138 return Hint;
139 }
140
141 static FixItHint CreateReplacement(SourceRange RemoveRange,
142 StringRef Code) {
143 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
144 }
145};
146
147struct DiagnosticStorage {
148 enum {
149 /// The maximum number of arguments we can hold. We
150 /// currently only support up to 10 arguments (%0-%9).
151 ///
152 /// A single diagnostic with more than that almost certainly has to
153 /// be simplified anyway.
154 MaxArguments = 10
155 };
156
157 /// The number of entries in Arguments.
158 unsigned char NumDiagArgs = 0;
159
160 /// Specifies for each argument whether it is in DiagArgumentsStr
161 /// or in DiagArguments.
162 unsigned char DiagArgumentsKind[MaxArguments];
163
164 /// The values for the various substitution positions.
165 ///
166 /// This is used when the argument is not an std::string. The specific value
167 /// is mangled into an intptr_t and the interpretation depends on exactly
168 /// what sort of argument kind it is.
169 intptr_t DiagArgumentsVal[MaxArguments];
170
171 /// The values for the various substitution positions that have
172 /// string arguments.
173 std::string DiagArgumentsStr[MaxArguments];
174
175 /// The list of ranges added to this diagnostic.
176 SmallVector<CharSourceRange, 8> DiagRanges;
177
178 /// If valid, provides a hint with some code to insert, remove, or
179 /// modify at a particular position.
180 SmallVector<FixItHint, 6> FixItHints;
181
182 DiagnosticStorage() = default;
183};
184
185/// Concrete class used by the front-end to report problems and issues.
186///
187/// This massages the diagnostics (e.g. handling things like "report warnings
188/// as errors" and passes them off to the DiagnosticConsumer for reporting to
189/// the user. DiagnosticsEngine is tied to one translation unit and one
190/// SourceManager.
191class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
192public:
193 /// The level of the diagnostic, after it has been through mapping.
194 enum Level {
195 Ignored = DiagnosticIDs::Ignored,
196 Note = DiagnosticIDs::Note,
197 Remark = DiagnosticIDs::Remark,
198 Warning = DiagnosticIDs::Warning,
199 Error = DiagnosticIDs::Error,
200 Fatal = DiagnosticIDs::Fatal
201 };
202
203 enum ArgumentKind {
204 /// std::string
205 ak_std_string,
206
207 /// const char *
208 ak_c_string,
209
210 /// int
211 ak_sint,
212
213 /// unsigned
214 ak_uint,
215
216 /// enum TokenKind : unsigned
217 ak_tokenkind,
218
219 /// IdentifierInfo
220 ak_identifierinfo,
221
222 /// address space
223 ak_addrspace,
224
225 /// Qualifiers
226 ak_qual,
227
228 /// QualType
229 ak_qualtype,
230
231 /// DeclarationName
232 ak_declarationname,
233
234 /// NamedDecl *
235 ak_nameddecl,
236
237 /// NestedNameSpecifier *
238 ak_nestednamespec,
239
240 /// DeclContext *
241 ak_declcontext,
242
243 /// pair<QualType, QualType>
244 ak_qualtype_pair,
245
246 /// Attr *
247 ak_attr
248 };
249
250 /// Represents on argument value, which is a union discriminated
251 /// by ArgumentKind, with a value.
252 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
253
254private:
255 // Used by __extension__
256 unsigned char AllExtensionsSilenced = 0;
257
258 // Treat fatal errors like errors.
259 bool FatalsAsError = false;
260
261 // Suppress all diagnostics.
262 bool SuppressAllDiagnostics = false;
263
264 // Elide common types of templates.
265 bool ElideType = true;
266
267 // Print a tree when comparing templates.
268 bool PrintTemplateTree = false;
269
270 // Color printing is enabled.
271 bool ShowColors = false;
272
273 // Which overload candidates to show.
274 OverloadsShown ShowOverloads = Ovl_All;
275
276 // With Ovl_Best, the number of overload candidates to show when we encounter
277 // an error.
278 //
279 // The value here is the number of candidates to show in the first nontrivial
280 // error. Future errors may show a different number of candidates.
281 unsigned NumOverloadsToShow = 32;
282
283 // Cap of # errors emitted, 0 -> no limit.
284 unsigned ErrorLimit = 0;
285
286 // Cap on depth of template backtrace stack, 0 -> no limit.
287 unsigned TemplateBacktraceLimit = 0;
288
289 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
290 unsigned ConstexprBacktraceLimit = 0;
291
292 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
293 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
294 DiagnosticConsumer *Client = nullptr;
295 std::unique_ptr<DiagnosticConsumer> Owner;
296 SourceManager *SourceMgr = nullptr;
297
298 /// Mapping information for diagnostics.
299 ///
300 /// Mapping info is packed into four bits per diagnostic. The low three
301 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
302 /// The high bit is set when the mapping was established as a user mapping.
303 /// If the high bit is clear, then the low bits are set to the default
304 /// value, and should be mapped with -pedantic, -Werror, etc.
305 ///
306 /// A new DiagState is created and kept around when diagnostic pragmas modify
307 /// the state so that we know what is the diagnostic state at any given
308 /// source location.
309 class DiagState {
310 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
311
312 public:
313 // "Global" configuration state that can actually vary between modules.
314
315 // Ignore all warnings: -w
316 unsigned IgnoreAllWarnings : 1;
317
318 // Enable all warnings.
319 unsigned EnableAllWarnings : 1;
320
321 // Treat warnings like errors.
322 unsigned WarningsAsErrors : 1;
323
324 // Treat errors like fatal errors.
325 unsigned ErrorsAsFatal : 1;
326
327 // Suppress warnings in system headers.
328 unsigned SuppressSystemWarnings : 1;
329
330 // Map extensions to warnings or errors?
331 diag::Severity ExtBehavior = diag::Severity::Ignored;
332
333 DiagState()
334 : IgnoreAllWarnings(false), EnableAllWarnings(false),
335 WarningsAsErrors(false), ErrorsAsFatal(false),
336 SuppressSystemWarnings(false) {}
337
338 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
339 using const_iterator =
340 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
341
342 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
343 DiagMap[Diag] = Info;
344 }
345
346 DiagnosticMapping lookupMapping(diag::kind Diag) const {
347 return DiagMap.lookup(Diag);
348 }
349
350 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
351
352 const_iterator begin() const { return DiagMap.begin(); }
353 const_iterator end() const { return DiagMap.end(); }
354 };
355
356 /// Keeps and automatically disposes all DiagStates that we create.
357 std::list<DiagState> DiagStates;
358
359 /// A mapping from files to the diagnostic states for those files. Lazily
360 /// built on demand for files in which the diagnostic state has not changed.
361 class DiagStateMap {
362 public:
363 /// Add an initial diagnostic state.
364 void appendFirst(DiagState *State);
365
366 /// Add a new latest state point.
367 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
368
369 /// Look up the diagnostic state at a given source location.
370 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
371
372 /// Determine whether this map is empty.
373 bool empty() const { return Files.empty(); }
374
375 /// Clear out this map.
376 void clear() {
377 Files.clear();
378 FirstDiagState = CurDiagState = nullptr;
379 CurDiagStateLoc = SourceLocation();
380 }
381
382 /// Produce a debugging dump of the diagnostic state.
383 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump(SourceManager &SrcMgr,
384 StringRef DiagName = StringRef()) const;
385
386 /// Grab the most-recently-added state point.
387 DiagState *getCurDiagState() const { return CurDiagState; }
388
389 /// Get the location at which a diagnostic state was last added.
390 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
391
392 private:
393 friend class ASTReader;
394 friend class ASTWriter;
395
396 /// Represents a point in source where the diagnostic state was
397 /// modified because of a pragma.
398 ///
399 /// 'Loc' can be null if the point represents the diagnostic state
400 /// modifications done through the command-line.
401 struct DiagStatePoint {
402 DiagState *State;
403 unsigned Offset;
404
405 DiagStatePoint(DiagState *State, unsigned Offset)
406 : State(State), Offset(Offset) {}
407 };
408
409 /// Description of the diagnostic states and state transitions for a
410 /// particular FileID.
411 struct File {
412 /// The diagnostic state for the parent file. This is strictly redundant,
413 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
414 /// map would give us this, but we cache it here for performance.
415 File *Parent = nullptr;
416
417 /// The offset of this file within its parent.
418 unsigned ParentOffset = 0;
419
420 /// Whether this file has any local (not imported from an AST file)
421 /// diagnostic state transitions.
422 bool HasLocalTransitions = false;
423
424 /// The points within the file where the state changes. There will always
425 /// be at least one of these (the state on entry to the file).
426 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
427
428 DiagState *lookup(unsigned Offset) const;
429 };
430
431 /// The diagnostic states for each file.
432 mutable std::map<FileID, File> Files;
433
434 /// The initial diagnostic state.
435 DiagState *FirstDiagState;
436
437 /// The current diagnostic state.
438 DiagState *CurDiagState;
439
440 /// The location at which the current diagnostic state was established.
441 SourceLocation CurDiagStateLoc;
442
443 /// Get the diagnostic state information for a file.
444 File *getFile(SourceManager &SrcMgr, FileID ID) const;
445 };
446
447 DiagStateMap DiagStatesByLoc;
448
449 /// Keeps the DiagState that was active during each diagnostic 'push'
450 /// so we can get back at it when we 'pop'.
451 std::vector<DiagState *> DiagStateOnPushStack;
452
453 DiagState *GetCurDiagState() const {
454 return DiagStatesByLoc.getCurDiagState();
455 }
456
457 void PushDiagStatePoint(DiagState *State, SourceLocation L);
458
459 /// Finds the DiagStatePoint that contains the diagnostic state of
460 /// the given source location.
461 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
462 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
463 : DiagStatesByLoc.getCurDiagState();
464 }
465
466 /// Sticky flag set to \c true when an error is emitted.
467 bool ErrorOccurred;
468
469 /// Sticky flag set to \c true when an "uncompilable error" occurs.
470 /// I.e. an error that was not upgraded from a warning by -Werror.
471 bool UncompilableErrorOccurred;
472
473 /// Sticky flag set to \c true when a fatal error is emitted.
474 bool FatalErrorOccurred;
475
476 /// Indicates that an unrecoverable error has occurred.
477 bool UnrecoverableErrorOccurred;
478
479 /// Counts for DiagnosticErrorTrap to check whether an error occurred
480 /// during a parsing section, e.g. during parsing a function.
481 unsigned TrapNumErrorsOccurred;
482 unsigned TrapNumUnrecoverableErrorsOccurred;
483
484 /// The level of the last diagnostic emitted.
485 ///
486 /// This is used to emit continuation diagnostics with the same level as the
487 /// diagnostic that they follow.
488 DiagnosticIDs::Level LastDiagLevel;
489
490 /// Number of warnings reported
491 unsigned NumWarnings;
492
493 /// Number of errors reported
494 unsigned NumErrors;
495
496 /// A function pointer that converts an opaque diagnostic
497 /// argument to a strings.
498 ///
499 /// This takes the modifiers and argument that was present in the diagnostic.
500 ///
501 /// The PrevArgs array indicates the previous arguments formatted for this
502 /// diagnostic. Implementations of this function can use this information to
503 /// avoid redundancy across arguments.
504 ///
505 /// This is a hack to avoid a layering violation between libbasic and libsema.
506 using ArgToStringFnTy = void (*)(
507 ArgumentKind Kind, intptr_t Val,
508 StringRef Modifier, StringRef Argument,
509 ArrayRef<ArgumentValue> PrevArgs,
510 SmallVectorImpl<char> &Output,
511 void *Cookie,
512 ArrayRef<intptr_t> QualTypeVals);
513
514 void *ArgToStringCookie = nullptr;
515 ArgToStringFnTy ArgToStringFn;
516
517 /// ID of the "delayed" diagnostic, which is a (typically
518 /// fatal) diagnostic that had to be delayed because it was found
519 /// while emitting another diagnostic.
520 unsigned DelayedDiagID;
521
522 /// First string argument for the delayed diagnostic.
523 std::string DelayedDiagArg1;
524
525 /// Second string argument for the delayed diagnostic.
526 std::string DelayedDiagArg2;
527
528 /// Third string argument for the delayed diagnostic.
529 std::string DelayedDiagArg3;
530
531 /// Optional flag value.
532 ///
533 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
534 /// -Rpass=<value>. The content of this string is emitted after the flag name
535 /// and '='.
536 std::string FlagValue;
537
538public:
539 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
540 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
541 DiagnosticConsumer *client = nullptr,
542 bool ShouldOwnClient = true);
543 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
544 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
545 ~DiagnosticsEngine();
546
547 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump() const;
548 LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void dump(StringRef DiagName) const;
549
550 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
551 return Diags;
552 }
553
554 /// Retrieve the diagnostic options.
555 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
556
557 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
558
559 /// Get the current set of diagnostic mappings.
560 diag_mapping_range getDiagnosticMappings() const {
561 const DiagState &DS = *GetCurDiagState();
562 return diag_mapping_range(DS.begin(), DS.end());
563 }
564
565 DiagnosticConsumer *getClient() { return Client; }
566 const DiagnosticConsumer *getClient() const { return Client; }
567
568 /// Determine whether this \c DiagnosticsEngine object own its client.
569 bool ownsClient() const { return Owner != nullptr; }
570
571 /// Return the current diagnostic client along with ownership of that
572 /// client.
573 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
574
575 bool hasSourceManager() const { return SourceMgr != nullptr; }
576
577 SourceManager &getSourceManager() const {
578 assert(SourceMgr && "SourceManager not set!")(static_cast <bool> (SourceMgr && "SourceManager not set!"
) ? void (0) : __assert_fail ("SourceMgr && \"SourceManager not set!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 578, __extension__ __PRETTY_FUNCTION__))
;
579 return *SourceMgr;
580 }
581
582 void setSourceManager(SourceManager *SrcMgr) {
583 assert(DiagStatesByLoc.empty() &&(static_cast <bool> (DiagStatesByLoc.empty() &&
"Leftover diag state from a different SourceManager.") ? void
(0) : __assert_fail ("DiagStatesByLoc.empty() && \"Leftover diag state from a different SourceManager.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 584, __extension__ __PRETTY_FUNCTION__))
584 "Leftover diag state from a different SourceManager.")(static_cast <bool> (DiagStatesByLoc.empty() &&
"Leftover diag state from a different SourceManager.") ? void
(0) : __assert_fail ("DiagStatesByLoc.empty() && \"Leftover diag state from a different SourceManager.\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 584, __extension__ __PRETTY_FUNCTION__))
;
585 SourceMgr = SrcMgr;
586 }
587
588 //===--------------------------------------------------------------------===//
589 // DiagnosticsEngine characterization methods, used by a client to customize
590 // how diagnostics are emitted.
591 //
592
593 /// Copies the current DiagMappings and pushes the new copy
594 /// onto the top of the stack.
595 void pushMappings(SourceLocation Loc);
596
597 /// Pops the current DiagMappings off the top of the stack,
598 /// causing the new top of the stack to be the active mappings.
599 ///
600 /// \returns \c true if the pop happens, \c false if there is only one
601 /// DiagMapping on the stack.
602 bool popMappings(SourceLocation Loc);
603
604 /// Set the diagnostic client associated with this diagnostic object.
605 ///
606 /// \param ShouldOwnClient true if the diagnostic object should take
607 /// ownership of \c client.
608 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
609
610 /// Specify a limit for the number of errors we should
611 /// emit before giving up.
612 ///
613 /// Zero disables the limit.
614 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
615
616 /// Specify the maximum number of template instantiation
617 /// notes to emit along with a given diagnostic.
618 void setTemplateBacktraceLimit(unsigned Limit) {
619 TemplateBacktraceLimit = Limit;
620 }
621
622 /// Retrieve the maximum number of template instantiation
623 /// notes to emit along with a given diagnostic.
624 unsigned getTemplateBacktraceLimit() const {
625 return TemplateBacktraceLimit;
626 }
627
628 /// Specify the maximum number of constexpr evaluation
629 /// notes to emit along with a given diagnostic.
630 void setConstexprBacktraceLimit(unsigned Limit) {
631 ConstexprBacktraceLimit = Limit;
632 }
633
634 /// Retrieve the maximum number of constexpr evaluation
635 /// notes to emit along with a given diagnostic.
636 unsigned getConstexprBacktraceLimit() const {
637 return ConstexprBacktraceLimit;
638 }
639
640 /// When set to true, any unmapped warnings are ignored.
641 ///
642 /// If this and WarningsAsErrors are both set, then this one wins.
643 void setIgnoreAllWarnings(bool Val) {
644 GetCurDiagState()->IgnoreAllWarnings = Val;
645 }
646 bool getIgnoreAllWarnings() const {
647 return GetCurDiagState()->IgnoreAllWarnings;
648 }
649
650 /// When set to true, any unmapped ignored warnings are no longer
651 /// ignored.
652 ///
653 /// If this and IgnoreAllWarnings are both set, then that one wins.
654 void setEnableAllWarnings(bool Val) {
655 GetCurDiagState()->EnableAllWarnings = Val;
656 }
657 bool getEnableAllWarnings() const {
658 return GetCurDiagState()->EnableAllWarnings;
659 }
660
661 /// When set to true, any warnings reported are issued as errors.
662 void setWarningsAsErrors(bool Val) {
663 GetCurDiagState()->WarningsAsErrors = Val;
664 }
665 bool getWarningsAsErrors() const {
666 return GetCurDiagState()->WarningsAsErrors;
667 }
668
669 /// When set to true, any error reported is made a fatal error.
670 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
671 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
672
673 /// \brief When set to true, any fatal error reported is made an error.
674 ///
675 /// This setting takes precedence over the setErrorsAsFatal setting above.
676 void setFatalsAsError(bool Val) { FatalsAsError = Val; }
677 bool getFatalsAsError() const { return FatalsAsError; }
678
679 /// When set to true mask warnings that come from system headers.
680 void setSuppressSystemWarnings(bool Val) {
681 GetCurDiagState()->SuppressSystemWarnings = Val;
682 }
683 bool getSuppressSystemWarnings() const {
684 return GetCurDiagState()->SuppressSystemWarnings;
685 }
686
687 /// Suppress all diagnostics, to silence the front end when we
688 /// know that we don't want any more diagnostics to be passed along to the
689 /// client
690 void setSuppressAllDiagnostics(bool Val) { SuppressAllDiagnostics = Val; }
691 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
692
693 /// Set type eliding, to skip outputting same types occurring in
694 /// template types.
695 void setElideType(bool Val) { ElideType = Val; }
696 bool getElideType() { return ElideType; }
697
698 /// Set tree printing, to outputting the template difference in a
699 /// tree format.
700 void setPrintTemplateTree(bool Val) { PrintTemplateTree = Val; }
701 bool getPrintTemplateTree() { return PrintTemplateTree; }
702
703 /// Set color printing, so the type diffing will inject color markers
704 /// into the output.
705 void setShowColors(bool Val) { ShowColors = Val; }
706 bool getShowColors() { return ShowColors; }
707
708 /// Specify which overload candidates to show when overload resolution
709 /// fails.
710 ///
711 /// By default, we show all candidates.
712 void setShowOverloads(OverloadsShown Val) {
713 ShowOverloads = Val;
714 }
715 OverloadsShown getShowOverloads() const { return ShowOverloads; }
716
717 /// When a call or operator fails, print out up to this many candidate
718 /// overloads as suggestions.
719 ///
720 /// With Ovl_Best, we set a high limit for the first nontrivial overload set
721 /// we print, and a lower limit for later sets. This way the user has a
722 /// chance of diagnosing at least one callsite in their program without
723 /// having to recompile with -fshow-overloads=all.
724 unsigned getNumOverloadCandidatesToShow() const {
725 switch (getShowOverloads()) {
726 case Ovl_All:
727 // INT_MAX rather than UINT_MAX so that we don't have to think about the
728 // effect of implicit conversions on this value. In practice we'll never
729 // hit 2^31 candidates anyway.
730 return std::numeric_limits<int>::max();
731 case Ovl_Best:
732 return NumOverloadsToShow;
733 }
734 llvm_unreachable("invalid OverloadsShown kind")::llvm::llvm_unreachable_internal("invalid OverloadsShown kind"
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 734)
;
735 }
736
737 /// Call this after showing N overload candidates. This influences the value
738 /// returned by later calls to getNumOverloadCandidatesToShow().
739 void overloadCandidatesShown(unsigned N) {
740 // Current heuristic: Start out with a large value for NumOverloadsToShow,
741 // and then once we print one nontrivially-large overload set, decrease it
742 // for future calls.
743 if (N > 4) {
744 NumOverloadsToShow = 4;
745 }
746 }
747
748 /// Pretend that the last diagnostic issued was ignored, so any
749 /// subsequent notes will be suppressed, or restore a prior ignoring
750 /// state after ignoring some diagnostics and their notes, possibly in
751 /// the middle of another diagnostic.
752 ///
753 /// This can be used by clients who suppress diagnostics themselves.
754 void setLastDiagnosticIgnored(bool Ignored) {
755 if (LastDiagLevel == DiagnosticIDs::Fatal)
756 FatalErrorOccurred = true;
757 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
758 }
759
760 /// Determine whether the previous diagnostic was ignored. This can
761 /// be used by clients that want to determine whether notes attached to a
762 /// diagnostic will be suppressed.
763 bool isLastDiagnosticIgnored() const {
764 return LastDiagLevel == DiagnosticIDs::Ignored;
765 }
766
767 /// Controls whether otherwise-unmapped extension diagnostics are
768 /// mapped onto ignore/warning/error.
769 ///
770 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
771 void setExtensionHandlingBehavior(diag::Severity H) {
772 GetCurDiagState()->ExtBehavior = H;
773 }
774 diag::Severity getExtensionHandlingBehavior() const {
775 return GetCurDiagState()->ExtBehavior;
776 }
777
778 /// Counter bumped when an __extension__ block is/ encountered.
779 ///
780 /// When non-zero, all extension diagnostics are entirely silenced, no
781 /// matter how they are mapped.
782 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
783 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
784 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
785
786 /// This allows the client to specify that certain warnings are
787 /// ignored.
788 ///
789 /// Notes can never be mapped, errors can only be mapped to fatal, and
790 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
791 ///
792 /// \param Loc The source location that this change of diagnostic state should
793 /// take affect. It can be null if we are setting the latest state.
794 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
795
796 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
797 /// have the specified mapping.
798 ///
799 /// \returns true (and ignores the request) if "Group" was unknown, false
800 /// otherwise.
801 ///
802 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
803 /// state of the -Wfoo group and vice versa.
804 ///
805 /// \param Loc The source location that this change of diagnostic state should
806 /// take affect. It can be null if we are setting the state from command-line.
807 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
808 diag::Severity Map,
809 SourceLocation Loc = SourceLocation());
810
811 /// Set the warning-as-error flag for the given diagnostic group.
812 ///
813 /// This function always only operates on the current diagnostic state.
814 ///
815 /// \returns True if the given group is unknown, false otherwise.
816 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
817
818 /// Set the error-as-fatal flag for the given diagnostic group.
819 ///
820 /// This function always only operates on the current diagnostic state.
821 ///
822 /// \returns True if the given group is unknown, false otherwise.
823 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
824
825 /// Add the specified mapping to all diagnostics of the specified
826 /// flavor.
827 ///
828 /// Mainly to be used by -Wno-everything to disable all warnings but allow
829 /// subsequent -W options to enable specific warnings.
830 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
831 SourceLocation Loc = SourceLocation());
832
833 bool hasErrorOccurred() const { return ErrorOccurred; }
834
835 /// Errors that actually prevent compilation, not those that are
836 /// upgraded from a warning by -Werror.
837 bool hasUncompilableErrorOccurred() const {
838 return UncompilableErrorOccurred;
839 }
840 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
841
842 /// Determine whether any kind of unrecoverable error has occurred.
843 bool hasUnrecoverableErrorOccurred() const {
844 return FatalErrorOccurred || UnrecoverableErrorOccurred;
845 }
846
847 unsigned getNumErrors() const { return NumErrors; }
848 unsigned getNumWarnings() const { return NumWarnings; }
849
850 void setNumWarnings(unsigned NumWarnings) {
851 this->NumWarnings = NumWarnings;
852 }
853
854 /// Return an ID for a diagnostic with the specified format string and
855 /// level.
856 ///
857 /// If this is the first request for this diagnostic, it is registered and
858 /// created, otherwise the existing ID is returned.
859 ///
860 /// \param FormatString A fixed diagnostic format string that will be hashed
861 /// and mapped to a unique DiagID.
862 template <unsigned N>
863 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
864 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
865 StringRef(FormatString, N - 1));
866 }
867
868 /// Converts a diagnostic argument (as an intptr_t) into the string
869 /// that represents it.
870 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
871 StringRef Modifier, StringRef Argument,
872 ArrayRef<ArgumentValue> PrevArgs,
873 SmallVectorImpl<char> &Output,
874 ArrayRef<intptr_t> QualTypeVals) const {
875 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
876 ArgToStringCookie, QualTypeVals);
877 }
878
879 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
880 ArgToStringFn = Fn;
881 ArgToStringCookie = Cookie;
882 }
883
884 /// Note that the prior diagnostic was emitted by some other
885 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
886 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
887 LastDiagLevel = Other.LastDiagLevel;
888 }
889
890 /// Reset the state of the diagnostic object to its initial
891 /// configuration.
892 void Reset();
893
894 //===--------------------------------------------------------------------===//
895 // DiagnosticsEngine classification and reporting interfaces.
896 //
897
898 /// Determine whether the diagnostic is known to be ignored.
899 ///
900 /// This can be used to opportunistically avoid expensive checks when it's
901 /// known for certain that the diagnostic has been suppressed at the
902 /// specified location \p Loc.
903 ///
904 /// \param Loc The source location we are interested in finding out the
905 /// diagnostic state. Can be null in order to query the latest state.
906 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
907 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
908 diag::Severity::Ignored;
909 }
910
911 /// Based on the way the client configured the DiagnosticsEngine
912 /// object, classify the specified diagnostic ID into a Level, consumable by
913 /// the DiagnosticConsumer.
914 ///
915 /// To preserve invariant assumptions, this function should not be used to
916 /// influence parse or semantic analysis actions. Instead consider using
917 /// \c isIgnored().
918 ///
919 /// \param Loc The source location we are interested in finding out the
920 /// diagnostic state. Can be null in order to query the latest state.
921 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
922 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
923 }
924
925 /// Issue the message to the client.
926 ///
927 /// This actually returns an instance of DiagnosticBuilder which emits the
928 /// diagnostics (through @c ProcessDiag) when it is destroyed.
929 ///
930 /// \param DiagID A member of the @c diag::kind enum.
931 /// \param Loc Represents the source location associated with the diagnostic,
932 /// which can be an invalid location if no position information is available.
933 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
934 inline DiagnosticBuilder Report(unsigned DiagID);
935
936 void Report(const StoredDiagnostic &storedDiag);
937
938 /// Determine whethere there is already a diagnostic in flight.
939 bool isDiagnosticInFlight() const {
940 return CurDiagID != std::numeric_limits<unsigned>::max();
941 }
942
943 /// Set the "delayed" diagnostic that will be emitted once
944 /// the current diagnostic completes.
945 ///
946 /// If a diagnostic is already in-flight but the front end must
947 /// report a problem (e.g., with an inconsistent file system
948 /// state), this routine sets a "delayed" diagnostic that will be
949 /// emitted after the current diagnostic completes. This should
950 /// only be used for fatal errors detected at inconvenient
951 /// times. If emitting a delayed diagnostic causes a second delayed
952 /// diagnostic to be introduced, that second delayed diagnostic
953 /// will be ignored.
954 ///
955 /// \param DiagID The ID of the diagnostic being delayed.
956 ///
957 /// \param Arg1 A string argument that will be provided to the
958 /// diagnostic. A copy of this string will be stored in the
959 /// DiagnosticsEngine object itself.
960 ///
961 /// \param Arg2 A string argument that will be provided to the
962 /// diagnostic. A copy of this string will be stored in the
963 /// DiagnosticsEngine object itself.
964 ///
965 /// \param Arg3 A string argument that will be provided to the
966 /// diagnostic. A copy of this string will be stored in the
967 /// DiagnosticsEngine object itself.
968 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
969 StringRef Arg2 = "", StringRef Arg3 = "");
970
971 /// Clear out the current diagnostic.
972 void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
973
974 /// Return the value associated with this diagnostic flag.
975 StringRef getFlagValue() const { return FlagValue; }
976
977private:
978 // This is private state used by DiagnosticBuilder. We put it here instead of
979 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
980 // object. This implementation choice means that we can only have one
981 // diagnostic "in flight" at a time, but this seems to be a reasonable
982 // tradeoff to keep these objects small. Assertions verify that only one
983 // diagnostic is in flight at a time.
984 friend class Diagnostic;
985 friend class DiagnosticBuilder;
986 friend class DiagnosticErrorTrap;
987 friend class DiagnosticIDs;
988 friend class PartialDiagnostic;
989
990 /// Report the delayed diagnostic.
991 void ReportDelayed();
992
993 /// The location of the current diagnostic that is in flight.
994 SourceLocation CurDiagLoc;
995
996 /// The ID of the current diagnostic that is in flight.
997 ///
998 /// This is set to std::numeric_limits<unsigned>::max() when there is no
999 /// diagnostic in flight.
1000 unsigned CurDiagID;
1001
1002 enum {
1003 /// The maximum number of arguments we can hold.
1004 ///
1005 /// We currently only support up to 10 arguments (%0-%9). A single
1006 /// diagnostic with more than that almost certainly has to be simplified
1007 /// anyway.
1008 MaxArguments = DiagnosticStorage::MaxArguments,
1009 };
1010
1011 DiagnosticStorage DiagStorage;
1012
1013 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
1014 bool isPragma = L.isValid();
1015 DiagnosticMapping Mapping =
1016 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
1017
1018 // If this is a pragma mapping, then set the diagnostic mapping flags so
1019 // that we override command line options.
1020 if (isPragma) {
1021 Mapping.setNoWarningAsError(true);
1022 Mapping.setNoErrorAsFatal(true);
1023 }
1024
1025 return Mapping;
1026 }
1027
1028 /// Used to report a diagnostic that is finally fully formed.
1029 ///
1030 /// \returns true if the diagnostic was emitted, false if it was suppressed.
1031 bool ProcessDiag() {
1032 return Diags->ProcessDiag(*this);
1033 }
1034
1035 /// @name Diagnostic Emission
1036 /// @{
1037protected:
1038 friend class ASTReader;
1039 friend class ASTWriter;
1040
1041 // Sema requires access to the following functions because the current design
1042 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
1043 // access us directly to ensure we minimize the emitted code for the common
1044 // Sema::Diag() patterns.
1045 friend class Sema;
1046
1047 /// Emit the current diagnostic and clear the diagnostic state.
1048 ///
1049 /// \param Force Emit the diagnostic regardless of suppression settings.
1050 bool EmitCurrentDiagnostic(bool Force = false);
1051
1052 unsigned getCurrentDiagID() const { return CurDiagID; }
1053
1054 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
1055
1056 /// @}
1057};
1058
1059/// RAII class that determines when any errors have occurred
1060/// between the time the instance was created and the time it was
1061/// queried.
1062///
1063/// Note that you almost certainly do not want to use this. It's usually
1064/// meaningless to ask whether a particular scope triggered an error message,
1065/// because error messages outside that scope can mark things invalid (or cause
1066/// us to reach an error limit), which can suppress errors within that scope.
1067class DiagnosticErrorTrap {
1068 DiagnosticsEngine &Diag;
1069 unsigned NumErrors;
1070 unsigned NumUnrecoverableErrors;
1071
1072public:
1073 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1074 : Diag(Diag) { reset(); }
1075
1076 /// Determine whether any errors have occurred since this
1077 /// object instance was created.
1078 bool hasErrorOccurred() const {
1079 return Diag.TrapNumErrorsOccurred > NumErrors;
1080 }
1081
1082 /// Determine whether any unrecoverable errors have occurred since this
1083 /// object instance was created.
1084 bool hasUnrecoverableErrorOccurred() const {
1085 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1086 }
1087
1088 /// Set to initial state of "no errors occurred".
1089 void reset() {
1090 NumErrors = Diag.TrapNumErrorsOccurred;
1091 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1092 }
1093};
1094
1095/// The streaming interface shared between DiagnosticBuilder and
1096/// PartialDiagnostic. This class is not intended to be constructed directly
1097/// but only as base class of DiagnosticBuilder and PartialDiagnostic builder.
1098///
1099/// Any new type of argument accepted by DiagnosticBuilder and PartialDiagnostic
1100/// should be implemented as a '<<' operator of StreamingDiagnostic, e.g.
1101///
1102/// const StreamingDiagnostic&
1103/// operator<<(const StreamingDiagnostic&, NewArgType);
1104///
1105class StreamingDiagnostic {
1106public:
1107 /// An allocator for DiagnosticStorage objects, which uses a small cache to
1108 /// objects, used to reduce malloc()/free() traffic for partial diagnostics.
1109 class DiagStorageAllocator {
1110 static const unsigned NumCached = 16;
1111 DiagnosticStorage Cached[NumCached];
1112 DiagnosticStorage *FreeList[NumCached];
1113 unsigned NumFreeListEntries;
1114
1115 public:
1116 DiagStorageAllocator();
1117 ~DiagStorageAllocator();
1118
1119 /// Allocate new storage.
1120 DiagnosticStorage *Allocate() {
1121 if (NumFreeListEntries == 0)
1122 return new DiagnosticStorage;
1123
1124 DiagnosticStorage *Result = FreeList[--NumFreeListEntries];
1125 Result->NumDiagArgs = 0;
1126 Result->DiagRanges.clear();
1127 Result->FixItHints.clear();
1128 return Result;
1129 }
1130
1131 /// Free the given storage object.
1132 void Deallocate(DiagnosticStorage *S) {
1133 if (S >= Cached && S <= Cached + NumCached) {
33
Assuming 'S' is < field 'Cached'
1134 FreeList[NumFreeListEntries++] = S;
1135 return;
1136 }
1137
1138 delete S;
34
Memory is released
1139 }
1140 };
1141
1142protected:
1143 mutable DiagnosticStorage *DiagStorage = nullptr;
1144
1145 /// Allocator used to allocate storage for this diagnostic.
1146 DiagStorageAllocator *Allocator = nullptr;
1147
1148public:
1149 /// Retrieve storage for this particular diagnostic.
1150 DiagnosticStorage *getStorage() const {
1151 if (DiagStorage)
1152 return DiagStorage;
1153
1154 assert(Allocator)(static_cast <bool> (Allocator) ? void (0) : __assert_fail
("Allocator", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1154, __extension__ __PRETTY_FUNCTION__))
;
1155 DiagStorage = Allocator->Allocate();
1156 return DiagStorage;
1157 }
1158
1159 void freeStorage() {
1160 if (!DiagStorage)
27
Assuming field 'DiagStorage' is non-null
28
Taking false branch
1161 return;
1162
1163 // The hot path for PartialDiagnostic is when we just used it to wrap an ID
1164 // (typically so we have the flexibility of passing a more complex
1165 // diagnostic into the callee, but that does not commonly occur).
1166 //
1167 // Split this out into a slow function for silly compilers (*cough*) which
1168 // can't do decent partial inlining.
1169 freeStorageSlow();
29
Calling 'StreamingDiagnostic::freeStorageSlow'
36
Returning; memory was released
1170 }
1171
1172 void freeStorageSlow() {
1173 if (!Allocator)
30
Assuming field 'Allocator' is non-null
31
Taking false branch
1174 return;
1175 Allocator->Deallocate(DiagStorage);
32
Calling 'DiagStorageAllocator::Deallocate'
35
Returning; memory was released via 1st parameter
1176 DiagStorage = nullptr;
1177 }
1178
1179 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1180 if (!DiagStorage
45.1
Field 'DiagStorage' is non-null
45.1
Field 'DiagStorage' is non-null
)
46
Taking false branch
1181 DiagStorage = getStorage();
1182
1183 assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < DiagnosticStorage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1184, __extension__ __PRETTY_FUNCTION__))
47
Use of memory after it is freed
1184 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < DiagnosticStorage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1184, __extension__ __PRETTY_FUNCTION__))
;
1185 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] = Kind;
1186 DiagStorage->DiagArgumentsVal[DiagStorage->NumDiagArgs++] = V;
1187 }
1188
1189 void AddString(StringRef V) const {
1190 if (!DiagStorage)
1191 DiagStorage = getStorage();
1192
1193 assert(DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments &&(static_cast <bool> (DiagStorage->NumDiagArgs < DiagnosticStorage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1194, __extension__ __PRETTY_FUNCTION__))
1194 "Too many arguments to diagnostic!")(static_cast <bool> (DiagStorage->NumDiagArgs < DiagnosticStorage
::MaxArguments && "Too many arguments to diagnostic!"
) ? void (0) : __assert_fail ("DiagStorage->NumDiagArgs < DiagnosticStorage::MaxArguments && \"Too many arguments to diagnostic!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1194, __extension__ __PRETTY_FUNCTION__))
;
1195 DiagStorage->DiagArgumentsKind[DiagStorage->NumDiagArgs] =
1196 DiagnosticsEngine::ak_std_string;
1197 DiagStorage->DiagArgumentsStr[DiagStorage->NumDiagArgs++] = std::string(V);
1198 }
1199
1200 void AddSourceRange(const CharSourceRange &R) const {
1201 if (!DiagStorage)
1202 DiagStorage = getStorage();
1203
1204 DiagStorage->DiagRanges.push_back(R);
1205 }
1206
1207 void AddFixItHint(const FixItHint &Hint) const {
1208 if (Hint.isNull())
1209 return;
1210
1211 if (!DiagStorage)
1212 DiagStorage = getStorage();
1213
1214 DiagStorage->FixItHints.push_back(Hint);
1215 }
1216
1217 /// Conversion of StreamingDiagnostic to bool always returns \c true.
1218 ///
1219 /// This allows is to be used in boolean error contexts (where \c true is
1220 /// used to indicate that an error has occurred), like:
1221 /// \code
1222 /// return Diag(...);
1223 /// \endcode
1224 operator bool() const { return true; }
1225
1226protected:
1227 StreamingDiagnostic() = default;
1228
1229 /// Construct with an external storage not owned by itself. The allocator
1230 /// is a null pointer in this case.
1231 explicit StreamingDiagnostic(DiagnosticStorage *Storage)
1232 : DiagStorage(Storage) {}
1233
1234 /// Construct with a storage allocator which will manage the storage. The
1235 /// allocator is not a null pointer in this case.
1236 explicit StreamingDiagnostic(DiagStorageAllocator &Alloc)
1237 : Allocator(&Alloc) {}
1238
1239 StreamingDiagnostic(const StreamingDiagnostic &Diag) = default;
1240 StreamingDiagnostic(StreamingDiagnostic &&Diag) = default;
1241
1242 ~StreamingDiagnostic() { freeStorage(); }
26
Calling 'StreamingDiagnostic::freeStorage'
37
Returning; memory was released
1243};
1244
1245//===----------------------------------------------------------------------===//
1246// DiagnosticBuilder
1247//===----------------------------------------------------------------------===//
1248
1249/// A little helper class used to produce diagnostics.
1250///
1251/// This is constructed by the DiagnosticsEngine::Report method, and
1252/// allows insertion of extra information (arguments and source ranges) into
1253/// the currently "in flight" diagnostic. When the temporary for the builder
1254/// is destroyed, the diagnostic is issued.
1255///
1256/// Note that many of these will be created as temporary objects (many call
1257/// sites), so we want them to be small and we never want their address taken.
1258/// This ensures that compilers with somewhat reasonable optimizers will promote
1259/// the common fields to registers, eliminating increments of the NumArgs field,
1260/// for example.
1261class DiagnosticBuilder : public StreamingDiagnostic {
1262 friend class DiagnosticsEngine;
1263 friend class PartialDiagnostic;
1264
1265 mutable DiagnosticsEngine *DiagObj = nullptr;
1266
1267 /// Status variable indicating if this diagnostic is still active.
1268 ///
1269 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1270 // but LLVM is not currently smart enough to eliminate the null check that
1271 // Emit() would end up with if we used that as our status variable.
1272 mutable bool IsActive = false;
1273
1274 /// Flag indicating that this diagnostic is being emitted via a
1275 /// call to ForceEmit.
1276 mutable bool IsForceEmit = false;
1277
1278 DiagnosticBuilder() = default;
1279
1280 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1281 : StreamingDiagnostic(&diagObj->DiagStorage), DiagObj(diagObj),
1282 IsActive(true) {
1283 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!")(static_cast <bool> (diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!"
) ? void (0) : __assert_fail ("diagObj && \"DiagnosticBuilder requires a valid DiagnosticsEngine!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1283, __extension__ __PRETTY_FUNCTION__))
;
1284 assert(DiagStorage &&(static_cast <bool> (DiagStorage && "DiagnosticBuilder requires a valid DiagnosticStorage!"
) ? void (0) : __assert_fail ("DiagStorage && \"DiagnosticBuilder requires a valid DiagnosticStorage!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1285, __extension__ __PRETTY_FUNCTION__))
1285 "DiagnosticBuilder requires a valid DiagnosticStorage!")(static_cast <bool> (DiagStorage && "DiagnosticBuilder requires a valid DiagnosticStorage!"
) ? void (0) : __assert_fail ("DiagStorage && \"DiagnosticBuilder requires a valid DiagnosticStorage!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1285, __extension__ __PRETTY_FUNCTION__))
;
1286 DiagStorage->NumDiagArgs = 0;
1287 DiagStorage->DiagRanges.clear();
1288 DiagStorage->FixItHints.clear();
1289 }
1290
1291protected:
1292 /// Clear out the current diagnostic.
1293 void Clear() const {
1294 DiagObj = nullptr;
1295 IsActive = false;
1296 IsForceEmit = false;
1297 }
1298
1299 /// Determine whether this diagnostic is still active.
1300 bool isActive() const { return IsActive; }
1301
1302 /// Force the diagnostic builder to emit the diagnostic now.
1303 ///
1304 /// Once this function has been called, the DiagnosticBuilder object
1305 /// should not be used again before it is destroyed.
1306 ///
1307 /// \returns true if a diagnostic was emitted, false if the
1308 /// diagnostic was suppressed.
1309 bool Emit() {
1310 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1311 // (or by a subclass, as in SemaDiagnosticBuilder).
1312 if (!isActive()) return false;
1313
1314 // Process the diagnostic.
1315 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1316
1317 // This diagnostic is dead.
1318 Clear();
1319
1320 return Result;
1321 }
1322
1323public:
1324 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1325 /// input and neuters it.
1326 DiagnosticBuilder(const DiagnosticBuilder &D) : StreamingDiagnostic() {
1327 DiagObj = D.DiagObj;
1328 DiagStorage = D.DiagStorage;
1329 IsActive = D.IsActive;
1330 IsForceEmit = D.IsForceEmit;
1331 D.Clear();
1332 }
1333
1334 template <typename T> const DiagnosticBuilder &operator<<(const T &V) const {
1335 assert(isActive() && "Clients must not add to cleared diagnostic!")(static_cast <bool> (isActive() && "Clients must not add to cleared diagnostic!"
) ? void (0) : __assert_fail ("isActive() && \"Clients must not add to cleared diagnostic!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1335, __extension__ __PRETTY_FUNCTION__))
;
1336 const StreamingDiagnostic &DB = *this;
1337 DB << V;
1338 return *this;
1339 }
1340
1341 // It is necessary to limit this to rvalue reference to avoid calling this
1342 // function with a bitfield lvalue argument since non-const reference to
1343 // bitfield is not allowed.
1344 template <typename T, typename = typename std::enable_if<
1345 !std::is_lvalue_reference<T>::value>::type>
1346 const DiagnosticBuilder &operator<<(T &&V) const {
1347 assert(isActive() && "Clients must not add to cleared diagnostic!")(static_cast <bool> (isActive() && "Clients must not add to cleared diagnostic!"
) ? void (0) : __assert_fail ("isActive() && \"Clients must not add to cleared diagnostic!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1347, __extension__ __PRETTY_FUNCTION__))
;
42
Assuming the condition is true
43
'?' condition is true
1348 const StreamingDiagnostic &DB = *this;
1349 DB << std::move(V);
44
Calling 'operator<<'
1350 return *this;
1351 }
1352
1353 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1354
1355 /// Emits the diagnostic.
1356 ~DiagnosticBuilder() { Emit(); }
25
Calling '~StreamingDiagnostic'
38
Returning from '~StreamingDiagnostic'
1357
1358 /// Forces the diagnostic to be emitted.
1359 const DiagnosticBuilder &setForceEmit() const {
1360 IsForceEmit = true;
1361 return *this;
1362 }
1363
1364 void addFlagValue(StringRef V) const { DiagObj->FlagValue = std::string(V); }
1365};
1366
1367struct AddFlagValue {
1368 StringRef Val;
1369
1370 explicit AddFlagValue(StringRef V) : Val(V) {}
1371};
1372
1373/// Register a value for the flag in the current diagnostic. This
1374/// value will be shown as the suffix "=value" after the flag name. It is
1375/// useful in cases where the diagnostic flag accepts values (e.g.,
1376/// -Rpass or -Wframe-larger-than).
1377inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1378 const AddFlagValue V) {
1379 DB.addFlagValue(V.Val);
1380 return DB;
1381}
1382
1383inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1384 StringRef S) {
1385 DB.AddString(S);
1386 return DB;
1387}
1388
1389inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1390 const char *Str) {
1391 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1392 DiagnosticsEngine::ak_c_string);
1393 return DB;
1394}
1395
1396inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1397 int I) {
1398 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1399 return DB;
1400}
1401
1402// We use enable_if here to prevent that this overload is selected for
1403// pointers or other arguments that are implicitly convertible to bool.
1404template <typename T>
1405inline std::enable_if_t<std::is_same<T, bool>::value,
1406 const StreamingDiagnostic &>
1407operator<<(const StreamingDiagnostic &DB, T I) {
1408 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1409 return DB;
1410}
1411
1412inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1413 unsigned I) {
1414 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1415 return DB;
1416}
1417
1418inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1419 tok::TokenKind I) {
1420 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
45
Calling 'StreamingDiagnostic::AddTaggedVal'
1421 return DB;
1422}
1423
1424inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1425 const IdentifierInfo *II) {
1426 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1427 DiagnosticsEngine::ak_identifierinfo);
1428 return DB;
1429}
1430
1431// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1432// so that we only match those arguments that are (statically) DeclContexts;
1433// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1434// match.
1435template <typename T>
1436inline std::enable_if_t<
1437 std::is_same<std::remove_const_t<T>, DeclContext>::value,
1438 const StreamingDiagnostic &>
1439operator<<(const StreamingDiagnostic &DB, T *DC) {
1440 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1441 DiagnosticsEngine::ak_declcontext);
1442 return DB;
1443}
1444
1445inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1446 SourceRange R) {
1447 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1448 return DB;
1449}
1450
1451inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1452 ArrayRef<SourceRange> Ranges) {
1453 for (SourceRange R : Ranges)
1454 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1455 return DB;
1456}
1457
1458inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1459 const CharSourceRange &R) {
1460 DB.AddSourceRange(R);
1461 return DB;
1462}
1463
1464inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1465 const FixItHint &Hint) {
1466 DB.AddFixItHint(Hint);
1467 return DB;
1468}
1469
1470inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1471 ArrayRef<FixItHint> Hints) {
1472 for (const FixItHint &Hint : Hints)
1473 DB.AddFixItHint(Hint);
1474 return DB;
1475}
1476
1477inline const StreamingDiagnostic &
1478operator<<(const StreamingDiagnostic &DB,
1479 const llvm::Optional<SourceRange> &Opt) {
1480 if (Opt)
1481 DB << *Opt;
1482 return DB;
1483}
1484
1485inline const StreamingDiagnostic &
1486operator<<(const StreamingDiagnostic &DB,
1487 const llvm::Optional<CharSourceRange> &Opt) {
1488 if (Opt)
1489 DB << *Opt;
1490 return DB;
1491}
1492
1493inline const StreamingDiagnostic &
1494operator<<(const StreamingDiagnostic &DB,
1495 const llvm::Optional<FixItHint> &Opt) {
1496 if (Opt)
1497 DB << *Opt;
1498 return DB;
1499}
1500
1501/// A nullability kind paired with a bit indicating whether it used a
1502/// context-sensitive keyword.
1503using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1504
1505const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1506 DiagNullabilityKind nullability);
1507
1508inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1509 unsigned DiagID) {
1510 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&(static_cast <bool> (CurDiagID == std::numeric_limits<
unsigned>::max() && "Multiple diagnostics in flight at once!"
) ? void (0) : __assert_fail ("CurDiagID == std::numeric_limits<unsigned>::max() && \"Multiple diagnostics in flight at once!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1511, __extension__ __PRETTY_FUNCTION__))
1511 "Multiple diagnostics in flight at once!")(static_cast <bool> (CurDiagID == std::numeric_limits<
unsigned>::max() && "Multiple diagnostics in flight at once!"
) ? void (0) : __assert_fail ("CurDiagID == std::numeric_limits<unsigned>::max() && \"Multiple diagnostics in flight at once!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1511, __extension__ __PRETTY_FUNCTION__))
;
1512 CurDiagLoc = Loc;
1513 CurDiagID = DiagID;
1514 FlagValue.clear();
1515 return DiagnosticBuilder(this);
1516}
1517
1518const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1519 llvm::Error &&E);
1520
1521inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1522 return Report(SourceLocation(), DiagID);
1523}
1524
1525//===----------------------------------------------------------------------===//
1526// Diagnostic
1527//===----------------------------------------------------------------------===//
1528
1529/// A little helper class (which is basically a smart pointer that forwards
1530/// info from DiagnosticsEngine) that allows clients to enquire about the
1531/// currently in-flight diagnostic.
1532class Diagnostic {
1533 const DiagnosticsEngine *DiagObj;
1534 StringRef StoredDiagMessage;
1535
1536public:
1537 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1538 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1539 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1540
1541 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1542 unsigned getID() const { return DiagObj->CurDiagID; }
1543 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1544 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1545 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1546
1547 unsigned getNumArgs() const { return DiagObj->DiagStorage.NumDiagArgs; }
1548
1549 /// Return the kind of the specified index.
1550 ///
1551 /// Based on the kind of argument, the accessors below can be used to get
1552 /// the value.
1553 ///
1554 /// \pre Idx < getNumArgs()
1555 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1556 assert(Idx < getNumArgs() && "Argument index out of range!")(static_cast <bool> (Idx < getNumArgs() && "Argument index out of range!"
) ? void (0) : __assert_fail ("Idx < getNumArgs() && \"Argument index out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1556, __extension__ __PRETTY_FUNCTION__))
;
1557 return (DiagnosticsEngine::ArgumentKind)
1558 DiagObj->DiagStorage.DiagArgumentsKind[Idx];
1559 }
1560
1561 /// Return the provided argument string specified by \p Idx.
1562 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1563 const std::string &getArgStdStr(unsigned Idx) const {
1564 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_std_string && "invalid argument accessor!") ? void
(0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1565, __extension__ __PRETTY_FUNCTION__))
1565 "invalid argument accessor!")(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_std_string && "invalid argument accessor!") ? void
(0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1565, __extension__ __PRETTY_FUNCTION__))
;
1566 return DiagObj->DiagStorage.DiagArgumentsStr[Idx];
1567 }
1568
1569 /// Return the specified C string argument.
1570 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1571 const char *getArgCStr(unsigned Idx) const {
1572 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_c_string && "invalid argument accessor!") ? void
(0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_c_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1573, __extension__ __PRETTY_FUNCTION__))
1573 "invalid argument accessor!")(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_c_string && "invalid argument accessor!") ? void
(0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_c_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1573, __extension__ __PRETTY_FUNCTION__))
;
1574 return reinterpret_cast<const char *>(
1575 DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1576 }
1577
1578 /// Return the specified signed integer argument.
1579 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1580 int getArgSInt(unsigned Idx) const {
1581 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_sint && "invalid argument accessor!") ? void (0)
: __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_sint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1582, __extension__ __PRETTY_FUNCTION__))
1582 "invalid argument accessor!")(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_sint && "invalid argument accessor!") ? void (0)
: __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_sint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1582, __extension__ __PRETTY_FUNCTION__))
;
1583 return (int)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1584 }
1585
1586 /// Return the specified unsigned integer argument.
1587 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1588 unsigned getArgUInt(unsigned Idx) const {
1589 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_uint && "invalid argument accessor!") ? void (0)
: __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_uint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1590, __extension__ __PRETTY_FUNCTION__))
1590 "invalid argument accessor!")(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_uint && "invalid argument accessor!") ? void (0)
: __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_uint && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1590, __extension__ __PRETTY_FUNCTION__))
;
1591 return (unsigned)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1592 }
1593
1594 /// Return the specified IdentifierInfo argument.
1595 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1596 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1597 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_identifierinfo && "invalid argument accessor!") ?
void (0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1598, __extension__ __PRETTY_FUNCTION__))
1598 "invalid argument accessor!")(static_cast <bool> (getArgKind(Idx) == DiagnosticsEngine
::ak_identifierinfo && "invalid argument accessor!") ?
void (0) : __assert_fail ("getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1598, __extension__ __PRETTY_FUNCTION__))
;
1599 return reinterpret_cast<IdentifierInfo *>(
1600 DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1601 }
1602
1603 /// Return the specified non-string argument in an opaque form.
1604 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1605 intptr_t getRawArg(unsigned Idx) const {
1606 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&(static_cast <bool> (getArgKind(Idx) != DiagnosticsEngine
::ak_std_string && "invalid argument accessor!") ? void
(0) : __assert_fail ("getArgKind(Idx) != DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1607, __extension__ __PRETTY_FUNCTION__))
1607 "invalid argument accessor!")(static_cast <bool> (getArgKind(Idx) != DiagnosticsEngine
::ak_std_string && "invalid argument accessor!") ? void
(0) : __assert_fail ("getArgKind(Idx) != DiagnosticsEngine::ak_std_string && \"invalid argument accessor!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1607, __extension__ __PRETTY_FUNCTION__))
;
1608 return DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1609 }
1610
1611 /// Return the number of source ranges associated with this diagnostic.
1612 unsigned getNumRanges() const {
1613 return DiagObj->DiagStorage.DiagRanges.size();
1614 }
1615
1616 /// \pre Idx < getNumRanges()
1617 const CharSourceRange &getRange(unsigned Idx) const {
1618 assert(Idx < getNumRanges() && "Invalid diagnostic range index!")(static_cast <bool> (Idx < getNumRanges() &&
"Invalid diagnostic range index!") ? void (0) : __assert_fail
("Idx < getNumRanges() && \"Invalid diagnostic range index!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1618, __extension__ __PRETTY_FUNCTION__))
;
1619 return DiagObj->DiagStorage.DiagRanges[Idx];
1620 }
1621
1622 /// Return an array reference for this diagnostic's ranges.
1623 ArrayRef<CharSourceRange> getRanges() const {
1624 return DiagObj->DiagStorage.DiagRanges;
1625 }
1626
1627 unsigned getNumFixItHints() const {
1628 return DiagObj->DiagStorage.FixItHints.size();
1629 }
1630
1631 const FixItHint &getFixItHint(unsigned Idx) const {
1632 assert(Idx < getNumFixItHints() && "Invalid index!")(static_cast <bool> (Idx < getNumFixItHints() &&
"Invalid index!") ? void (0) : __assert_fail ("Idx < getNumFixItHints() && \"Invalid index!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Basic/Diagnostic.h"
, 1632, __extension__ __PRETTY_FUNCTION__))
;
1633 return DiagObj->DiagStorage.FixItHints[Idx];
1634 }
1635
1636 ArrayRef<FixItHint> getFixItHints() const {
1637 return DiagObj->DiagStorage.FixItHints;
1638 }
1639
1640 /// Format this diagnostic into a string, substituting the
1641 /// formal arguments into the %0 slots.
1642 ///
1643 /// The result is appended onto the \p OutStr array.
1644 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1645
1646 /// Format the given format-string into the output buffer using the
1647 /// arguments stored in this diagnostic.
1648 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1649 SmallVectorImpl<char> &OutStr) const;
1650};
1651
1652/**
1653 * Represents a diagnostic in a form that can be retained until its
1654 * corresponding source manager is destroyed.
1655 */
1656class StoredDiagnostic {
1657 unsigned ID;
1658 DiagnosticsEngine::Level Level;
1659 FullSourceLoc Loc;
1660 std::string Message;
1661 std::vector<CharSourceRange> Ranges;
1662 std::vector<FixItHint> FixIts;
1663
1664public:
1665 StoredDiagnostic() = default;
1666 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1667 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1668 StringRef Message);
1669 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1670 StringRef Message, FullSourceLoc Loc,
1671 ArrayRef<CharSourceRange> Ranges,
1672 ArrayRef<FixItHint> Fixits);
1673
1674 /// Evaluates true when this object stores a diagnostic.
1675 explicit operator bool() const { return !Message.empty(); }
1676
1677 unsigned getID() const { return ID; }
1678 DiagnosticsEngine::Level getLevel() const { return Level; }
1679 const FullSourceLoc &getLocation() const { return Loc; }
1680 StringRef getMessage() const { return Message; }
1681
1682 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1683
1684 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1685
1686 range_iterator range_begin() const { return Ranges.begin(); }
1687 range_iterator range_end() const { return Ranges.end(); }
1688 unsigned range_size() const { return Ranges.size(); }
1689
1690 ArrayRef<CharSourceRange> getRanges() const {
1691 return llvm::makeArrayRef(Ranges);
1692 }
1693
1694 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1695
1696 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1697 fixit_iterator fixit_end() const { return FixIts.end(); }
1698 unsigned fixit_size() const { return FixIts.size(); }
1699
1700 ArrayRef<FixItHint> getFixIts() const {
1701 return llvm::makeArrayRef(FixIts);
1702 }
1703};
1704
1705/// Abstract interface, implemented by clients of the front-end, which
1706/// formats and prints fully processed diagnostics.
1707class DiagnosticConsumer {
1708protected:
1709 unsigned NumWarnings = 0; ///< Number of warnings reported
1710 unsigned NumErrors = 0; ///< Number of errors reported
1711
1712public:
1713 DiagnosticConsumer() = default;
1714 virtual ~DiagnosticConsumer();
1715
1716 unsigned getNumErrors() const { return NumErrors; }
1717 unsigned getNumWarnings() const { return NumWarnings; }
1718 virtual void clear() { NumWarnings = NumErrors = 0; }
1719
1720 /// Callback to inform the diagnostic client that processing
1721 /// of a source file is beginning.
1722 ///
1723 /// Note that diagnostics may be emitted outside the processing of a source
1724 /// file, for example during the parsing of command line options. However,
1725 /// diagnostics with source range information are required to only be emitted
1726 /// in between BeginSourceFile() and EndSourceFile().
1727 ///
1728 /// \param LangOpts The language options for the source file being processed.
1729 /// \param PP The preprocessor object being used for the source; this is
1730 /// optional, e.g., it may not be present when processing AST source files.
1731 virtual void BeginSourceFile(const LangOptions &LangOpts,
1732 const Preprocessor *PP = nullptr) {}
1733
1734 /// Callback to inform the diagnostic client that processing
1735 /// of a source file has ended.
1736 ///
1737 /// The diagnostic client should assume that any objects made available via
1738 /// BeginSourceFile() are inaccessible.
1739 virtual void EndSourceFile() {}
1740
1741 /// Callback to inform the diagnostic client that processing of all
1742 /// source files has ended.
1743 virtual void finish() {}
1744
1745 /// Indicates whether the diagnostics handled by this
1746 /// DiagnosticConsumer should be included in the number of diagnostics
1747 /// reported by DiagnosticsEngine.
1748 ///
1749 /// The default implementation returns true.
1750 virtual bool IncludeInDiagnosticCounts() const;
1751
1752 /// Handle this diagnostic, reporting it to the user or
1753 /// capturing it to a log as needed.
1754 ///
1755 /// The default implementation just keeps track of the total number of
1756 /// warnings and errors.
1757 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1758 const Diagnostic &Info);
1759};
1760
1761/// A diagnostic client that ignores all diagnostics.
1762class IgnoringDiagConsumer : public DiagnosticConsumer {
1763 virtual void anchor();
1764
1765 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1766 const Diagnostic &Info) override {
1767 // Just ignore it.
1768 }
1769};
1770
1771/// Diagnostic consumer that forwards diagnostics along to an
1772/// existing, already-initialized diagnostic consumer.
1773///
1774class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1775 DiagnosticConsumer &Target;
1776
1777public:
1778 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1779 ~ForwardingDiagnosticConsumer() override;
1780
1781 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1782 const Diagnostic &Info) override;
1783 void clear() override;
1784
1785 bool IncludeInDiagnosticCounts() const override;
1786};
1787
1788// Struct used for sending info about how a type should be printed.
1789struct TemplateDiffTypes {
1790 intptr_t FromType;
1791 intptr_t ToType;
1792 unsigned PrintTree : 1;
1793 unsigned PrintFromType : 1;
1794 unsigned ElideType : 1;
1795 unsigned ShowColors : 1;
1796
1797 // The printer sets this variable to true if the template diff was used.
1798 unsigned TemplateDiffUsed : 1;
1799};
1800
1801/// Special character that the diagnostic printer will use to toggle the bold
1802/// attribute. The character itself will be not be printed.
1803const char ToggleHighlight = 127;
1804
1805/// ProcessWarningOptions - Initialize the diagnostic client and process the
1806/// warning options specified on the command line.
1807void ProcessWarningOptions(DiagnosticsEngine &Diags,
1808 const DiagnosticOptions &Opts,
1809 bool ReportDiags = true);
1810
1811} // namespace clang
1812
1813#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H