Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Parse -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Parse -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/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-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -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-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Parse/ParsePragma.cpp

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/Parse/ParsePragma.cpp

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

/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include/clang/Basic/Diagnostic.h

1//===- Diagnostic.h - C Language Family Diagnostic Handling -----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_DIAGNOSTIC_H
15#define LLVM_CLANG_BASIC_DIAGNOSTIC_H
16
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/SourceLocation.h"
20#include "clang/Basic/Specifiers.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/IntrusiveRefCntPtr.h"
24#include "llvm/ADT/Optional.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringRef.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Compiler.h"
29#include <cassert>
30#include <cstdint>
31#include <limits>
32#include <list>
33#include <map>
34#include <memory>
35#include <string>
36#include <type_traits>
37#include <utility>
38#include <vector>
39
40namespace llvm {
41class Error;
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 SourceRange R) {
1476 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1477 return DB;
1478}
1479
1480inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1481 ArrayRef<SourceRange> Ranges) {
1482 for (SourceRange R : Ranges)
1483 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1484 return DB;
1485}
1486
1487inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1488 const CharSourceRange &R) {
1489 DB.AddSourceRange(R);
1490 return DB;
1491}
1492
1493inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1494 const FixItHint &Hint) {
1495 DB.AddFixItHint(Hint);
1496 return DB;
1497}
1498
1499inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1500 ArrayRef<FixItHint> Hints) {
1501 for (const FixItHint &Hint : Hints)
1502 DB.AddFixItHint(Hint);
1503 return DB;
1504}
1505
1506inline const StreamingDiagnostic &
1507operator<<(const StreamingDiagnostic &DB,
1508 const llvm::Optional<SourceRange> &Opt) {
1509 if (Opt)
1510 DB << *Opt;
1511 return DB;
1512}
1513
1514inline const StreamingDiagnostic &
1515operator<<(const StreamingDiagnostic &DB,
1516 const llvm::Optional<CharSourceRange> &Opt) {
1517 if (Opt)
1518 DB << *Opt;
1519 return DB;
1520}
1521
1522inline const StreamingDiagnostic &
1523operator<<(const StreamingDiagnostic &DB,
1524 const llvm::Optional<FixItHint> &Opt) {
1525 if (Opt)
1526 DB << *Opt;
1527 return DB;
1528}
1529
1530/// A nullability kind paired with a bit indicating whether it used a
1531/// context-sensitive keyword.
1532using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1533
1534const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1535 DiagNullabilityKind nullability);
1536
1537inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1538 unsigned DiagID) {
1539 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", 1540, __extension__
__PRETTY_FUNCTION__))
1540 "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", 1540, __extension__
__PRETTY_FUNCTION__))
;
1541 CurDiagLoc = Loc;
1542 CurDiagID = DiagID;
1543 FlagValue.clear();
1544 return DiagnosticBuilder(this);
1545}
1546
1547const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
1548 llvm::Error &&E);
1549
1550inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1551 return Report(SourceLocation(), DiagID);
1552}
1553
1554//===----------------------------------------------------------------------===//
1555// Diagnostic
1556//===----------------------------------------------------------------------===//
1557
1558/// A little helper class (which is basically a smart pointer that forwards
1559/// info from DiagnosticsEngine) that allows clients to enquire about the
1560/// currently in-flight diagnostic.
1561class Diagnostic {
1562 const DiagnosticsEngine *DiagObj;
1563 StringRef StoredDiagMessage;
1564
1565public:
1566 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1567 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1568 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1569
1570 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1571 unsigned getID() const { return DiagObj->CurDiagID; }
1572 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1573 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1574 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1575
1576 unsigned getNumArgs() const { return DiagObj->DiagStorage.NumDiagArgs; }
1577
1578 /// Return the kind of the specified index.
1579 ///
1580 /// Based on the kind of argument, the accessors below can be used to get
1581 /// the value.
1582 ///
1583 /// \pre Idx < getNumArgs()
1584 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1585 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", 1585, __extension__
__PRETTY_FUNCTION__))
;
1586 return (DiagnosticsEngine::ArgumentKind)
1587 DiagObj->DiagStorage.DiagArgumentsKind[Idx];
1588 }
1589
1590 /// Return the provided argument string specified by \p Idx.
1591 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1592 const std::string &getArgStdStr(unsigned Idx) const {
1593 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", 1594, __extension__
__PRETTY_FUNCTION__))
1594 "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", 1594, __extension__
__PRETTY_FUNCTION__))
;
1595 return DiagObj->DiagStorage.DiagArgumentsStr[Idx];
1596 }
1597
1598 /// Return the specified C string argument.
1599 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1600 const char *getArgCStr(unsigned Idx) const {
1601 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", 1602, __extension__
__PRETTY_FUNCTION__))
1602 "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", 1602, __extension__
__PRETTY_FUNCTION__))
;
1603 return reinterpret_cast<const char *>(
1604 DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1605 }
1606
1607 /// Return the specified signed integer argument.
1608 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1609 int64_t getArgSInt(unsigned Idx) const {
1610 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", 1611, __extension__
__PRETTY_FUNCTION__))
1611 "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", 1611, __extension__
__PRETTY_FUNCTION__))
;
1612 return (int64_t)DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1613 }
1614
1615 /// Return the specified unsigned integer argument.
1616 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1617 uint64_t getArgUInt(unsigned Idx) const {
1618 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", 1619, __extension__
__PRETTY_FUNCTION__))
1619 "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", 1619, __extension__
__PRETTY_FUNCTION__))
;
1620 return DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1621 }
1622
1623 /// Return the specified IdentifierInfo argument.
1624 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1625 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1626 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", 1627, __extension__
__PRETTY_FUNCTION__))
1627 "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", 1627, __extension__
__PRETTY_FUNCTION__))
;
1628 return reinterpret_cast<IdentifierInfo *>(
1629 DiagObj->DiagStorage.DiagArgumentsVal[Idx]);
1630 }
1631
1632 /// Return the specified non-string argument in an opaque form.
1633 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1634 uint64_t getRawArg(unsigned Idx) const {
1635 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", 1636, __extension__
__PRETTY_FUNCTION__))
1636 "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", 1636, __extension__
__PRETTY_FUNCTION__))
;
1637 return DiagObj->DiagStorage.DiagArgumentsVal[Idx];
1638 }
1639
1640 /// Return the number of source ranges associated with this diagnostic.
1641 unsigned getNumRanges() const {
1642 return DiagObj->DiagStorage.DiagRanges.size();
1643 }
1644
1645 /// \pre Idx < getNumRanges()
1646 const CharSourceRange &getRange(unsigned Idx) const {
1647 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", 1647, __extension__
__PRETTY_FUNCTION__))
;
1648 return DiagObj->DiagStorage.DiagRanges[Idx];
1649 }
1650
1651 /// Return an array reference for this diagnostic's ranges.
1652 ArrayRef<CharSourceRange> getRanges() const {
1653 return DiagObj->DiagStorage.DiagRanges;
1654 }
1655
1656 unsigned getNumFixItHints() const {
1657 return DiagObj->DiagStorage.FixItHints.size();
1658 }
1659
1660 const FixItHint &getFixItHint(unsigned Idx) const {
1661 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", 1661, __extension__
__PRETTY_FUNCTION__))
;
1662 return DiagObj->DiagStorage.FixItHints[Idx];
1663 }
1664
1665 ArrayRef<FixItHint> getFixItHints() const {
1666 return DiagObj->DiagStorage.FixItHints;
1667 }
1668
1669 /// Format this diagnostic into a string, substituting the
1670 /// formal arguments into the %0 slots.
1671 ///
1672 /// The result is appended onto the \p OutStr array.
1673 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1674
1675 /// Format the given format-string into the output buffer using the
1676 /// arguments stored in this diagnostic.
1677 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1678 SmallVectorImpl<char> &OutStr) const;
1679};
1680
1681/**
1682 * Represents a diagnostic in a form that can be retained until its
1683 * corresponding source manager is destroyed.
1684 */
1685class StoredDiagnostic {
1686 unsigned ID;
1687 DiagnosticsEngine::Level Level;
1688 FullSourceLoc Loc;
1689 std::string Message;
1690 std::vector<CharSourceRange> Ranges;
1691 std::vector<FixItHint> FixIts;
1692
1693public:
1694 StoredDiagnostic() = default;
1695 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1696 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1697 StringRef Message);
1698 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1699 StringRef Message, FullSourceLoc Loc,
1700 ArrayRef<CharSourceRange> Ranges,
1701 ArrayRef<FixItHint> Fixits);
1702
1703 /// Evaluates true when this object stores a diagnostic.
1704 explicit operator bool() const { return !Message.empty(); }
1705
1706 unsigned getID() const { return ID; }
1707 DiagnosticsEngine::Level getLevel() const { return Level; }
1708 const FullSourceLoc &getLocation() const { return Loc; }
1709 StringRef getMessage() const { return Message; }
1710
1711 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1712
1713 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1714
1715 range_iterator range_begin() const { return Ranges.begin(); }
1716 range_iterator range_end() const { return Ranges.end(); }
1717 unsigned range_size() const { return Ranges.size(); }
1718
1719 ArrayRef<CharSourceRange> getRanges() const {
1720 return llvm::makeArrayRef(Ranges);
1721 }
1722
1723 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1724
1725 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1726 fixit_iterator fixit_end() const { return FixIts.end(); }
1727 unsigned fixit_size() const { return FixIts.size(); }
1728
1729 ArrayRef<FixItHint> getFixIts() const {
1730 return llvm::makeArrayRef(FixIts);
1731 }
1732};
1733
1734// Simple debug printing of StoredDiagnostic.
1735llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const StoredDiagnostic &);
1736
1737/// Abstract interface, implemented by clients of the front-end, which
1738/// formats and prints fully processed diagnostics.
1739class DiagnosticConsumer {
1740protected:
1741 unsigned NumWarnings = 0; ///< Number of warnings reported
1742 unsigned NumErrors = 0; ///< Number of errors reported
1743
1744public:
1745 DiagnosticConsumer() = default;
1746 virtual ~DiagnosticConsumer();
1747
1748 unsigned getNumErrors() const { return NumErrors; }
1749 unsigned getNumWarnings() const { return NumWarnings; }
1750 virtual void clear() { NumWarnings = NumErrors = 0; }
1751
1752 /// Callback to inform the diagnostic client that processing
1753 /// of a source file is beginning.
1754 ///
1755 /// Note that diagnostics may be emitted outside the processing of a source
1756 /// file, for example during the parsing of command line options. However,
1757 /// diagnostics with source range information are required to only be emitted
1758 /// in between BeginSourceFile() and EndSourceFile().
1759 ///
1760 /// \param LangOpts The language options for the source file being processed.
1761 /// \param PP The preprocessor object being used for the source; this is
1762 /// optional, e.g., it may not be present when processing AST source files.
1763 virtual void BeginSourceFile(const LangOptions &LangOpts,
1764 const Preprocessor *PP = nullptr) {}
1765
1766 /// Callback to inform the diagnostic client that processing
1767 /// of a source file has ended.
1768 ///
1769 /// The diagnostic client should assume that any objects made available via
1770 /// BeginSourceFile() are inaccessible.
1771 virtual void EndSourceFile() {}
1772
1773 /// Callback to inform the diagnostic client that processing of all
1774 /// source files has ended.
1775 virtual void finish() {}
1776
1777 /// Indicates whether the diagnostics handled by this
1778 /// DiagnosticConsumer should be included in the number of diagnostics
1779 /// reported by DiagnosticsEngine.
1780 ///
1781 /// The default implementation returns true.
1782 virtual bool IncludeInDiagnosticCounts() const;
1783
1784 /// Handle this diagnostic, reporting it to the user or
1785 /// capturing it to a log as needed.
1786 ///
1787 /// The default implementation just keeps track of the total number of
1788 /// warnings and errors.
1789 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1790 const Diagnostic &Info);
1791};
1792
1793/// A diagnostic client that ignores all diagnostics.
1794class IgnoringDiagConsumer : public DiagnosticConsumer {
1795 virtual void anchor();
1796
1797 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1798 const Diagnostic &Info) override {
1799 // Just ignore it.
1800 }
1801};
1802
1803/// Diagnostic consumer that forwards diagnostics along to an
1804/// existing, already-initialized diagnostic consumer.
1805///
1806class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1807 DiagnosticConsumer &Target;
1808
1809public:
1810 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1811 ~ForwardingDiagnosticConsumer() override;
1812
1813 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1814 const Diagnostic &Info) override;
1815 void clear() override;
1816
1817 bool IncludeInDiagnosticCounts() const override;
1818};
1819
1820// Struct used for sending info about how a type should be printed.
1821struct TemplateDiffTypes {
1822 intptr_t FromType;
1823 intptr_t ToType;
1824 unsigned PrintTree : 1;
1825 unsigned PrintFromType : 1;
1826 unsigned ElideType : 1;
1827 unsigned ShowColors : 1;
1828
1829 // The printer sets this variable to true if the template diff was used.
1830 unsigned TemplateDiffUsed : 1;
1831};
1832
1833/// Special character that the diagnostic printer will use to toggle the bold
1834/// attribute. The character itself will be not be printed.
1835const char ToggleHighlight = 127;
1836
1837/// ProcessWarningOptions - Initialize the diagnostic client and process the
1838/// warning options specified on the command line.
1839void ProcessWarningOptions(DiagnosticsEngine &Diags,
1840 const DiagnosticOptions &Opts,
1841 bool ReportDiags = true);
1842
1843} // namespace clang
1844
1845#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H