Bug Summary

File:build/source/clang/include/clang/Basic/Diagnostic.h
Warning:line 1188, 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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ParsePragma.cpp -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Parse -I /build/source/clang/lib/Parse -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -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-17/lib/clang/17/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 -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1679915782 -O3 -Wno-unused-command-line-argument -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 -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2023-03-27-130437-16335-1 -x c++ /build/source/clang/lib/Parse/ParsePragma.cpp

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

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