Bug Summary

File:tools/clang/lib/Parse/ParsePragma.cpp
Warning:line 2946, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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