Bug Summary

File:build/source/clang/lib/Parse/ParseOpenMP.cpp
Warning:line 2908, column 7
Value stored to 'HasImplicitClause' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ParseOpenMP.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Parse -I /build/source/clang/lib/Parse -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Parse/ParseOpenMP.cpp
1//===--- ParseOpenMP.cpp - OpenMP directives parsing ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9/// This file implements parsing of all OpenMP directives and clauses.
10///
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/OpenMPClause.h"
15#include "clang/AST/StmtOpenMP.h"
16#include "clang/Basic/OpenMPKinds.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Basic/TokenKinds.h"
19#include "clang/Parse/ParseDiagnostic.h"
20#include "clang/Parse/Parser.h"
21#include "clang/Parse/RAIIObjectsForParser.h"
22#include "clang/Sema/EnterExpressionEvaluationContext.h"
23#include "clang/Sema/Scope.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/ADT/UniqueVector.h"
27#include "llvm/Frontend/OpenMP/OMPAssume.h"
28#include "llvm/Frontend/OpenMP/OMPContext.h"
29#include <optional>
30
31using namespace clang;
32using namespace llvm::omp;
33
34//===----------------------------------------------------------------------===//
35// OpenMP declarative directives.
36//===----------------------------------------------------------------------===//
37
38namespace {
39enum OpenMPDirectiveKindEx {
40 OMPD_cancellation = llvm::omp::Directive_enumSize + 1,
41 OMPD_data,
42 OMPD_declare,
43 OMPD_end,
44 OMPD_end_declare,
45 OMPD_enter,
46 OMPD_exit,
47 OMPD_point,
48 OMPD_reduction,
49 OMPD_target_enter,
50 OMPD_target_exit,
51 OMPD_update,
52 OMPD_distribute_parallel,
53 OMPD_teams_distribute_parallel,
54 OMPD_target_teams_distribute_parallel,
55 OMPD_mapper,
56 OMPD_variant,
57 OMPD_begin,
58 OMPD_begin_declare,
59};
60
61// Helper to unify the enum class OpenMPDirectiveKind with its extension
62// the OpenMPDirectiveKindEx enum which allows to use them together as if they
63// are unsigned values.
64struct OpenMPDirectiveKindExWrapper {
65 OpenMPDirectiveKindExWrapper(unsigned Value) : Value(Value) {}
66 OpenMPDirectiveKindExWrapper(OpenMPDirectiveKind DK) : Value(unsigned(DK)) {}
67 bool operator==(OpenMPDirectiveKindExWrapper V) const {
68 return Value == V.Value;
69 }
70 bool operator!=(OpenMPDirectiveKindExWrapper V) const {
71 return Value != V.Value;
72 }
73 bool operator==(OpenMPDirectiveKind V) const { return Value == unsigned(V); }
74 bool operator!=(OpenMPDirectiveKind V) const { return Value != unsigned(V); }
75 bool operator<(OpenMPDirectiveKind V) const { return Value < unsigned(V); }
76 operator unsigned() const { return Value; }
77 operator OpenMPDirectiveKind() const { return OpenMPDirectiveKind(Value); }
78 unsigned Value;
79};
80
81class DeclDirectiveListParserHelper final {
82 SmallVector<Expr *, 4> Identifiers;
83 Parser *P;
84 OpenMPDirectiveKind Kind;
85
86public:
87 DeclDirectiveListParserHelper(Parser *P, OpenMPDirectiveKind Kind)
88 : P(P), Kind(Kind) {}
89 void operator()(CXXScopeSpec &SS, DeclarationNameInfo NameInfo) {
90 ExprResult Res = P->getActions().ActOnOpenMPIdExpression(
91 P->getCurScope(), SS, NameInfo, Kind);
92 if (Res.isUsable())
93 Identifiers.push_back(Res.get());
94 }
95 llvm::ArrayRef<Expr *> getIdentifiers() const { return Identifiers; }
96};
97} // namespace
98
99// Map token string to extended OMP token kind that are
100// OpenMPDirectiveKind + OpenMPDirectiveKindEx.
101static unsigned getOpenMPDirectiveKindEx(StringRef S) {
102 OpenMPDirectiveKindExWrapper DKind = getOpenMPDirectiveKind(S);
103 if (DKind != OMPD_unknown)
104 return DKind;
105
106 return llvm::StringSwitch<OpenMPDirectiveKindExWrapper>(S)
107 .Case("cancellation", OMPD_cancellation)
108 .Case("data", OMPD_data)
109 .Case("declare", OMPD_declare)
110 .Case("end", OMPD_end)
111 .Case("enter", OMPD_enter)
112 .Case("exit", OMPD_exit)
113 .Case("point", OMPD_point)
114 .Case("reduction", OMPD_reduction)
115 .Case("update", OMPD_update)
116 .Case("mapper", OMPD_mapper)
117 .Case("variant", OMPD_variant)
118 .Case("begin", OMPD_begin)
119 .Default(OMPD_unknown);
120}
121
122static OpenMPDirectiveKindExWrapper parseOpenMPDirectiveKind(Parser &P) {
123 // Array of foldings: F[i][0] F[i][1] ===> F[i][2].
124 // E.g.: OMPD_for OMPD_simd ===> OMPD_for_simd
125 // TODO: add other combined directives in topological order.
126 static const OpenMPDirectiveKindExWrapper F[][3] = {
127 {OMPD_begin, OMPD_declare, OMPD_begin_declare},
128 {OMPD_begin, OMPD_assumes, OMPD_begin_assumes},
129 {OMPD_end, OMPD_declare, OMPD_end_declare},
130 {OMPD_end, OMPD_assumes, OMPD_end_assumes},
131 {OMPD_cancellation, OMPD_point, OMPD_cancellation_point},
132 {OMPD_declare, OMPD_reduction, OMPD_declare_reduction},
133 {OMPD_declare, OMPD_mapper, OMPD_declare_mapper},
134 {OMPD_declare, OMPD_simd, OMPD_declare_simd},
135 {OMPD_declare, OMPD_target, OMPD_declare_target},
136 {OMPD_declare, OMPD_variant, OMPD_declare_variant},
137 {OMPD_begin_declare, OMPD_target, OMPD_begin_declare_target},
138 {OMPD_begin_declare, OMPD_variant, OMPD_begin_declare_variant},
139 {OMPD_end_declare, OMPD_variant, OMPD_end_declare_variant},
140 {OMPD_distribute, OMPD_parallel, OMPD_distribute_parallel},
141 {OMPD_distribute_parallel, OMPD_for, OMPD_distribute_parallel_for},
142 {OMPD_distribute_parallel_for, OMPD_simd,
143 OMPD_distribute_parallel_for_simd},
144 {OMPD_distribute, OMPD_simd, OMPD_distribute_simd},
145 {OMPD_end_declare, OMPD_target, OMPD_end_declare_target},
146 {OMPD_target, OMPD_data, OMPD_target_data},
147 {OMPD_target, OMPD_enter, OMPD_target_enter},
148 {OMPD_target, OMPD_exit, OMPD_target_exit},
149 {OMPD_target, OMPD_update, OMPD_target_update},
150 {OMPD_target_enter, OMPD_data, OMPD_target_enter_data},
151 {OMPD_target_exit, OMPD_data, OMPD_target_exit_data},
152 {OMPD_for, OMPD_simd, OMPD_for_simd},
153 {OMPD_parallel, OMPD_for, OMPD_parallel_for},
154 {OMPD_parallel_for, OMPD_simd, OMPD_parallel_for_simd},
155 {OMPD_parallel, OMPD_loop, OMPD_parallel_loop},
156 {OMPD_parallel, OMPD_sections, OMPD_parallel_sections},
157 {OMPD_taskloop, OMPD_simd, OMPD_taskloop_simd},
158 {OMPD_target, OMPD_parallel, OMPD_target_parallel},
159 {OMPD_target, OMPD_simd, OMPD_target_simd},
160 {OMPD_target_parallel, OMPD_loop, OMPD_target_parallel_loop},
161 {OMPD_target_parallel, OMPD_for, OMPD_target_parallel_for},
162 {OMPD_target_parallel_for, OMPD_simd, OMPD_target_parallel_for_simd},
163 {OMPD_teams, OMPD_distribute, OMPD_teams_distribute},
164 {OMPD_teams_distribute, OMPD_simd, OMPD_teams_distribute_simd},
165 {OMPD_teams_distribute, OMPD_parallel, OMPD_teams_distribute_parallel},
166 {OMPD_teams_distribute_parallel, OMPD_for,
167 OMPD_teams_distribute_parallel_for},
168 {OMPD_teams_distribute_parallel_for, OMPD_simd,
169 OMPD_teams_distribute_parallel_for_simd},
170 {OMPD_teams, OMPD_loop, OMPD_teams_loop},
171 {OMPD_target, OMPD_teams, OMPD_target_teams},
172 {OMPD_target_teams, OMPD_distribute, OMPD_target_teams_distribute},
173 {OMPD_target_teams, OMPD_loop, OMPD_target_teams_loop},
174 {OMPD_target_teams_distribute, OMPD_parallel,
175 OMPD_target_teams_distribute_parallel},
176 {OMPD_target_teams_distribute, OMPD_simd,
177 OMPD_target_teams_distribute_simd},
178 {OMPD_target_teams_distribute_parallel, OMPD_for,
179 OMPD_target_teams_distribute_parallel_for},
180 {OMPD_target_teams_distribute_parallel_for, OMPD_simd,
181 OMPD_target_teams_distribute_parallel_for_simd},
182 {OMPD_master, OMPD_taskloop, OMPD_master_taskloop},
183 {OMPD_masked, OMPD_taskloop, OMPD_masked_taskloop},
184 {OMPD_master_taskloop, OMPD_simd, OMPD_master_taskloop_simd},
185 {OMPD_masked_taskloop, OMPD_simd, OMPD_masked_taskloop_simd},
186 {OMPD_parallel, OMPD_master, OMPD_parallel_master},
187 {OMPD_parallel, OMPD_masked, OMPD_parallel_masked},
188 {OMPD_parallel_master, OMPD_taskloop, OMPD_parallel_master_taskloop},
189 {OMPD_parallel_masked, OMPD_taskloop, OMPD_parallel_masked_taskloop},
190 {OMPD_parallel_master_taskloop, OMPD_simd,
191 OMPD_parallel_master_taskloop_simd},
192 {OMPD_parallel_masked_taskloop, OMPD_simd,
193 OMPD_parallel_masked_taskloop_simd}};
194 enum { CancellationPoint = 0, DeclareReduction = 1, TargetData = 2 };
195 Token Tok = P.getCurToken();
196 OpenMPDirectiveKindExWrapper DKind =
197 Tok.isAnnotation()
198 ? static_cast<unsigned>(OMPD_unknown)
199 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
200 if (DKind == OMPD_unknown)
201 return OMPD_unknown;
202
203 for (const auto &I : F) {
204 if (DKind != I[0])
205 continue;
206
207 Tok = P.getPreprocessor().LookAhead(0);
208 OpenMPDirectiveKindExWrapper SDKind =
209 Tok.isAnnotation()
210 ? static_cast<unsigned>(OMPD_unknown)
211 : getOpenMPDirectiveKindEx(P.getPreprocessor().getSpelling(Tok));
212 if (SDKind == OMPD_unknown)
213 continue;
214
215 if (SDKind == I[1]) {
216 P.ConsumeToken();
217 DKind = I[2];
218 }
219 }
220 return unsigned(DKind) < llvm::omp::Directive_enumSize
221 ? static_cast<OpenMPDirectiveKind>(DKind)
222 : OMPD_unknown;
223}
224
225static DeclarationName parseOpenMPReductionId(Parser &P) {
226 Token Tok = P.getCurToken();
227 Sema &Actions = P.getActions();
228 OverloadedOperatorKind OOK = OO_None;
229 // Allow to use 'operator' keyword for C++ operators
230 bool WithOperator = false;
231 if (Tok.is(tok::kw_operator)) {
232 P.ConsumeToken();
233 Tok = P.getCurToken();
234 WithOperator = true;
235 }
236 switch (Tok.getKind()) {
237 case tok::plus: // '+'
238 OOK = OO_Plus;
239 break;
240 case tok::minus: // '-'
241 OOK = OO_Minus;
242 break;
243 case tok::star: // '*'
244 OOK = OO_Star;
245 break;
246 case tok::amp: // '&'
247 OOK = OO_Amp;
248 break;
249 case tok::pipe: // '|'
250 OOK = OO_Pipe;
251 break;
252 case tok::caret: // '^'
253 OOK = OO_Caret;
254 break;
255 case tok::ampamp: // '&&'
256 OOK = OO_AmpAmp;
257 break;
258 case tok::pipepipe: // '||'
259 OOK = OO_PipePipe;
260 break;
261 case tok::identifier: // identifier
262 if (!WithOperator)
263 break;
264 [[fallthrough]];
265 default:
266 P.Diag(Tok.getLocation(), diag::err_omp_expected_reduction_identifier);
267 P.SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
268 Parser::StopBeforeMatch);
269 return DeclarationName();
270 }
271 P.ConsumeToken();
272 auto &DeclNames = Actions.getASTContext().DeclarationNames;
273 return OOK == OO_None ? DeclNames.getIdentifier(Tok.getIdentifierInfo())
274 : DeclNames.getCXXOperatorName(OOK);
275}
276
277/// Parse 'omp declare reduction' construct.
278///
279/// declare-reduction-directive:
280/// annot_pragma_openmp 'declare' 'reduction'
281/// '(' <reduction_id> ':' <type> {',' <type>} ':' <expression> ')'
282/// ['initializer' '(' ('omp_priv' '=' <expression>)|<function_call> ')']
283/// annot_pragma_openmp_end
284/// <reduction_id> is either a base language identifier or one of the following
285/// operators: '+', '-', '*', '&', '|', '^', '&&' and '||'.
286///
287Parser::DeclGroupPtrTy
288Parser::ParseOpenMPDeclareReductionDirective(AccessSpecifier AS) {
289 // Parse '('.
290 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
291 if (T.expectAndConsume(
292 diag::err_expected_lparen_after,
293 getOpenMPDirectiveName(OMPD_declare_reduction).data())) {
294 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
295 return DeclGroupPtrTy();
296 }
297
298 DeclarationName Name = parseOpenMPReductionId(*this);
299 if (Name.isEmpty() && Tok.is(tok::annot_pragma_openmp_end))
300 return DeclGroupPtrTy();
301
302 // Consume ':'.
303 bool IsCorrect = !ExpectAndConsume(tok::colon);
304
305 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
306 return DeclGroupPtrTy();
307
308 IsCorrect = IsCorrect && !Name.isEmpty();
309
310 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end)) {
311 Diag(Tok.getLocation(), diag::err_expected_type);
312 IsCorrect = false;
313 }
314
315 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
316 return DeclGroupPtrTy();
317
318 SmallVector<std::pair<QualType, SourceLocation>, 8> ReductionTypes;
319 // Parse list of types until ':' token.
320 do {
321 ColonProtectionRAIIObject ColonRAII(*this);
322 SourceRange Range;
323 TypeResult TR = ParseTypeName(&Range, DeclaratorContext::Prototype, AS);
324 if (TR.isUsable()) {
325 QualType ReductionType =
326 Actions.ActOnOpenMPDeclareReductionType(Range.getBegin(), TR);
327 if (!ReductionType.isNull()) {
328 ReductionTypes.push_back(
329 std::make_pair(ReductionType, Range.getBegin()));
330 }
331 } else {
332 SkipUntil(tok::comma, tok::colon, tok::annot_pragma_openmp_end,
333 StopBeforeMatch);
334 }
335
336 if (Tok.is(tok::colon) || Tok.is(tok::annot_pragma_openmp_end))
337 break;
338
339 // Consume ','.
340 if (ExpectAndConsume(tok::comma)) {
341 IsCorrect = false;
342 if (Tok.is(tok::annot_pragma_openmp_end)) {
343 Diag(Tok.getLocation(), diag::err_expected_type);
344 return DeclGroupPtrTy();
345 }
346 }
347 } while (Tok.isNot(tok::annot_pragma_openmp_end));
348
349 if (ReductionTypes.empty()) {
350 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
351 return DeclGroupPtrTy();
352 }
353
354 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
355 return DeclGroupPtrTy();
356
357 // Consume ':'.
358 if (ExpectAndConsume(tok::colon))
359 IsCorrect = false;
360
361 if (Tok.is(tok::annot_pragma_openmp_end)) {
362 Diag(Tok.getLocation(), diag::err_expected_expression);
363 return DeclGroupPtrTy();
364 }
365
366 DeclGroupPtrTy DRD = Actions.ActOnOpenMPDeclareReductionDirectiveStart(
367 getCurScope(), Actions.getCurLexicalContext(), Name, ReductionTypes, AS);
368
369 // Parse <combiner> expression and then parse initializer if any for each
370 // correct type.
371 unsigned I = 0, E = ReductionTypes.size();
372 for (Decl *D : DRD.get()) {
373 TentativeParsingAction TPA(*this);
374 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
375 Scope::CompoundStmtScope |
376 Scope::OpenMPDirectiveScope);
377 // Parse <combiner> expression.
378 Actions.ActOnOpenMPDeclareReductionCombinerStart(getCurScope(), D);
379 ExprResult CombinerResult = Actions.ActOnFinishFullExpr(
380 ParseExpression().get(), D->getLocation(), /*DiscardedValue*/ false);
381 Actions.ActOnOpenMPDeclareReductionCombinerEnd(D, CombinerResult.get());
382
383 if (CombinerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
384 Tok.isNot(tok::annot_pragma_openmp_end)) {
385 TPA.Commit();
386 IsCorrect = false;
387 break;
388 }
389 IsCorrect = !T.consumeClose() && IsCorrect && CombinerResult.isUsable();
390 ExprResult InitializerResult;
391 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
392 // Parse <initializer> expression.
393 if (Tok.is(tok::identifier) &&
394 Tok.getIdentifierInfo()->isStr("initializer")) {
395 ConsumeToken();
396 } else {
397 Diag(Tok.getLocation(), diag::err_expected) << "'initializer'";
398 TPA.Commit();
399 IsCorrect = false;
400 break;
401 }
402 // Parse '('.
403 BalancedDelimiterTracker T(*this, tok::l_paren,
404 tok::annot_pragma_openmp_end);
405 IsCorrect =
406 !T.expectAndConsume(diag::err_expected_lparen_after, "initializer") &&
407 IsCorrect;
408 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
409 ParseScope OMPDRScope(this, Scope::FnScope | Scope::DeclScope |
410 Scope::CompoundStmtScope |
411 Scope::OpenMPDirectiveScope);
412 // Parse expression.
413 VarDecl *OmpPrivParm =
414 Actions.ActOnOpenMPDeclareReductionInitializerStart(getCurScope(),
415 D);
416 // Check if initializer is omp_priv <init_expr> or something else.
417 if (Tok.is(tok::identifier) &&
418 Tok.getIdentifierInfo()->isStr("omp_priv")) {
419 ConsumeToken();
420 ParseOpenMPReductionInitializerForDecl(OmpPrivParm);
421 } else {
422 InitializerResult = Actions.ActOnFinishFullExpr(
423 ParseAssignmentExpression().get(), D->getLocation(),
424 /*DiscardedValue*/ false);
425 }
426 Actions.ActOnOpenMPDeclareReductionInitializerEnd(
427 D, InitializerResult.get(), OmpPrivParm);
428 if (InitializerResult.isInvalid() && Tok.isNot(tok::r_paren) &&
429 Tok.isNot(tok::annot_pragma_openmp_end)) {
430 TPA.Commit();
431 IsCorrect = false;
432 break;
433 }
434 IsCorrect =
435 !T.consumeClose() && IsCorrect && !InitializerResult.isInvalid();
436 }
437 }
438
439 ++I;
440 // Revert parsing if not the last type, otherwise accept it, we're done with
441 // parsing.
442 if (I != E)
443 TPA.Revert();
444 else
445 TPA.Commit();
446 }
447 return Actions.ActOnOpenMPDeclareReductionDirectiveEnd(getCurScope(), DRD,
448 IsCorrect);
449}
450
451void Parser::ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm) {
452 // Parse declarator '=' initializer.
453 // If a '==' or '+=' is found, suggest a fixit to '='.
454 if (isTokenEqualOrEqualTypo()) {
455 ConsumeToken();
456
457 if (Tok.is(tok::code_completion)) {
458 cutOffParsing();
459 Actions.CodeCompleteInitializer(getCurScope(), OmpPrivParm);
460 Actions.FinalizeDeclaration(OmpPrivParm);
461 return;
462 }
463
464 PreferredType.enterVariableInit(Tok.getLocation(), OmpPrivParm);
465 ExprResult Init = ParseInitializer();
466
467 if (Init.isInvalid()) {
468 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
469 Actions.ActOnInitializerError(OmpPrivParm);
470 } else {
471 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
472 /*DirectInit=*/false);
473 }
474 } else if (Tok.is(tok::l_paren)) {
475 // Parse C++ direct initializer: '(' expression-list ')'
476 BalancedDelimiterTracker T(*this, tok::l_paren);
477 T.consumeOpen();
478
479 ExprVector Exprs;
480
481 SourceLocation LParLoc = T.getOpenLocation();
482 auto RunSignatureHelp = [this, OmpPrivParm, LParLoc, &Exprs]() {
483 QualType PreferredType = Actions.ProduceConstructorSignatureHelp(
484 OmpPrivParm->getType()->getCanonicalTypeInternal(),
485 OmpPrivParm->getLocation(), Exprs, LParLoc, /*Braced=*/false);
486 CalledSignatureHelp = true;
487 return PreferredType;
488 };
489 if (ParseExpressionList(Exprs, [&] {
490 PreferredType.enterFunctionArgument(Tok.getLocation(),
491 RunSignatureHelp);
492 })) {
493 if (PP.isCodeCompletionReached() && !CalledSignatureHelp)
494 RunSignatureHelp();
495 Actions.ActOnInitializerError(OmpPrivParm);
496 SkipUntil(tok::r_paren, tok::annot_pragma_openmp_end, StopBeforeMatch);
497 } else {
498 // Match the ')'.
499 SourceLocation RLoc = Tok.getLocation();
500 if (!T.consumeClose())
501 RLoc = T.getCloseLocation();
502
503 ExprResult Initializer =
504 Actions.ActOnParenListExpr(T.getOpenLocation(), RLoc, Exprs);
505 Actions.AddInitializerToDecl(OmpPrivParm, Initializer.get(),
506 /*DirectInit=*/true);
507 }
508 } else if (getLangOpts().CPlusPlus11 && Tok.is(tok::l_brace)) {
509 // Parse C++0x braced-init-list.
510 Diag(Tok, diag::warn_cxx98_compat_generalized_initializer_lists);
511
512 ExprResult Init(ParseBraceInitializer());
513
514 if (Init.isInvalid()) {
515 Actions.ActOnInitializerError(OmpPrivParm);
516 } else {
517 Actions.AddInitializerToDecl(OmpPrivParm, Init.get(),
518 /*DirectInit=*/true);
519 }
520 } else {
521 Actions.ActOnUninitializedDecl(OmpPrivParm);
522 }
523}
524
525/// Parses 'omp declare mapper' directive.
526///
527/// declare-mapper-directive:
528/// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifier> ':']
529/// <type> <var> ')' [<clause>[[,] <clause>] ... ]
530/// annot_pragma_openmp_end
531/// <mapper-identifier> and <var> are base language identifiers.
532///
533Parser::DeclGroupPtrTy
534Parser::ParseOpenMPDeclareMapperDirective(AccessSpecifier AS) {
535 bool IsCorrect = true;
536 // Parse '('
537 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
538 if (T.expectAndConsume(diag::err_expected_lparen_after,
539 getOpenMPDirectiveName(OMPD_declare_mapper).data())) {
540 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
541 return DeclGroupPtrTy();
542 }
543
544 // Parse <mapper-identifier>
545 auto &DeclNames = Actions.getASTContext().DeclarationNames;
546 DeclarationName MapperId;
547 if (PP.LookAhead(0).is(tok::colon)) {
548 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
549 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
550 IsCorrect = false;
551 } else {
552 MapperId = DeclNames.getIdentifier(Tok.getIdentifierInfo());
553 }
554 ConsumeToken();
555 // Consume ':'.
556 ExpectAndConsume(tok::colon);
557 } else {
558 // If no mapper identifier is provided, its name is "default" by default
559 MapperId =
560 DeclNames.getIdentifier(&Actions.getASTContext().Idents.get("default"));
561 }
562
563 if (!IsCorrect && Tok.is(tok::annot_pragma_openmp_end))
564 return DeclGroupPtrTy();
565
566 // Parse <type> <var>
567 DeclarationName VName;
568 QualType MapperType;
569 SourceRange Range;
570 TypeResult ParsedType = parseOpenMPDeclareMapperVarDecl(Range, VName, AS);
571 if (ParsedType.isUsable())
572 MapperType =
573 Actions.ActOnOpenMPDeclareMapperType(Range.getBegin(), ParsedType);
574 if (MapperType.isNull())
575 IsCorrect = false;
576 if (!IsCorrect) {
577 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
578 return DeclGroupPtrTy();
579 }
580
581 // Consume ')'.
582 IsCorrect &= !T.consumeClose();
583 if (!IsCorrect) {
584 SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch);
585 return DeclGroupPtrTy();
586 }
587
588 // Enter scope.
589 DeclarationNameInfo DirName;
590 SourceLocation Loc = Tok.getLocation();
591 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
592 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
593 ParseScope OMPDirectiveScope(this, ScopeFlags);
594 Actions.StartOpenMPDSABlock(OMPD_declare_mapper, DirName, getCurScope(), Loc);
595
596 // Add the mapper variable declaration.
597 ExprResult MapperVarRef = Actions.ActOnOpenMPDeclareMapperDirectiveVarDecl(
598 getCurScope(), MapperType, Range.getBegin(), VName);
599
600 // Parse map clauses.
601 SmallVector<OMPClause *, 6> Clauses;
602 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
603 OpenMPClauseKind CKind = Tok.isAnnotation()
604 ? OMPC_unknown
605 : getOpenMPClauseKind(PP.getSpelling(Tok));
606 Actions.StartOpenMPClause(CKind);
607 OMPClause *Clause =
608 ParseOpenMPClause(OMPD_declare_mapper, CKind, Clauses.empty());
609 if (Clause)
610 Clauses.push_back(Clause);
611 else
612 IsCorrect = false;
613 // Skip ',' if any.
614 if (Tok.is(tok::comma))
615 ConsumeToken();
616 Actions.EndOpenMPClause();
617 }
618 if (Clauses.empty()) {
619 Diag(Tok, diag::err_omp_expected_clause)
620 << getOpenMPDirectiveName(OMPD_declare_mapper);
621 IsCorrect = false;
622 }
623
624 // Exit scope.
625 Actions.EndOpenMPDSABlock(nullptr);
626 OMPDirectiveScope.Exit();
627 DeclGroupPtrTy DG = Actions.ActOnOpenMPDeclareMapperDirective(
628 getCurScope(), Actions.getCurLexicalContext(), MapperId, MapperType,
629 Range.getBegin(), VName, AS, MapperVarRef.get(), Clauses);
630 if (!IsCorrect)
631 return DeclGroupPtrTy();
632
633 return DG;
634}
635
636TypeResult Parser::parseOpenMPDeclareMapperVarDecl(SourceRange &Range,
637 DeclarationName &Name,
638 AccessSpecifier AS) {
639 // Parse the common declaration-specifiers piece.
640 Parser::DeclSpecContext DSC = Parser::DeclSpecContext::DSC_type_specifier;
641 DeclSpec DS(AttrFactory);
642 ParseSpecifierQualifierList(DS, AS, DSC);
643
644 // Parse the declarator.
645 DeclaratorContext Context = DeclaratorContext::Prototype;
646 Declarator DeclaratorInfo(DS, ParsedAttributesView::none(), Context);
647 ParseDeclarator(DeclaratorInfo);
648 Range = DeclaratorInfo.getSourceRange();
649 if (DeclaratorInfo.getIdentifier() == nullptr) {
650 Diag(Tok.getLocation(), diag::err_omp_mapper_expected_declarator);
651 return true;
652 }
653 Name = Actions.GetNameForDeclarator(DeclaratorInfo).getName();
654
655 return Actions.ActOnOpenMPDeclareMapperVarDecl(getCurScope(), DeclaratorInfo);
656}
657
658namespace {
659/// RAII that recreates function context for correct parsing of clauses of
660/// 'declare simd' construct.
661/// OpenMP, 2.8.2 declare simd Construct
662/// The expressions appearing in the clauses of this directive are evaluated in
663/// the scope of the arguments of the function declaration or definition.
664class FNContextRAII final {
665 Parser &P;
666 Sema::CXXThisScopeRAII *ThisScope;
667 Parser::MultiParseScope Scopes;
668 bool HasFunScope = false;
669 FNContextRAII() = delete;
670 FNContextRAII(const FNContextRAII &) = delete;
671 FNContextRAII &operator=(const FNContextRAII &) = delete;
672
673public:
674 FNContextRAII(Parser &P, Parser::DeclGroupPtrTy Ptr) : P(P), Scopes(P) {
675 Decl *D = *Ptr.get().begin();
676 NamedDecl *ND = dyn_cast<NamedDecl>(D);
677 RecordDecl *RD = dyn_cast_or_null<RecordDecl>(D->getDeclContext());
678 Sema &Actions = P.getActions();
679
680 // Allow 'this' within late-parsed attributes.
681 ThisScope = new Sema::CXXThisScopeRAII(Actions, RD, Qualifiers(),
682 ND && ND->isCXXInstanceMember());
683
684 // If the Decl is templatized, add template parameters to scope.
685 // FIXME: Track CurTemplateDepth?
686 P.ReenterTemplateScopes(Scopes, D);
687
688 // If the Decl is on a function, add function parameters to the scope.
689 if (D->isFunctionOrFunctionTemplate()) {
690 HasFunScope = true;
691 Scopes.Enter(Scope::FnScope | Scope::DeclScope |
692 Scope::CompoundStmtScope);
693 Actions.ActOnReenterFunctionContext(Actions.getCurScope(), D);
694 }
695 }
696 ~FNContextRAII() {
697 if (HasFunScope)
698 P.getActions().ActOnExitFunctionContext();
699 delete ThisScope;
700 }
701};
702} // namespace
703
704/// Parses clauses for 'declare simd' directive.
705/// clause:
706/// 'inbranch' | 'notinbranch'
707/// 'simdlen' '(' <expr> ')'
708/// { 'uniform' '(' <argument_list> ')' }
709/// { 'aligned '(' <argument_list> [ ':' <alignment> ] ')' }
710/// { 'linear '(' <argument_list> [ ':' <step> ] ')' }
711static bool parseDeclareSimdClauses(
712 Parser &P, OMPDeclareSimdDeclAttr::BranchStateTy &BS, ExprResult &SimdLen,
713 SmallVectorImpl<Expr *> &Uniforms, SmallVectorImpl<Expr *> &Aligneds,
714 SmallVectorImpl<Expr *> &Alignments, SmallVectorImpl<Expr *> &Linears,
715 SmallVectorImpl<unsigned> &LinModifiers, SmallVectorImpl<Expr *> &Steps) {
716 SourceRange BSRange;
717 const Token &Tok = P.getCurToken();
718 bool IsError = false;
719 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
720 if (Tok.isNot(tok::identifier))
721 break;
722 OMPDeclareSimdDeclAttr::BranchStateTy Out;
723 IdentifierInfo *II = Tok.getIdentifierInfo();
724 StringRef ClauseName = II->getName();
725 // Parse 'inranch|notinbranch' clauses.
726 if (OMPDeclareSimdDeclAttr::ConvertStrToBranchStateTy(ClauseName, Out)) {
727 if (BS != OMPDeclareSimdDeclAttr::BS_Undefined && BS != Out) {
728 P.Diag(Tok, diag::err_omp_declare_simd_inbranch_notinbranch)
729 << ClauseName
730 << OMPDeclareSimdDeclAttr::ConvertBranchStateTyToStr(BS) << BSRange;
731 IsError = true;
732 }
733 BS = Out;
734 BSRange = SourceRange(Tok.getLocation(), Tok.getEndLoc());
735 P.ConsumeToken();
736 } else if (ClauseName.equals("simdlen")) {
737 if (SimdLen.isUsable()) {
738 P.Diag(Tok, diag::err_omp_more_one_clause)
739 << getOpenMPDirectiveName(OMPD_declare_simd) << ClauseName << 0;
740 IsError = true;
741 }
742 P.ConsumeToken();
743 SourceLocation RLoc;
744 SimdLen = P.ParseOpenMPParensExpr(ClauseName, RLoc);
745 if (SimdLen.isInvalid())
746 IsError = true;
747 } else {
748 OpenMPClauseKind CKind = getOpenMPClauseKind(ClauseName);
749 if (CKind == OMPC_uniform || CKind == OMPC_aligned ||
750 CKind == OMPC_linear) {
751 Sema::OpenMPVarListDataTy Data;
752 SmallVectorImpl<Expr *> *Vars = &Uniforms;
753 if (CKind == OMPC_aligned) {
754 Vars = &Aligneds;
755 } else if (CKind == OMPC_linear) {
756 Data.ExtraModifier = OMPC_LINEAR_val;
757 Vars = &Linears;
758 }
759
760 P.ConsumeToken();
761 if (P.ParseOpenMPVarList(OMPD_declare_simd,
762 getOpenMPClauseKind(ClauseName), *Vars, Data))
763 IsError = true;
764 if (CKind == OMPC_aligned) {
765 Alignments.append(Aligneds.size() - Alignments.size(),
766 Data.DepModOrTailExpr);
767 } else if (CKind == OMPC_linear) {
768 assert(0 <= Data.ExtraModifier &&(static_cast <bool> (0 <= Data.ExtraModifier &&
Data.ExtraModifier <= OMPC_LINEAR_unknown && "Unexpected linear modifier."
) ? void (0) : __assert_fail ("0 <= Data.ExtraModifier && Data.ExtraModifier <= OMPC_LINEAR_unknown && \"Unexpected linear modifier.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 770, __extension__ __PRETTY_FUNCTION__
))
769 Data.ExtraModifier <= OMPC_LINEAR_unknown &&(static_cast <bool> (0 <= Data.ExtraModifier &&
Data.ExtraModifier <= OMPC_LINEAR_unknown && "Unexpected linear modifier."
) ? void (0) : __assert_fail ("0 <= Data.ExtraModifier && Data.ExtraModifier <= OMPC_LINEAR_unknown && \"Unexpected linear modifier.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 770, __extension__ __PRETTY_FUNCTION__
))
770 "Unexpected linear modifier.")(static_cast <bool> (0 <= Data.ExtraModifier &&
Data.ExtraModifier <= OMPC_LINEAR_unknown && "Unexpected linear modifier."
) ? void (0) : __assert_fail ("0 <= Data.ExtraModifier && Data.ExtraModifier <= OMPC_LINEAR_unknown && \"Unexpected linear modifier.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 770, __extension__ __PRETTY_FUNCTION__
))
;
771 if (P.getActions().CheckOpenMPLinearModifier(
772 static_cast<OpenMPLinearClauseKind>(Data.ExtraModifier),
773 Data.ExtraModifierLoc))
774 Data.ExtraModifier = OMPC_LINEAR_val;
775 LinModifiers.append(Linears.size() - LinModifiers.size(),
776 Data.ExtraModifier);
777 Steps.append(Linears.size() - Steps.size(), Data.DepModOrTailExpr);
778 }
779 } else
780 // TODO: add parsing of other clauses.
781 break;
782 }
783 // Skip ',' if any.
784 if (Tok.is(tok::comma))
785 P.ConsumeToken();
786 }
787 return IsError;
788}
789
790/// Parse clauses for '#pragma omp declare simd'.
791Parser::DeclGroupPtrTy
792Parser::ParseOMPDeclareSimdClauses(Parser::DeclGroupPtrTy Ptr,
793 CachedTokens &Toks, SourceLocation Loc) {
794 PP.EnterToken(Tok, /*IsReinject*/ true);
795 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
796 /*IsReinject*/ true);
797 // Consume the previously pushed token.
798 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
799 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
800
801 FNContextRAII FnContext(*this, Ptr);
802 OMPDeclareSimdDeclAttr::BranchStateTy BS =
803 OMPDeclareSimdDeclAttr::BS_Undefined;
804 ExprResult Simdlen;
805 SmallVector<Expr *, 4> Uniforms;
806 SmallVector<Expr *, 4> Aligneds;
807 SmallVector<Expr *, 4> Alignments;
808 SmallVector<Expr *, 4> Linears;
809 SmallVector<unsigned, 4> LinModifiers;
810 SmallVector<Expr *, 4> Steps;
811 bool IsError =
812 parseDeclareSimdClauses(*this, BS, Simdlen, Uniforms, Aligneds,
813 Alignments, Linears, LinModifiers, Steps);
814 skipUntilPragmaOpenMPEnd(OMPD_declare_simd);
815 // Skip the last annot_pragma_openmp_end.
816 SourceLocation EndLoc = ConsumeAnnotationToken();
817 if (IsError)
818 return Ptr;
819 return Actions.ActOnOpenMPDeclareSimdDirective(
820 Ptr, BS, Simdlen.get(), Uniforms, Aligneds, Alignments, Linears,
821 LinModifiers, Steps, SourceRange(Loc, EndLoc));
822}
823
824namespace {
825/// Constant used in the diagnostics to distinguish the levels in an OpenMP
826/// contexts: selector-set={selector(trait, ...), ...}, ....
827enum OMPContextLvl {
828 CONTEXT_SELECTOR_SET_LVL = 0,
829 CONTEXT_SELECTOR_LVL = 1,
830 CONTEXT_TRAIT_LVL = 2,
831};
832
833static StringRef stringLiteralParser(Parser &P) {
834 ExprResult Res = P.ParseStringLiteralExpression(true);
835 return Res.isUsable() ? Res.getAs<StringLiteral>()->getString() : "";
836}
837
838static StringRef getNameFromIdOrString(Parser &P, Token &Tok,
839 OMPContextLvl Lvl) {
840 if (Tok.is(tok::identifier) || Tok.is(tok::kw_for)) {
841 llvm::SmallString<16> Buffer;
842 StringRef Name = P.getPreprocessor().getSpelling(Tok, Buffer);
843 (void)P.ConsumeToken();
844 return Name;
845 }
846
847 if (tok::isStringLiteral(Tok.getKind()))
848 return stringLiteralParser(P);
849
850 P.Diag(Tok.getLocation(),
851 diag::warn_omp_declare_variant_string_literal_or_identifier)
852 << Lvl;
853 return "";
854}
855
856static bool checkForDuplicates(Parser &P, StringRef Name,
857 SourceLocation NameLoc,
858 llvm::StringMap<SourceLocation> &Seen,
859 OMPContextLvl Lvl) {
860 auto Res = Seen.try_emplace(Name, NameLoc);
861 if (Res.second)
862 return false;
863
864 // Each trait-set-selector-name, trait-selector-name and trait-name can
865 // only be specified once.
866 P.Diag(NameLoc, diag::warn_omp_declare_variant_ctx_mutiple_use)
867 << Lvl << Name;
868 P.Diag(Res.first->getValue(), diag::note_omp_declare_variant_ctx_used_here)
869 << Lvl << Name;
870 return true;
871}
872} // namespace
873
874void Parser::parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty,
875 llvm::omp::TraitSet Set,
876 llvm::omp::TraitSelector Selector,
877 llvm::StringMap<SourceLocation> &Seen) {
878 TIProperty.Kind = TraitProperty::invalid;
879
880 SourceLocation NameLoc = Tok.getLocation();
881 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_TRAIT_LVL);
882 if (Name.empty()) {
883 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
884 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
885 return;
886 }
887
888 TIProperty.RawString = Name;
889 TIProperty.Kind = getOpenMPContextTraitPropertyKind(Set, Selector, Name);
890 if (TIProperty.Kind != TraitProperty::invalid) {
891 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_TRAIT_LVL))
892 TIProperty.Kind = TraitProperty::invalid;
893 return;
894 }
895
896 // It follows diagnosis and helping notes.
897 // FIXME: We should move the diagnosis string generation into libFrontend.
898 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_property)
899 << Name << getOpenMPContextTraitSelectorName(Selector)
900 << getOpenMPContextTraitSetName(Set);
901
902 TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
903 if (SetForName != TraitSet::invalid) {
904 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
905 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_TRAIT_LVL;
906 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
907 << Name << "<selector-name>"
908 << "(<property-name>)";
909 return;
910 }
911 TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
912 if (SelectorForName != TraitSelector::invalid) {
913 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
914 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_TRAIT_LVL;
915 bool AllowsTraitScore = false;
916 bool RequiresProperty = false;
917 isValidTraitSelectorForTraitSet(
918 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
919 AllowsTraitScore, RequiresProperty);
920 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
921 << getOpenMPContextTraitSetName(
922 getOpenMPContextTraitSetForSelector(SelectorForName))
923 << Name << (RequiresProperty ? "(<property-name>)" : "");
924 return;
925 }
926 for (const auto &PotentialSet :
927 {TraitSet::construct, TraitSet::user, TraitSet::implementation,
928 TraitSet::device}) {
929 TraitProperty PropertyForName =
930 getOpenMPContextTraitPropertyKind(PotentialSet, Selector, Name);
931 if (PropertyForName == TraitProperty::invalid)
932 continue;
933 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
934 << getOpenMPContextTraitSetName(
935 getOpenMPContextTraitSetForProperty(PropertyForName))
936 << getOpenMPContextTraitSelectorName(
937 getOpenMPContextTraitSelectorForProperty(PropertyForName))
938 << ("(" + Name + ")").str();
939 return;
940 }
941 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
942 << CONTEXT_TRAIT_LVL << listOpenMPContextTraitProperties(Set, Selector);
943}
944
945static bool checkExtensionProperty(Parser &P, SourceLocation Loc,
946 OMPTraitProperty &TIProperty,
947 OMPTraitSelector &TISelector,
948 llvm::StringMap<SourceLocation> &Seen) {
949 assert(TISelector.Kind ==(static_cast <bool> (TISelector.Kind == llvm::omp::TraitSelector
::implementation_extension && "Only for extension properties, e.g., "
"`implementation={extension(PROPERTY)}`") ? void (0) : __assert_fail
("TISelector.Kind == llvm::omp::TraitSelector::implementation_extension && \"Only for extension properties, e.g., \" \"`implementation={extension(PROPERTY)}`\""
, "clang/lib/Parse/ParseOpenMP.cpp", 952, __extension__ __PRETTY_FUNCTION__
))
950 llvm::omp::TraitSelector::implementation_extension &&(static_cast <bool> (TISelector.Kind == llvm::omp::TraitSelector
::implementation_extension && "Only for extension properties, e.g., "
"`implementation={extension(PROPERTY)}`") ? void (0) : __assert_fail
("TISelector.Kind == llvm::omp::TraitSelector::implementation_extension && \"Only for extension properties, e.g., \" \"`implementation={extension(PROPERTY)}`\""
, "clang/lib/Parse/ParseOpenMP.cpp", 952, __extension__ __PRETTY_FUNCTION__
))
951 "Only for extension properties, e.g., "(static_cast <bool> (TISelector.Kind == llvm::omp::TraitSelector
::implementation_extension && "Only for extension properties, e.g., "
"`implementation={extension(PROPERTY)}`") ? void (0) : __assert_fail
("TISelector.Kind == llvm::omp::TraitSelector::implementation_extension && \"Only for extension properties, e.g., \" \"`implementation={extension(PROPERTY)}`\""
, "clang/lib/Parse/ParseOpenMP.cpp", 952, __extension__ __PRETTY_FUNCTION__
))
952 "`implementation={extension(PROPERTY)}`")(static_cast <bool> (TISelector.Kind == llvm::omp::TraitSelector
::implementation_extension && "Only for extension properties, e.g., "
"`implementation={extension(PROPERTY)}`") ? void (0) : __assert_fail
("TISelector.Kind == llvm::omp::TraitSelector::implementation_extension && \"Only for extension properties, e.g., \" \"`implementation={extension(PROPERTY)}`\""
, "clang/lib/Parse/ParseOpenMP.cpp", 952, __extension__ __PRETTY_FUNCTION__
))
;
953 if (TIProperty.Kind == TraitProperty::invalid)
954 return false;
955
956 if (TIProperty.Kind ==
957 TraitProperty::implementation_extension_disable_implicit_base)
958 return true;
959
960 if (TIProperty.Kind ==
961 TraitProperty::implementation_extension_allow_templates)
962 return true;
963
964 if (TIProperty.Kind ==
965 TraitProperty::implementation_extension_bind_to_declaration)
966 return true;
967
968 auto IsMatchExtension = [](OMPTraitProperty &TP) {
969 return (TP.Kind ==
970 llvm::omp::TraitProperty::implementation_extension_match_all ||
971 TP.Kind ==
972 llvm::omp::TraitProperty::implementation_extension_match_any ||
973 TP.Kind ==
974 llvm::omp::TraitProperty::implementation_extension_match_none);
975 };
976
977 if (IsMatchExtension(TIProperty)) {
978 for (OMPTraitProperty &SeenProp : TISelector.Properties)
979 if (IsMatchExtension(SeenProp)) {
980 P.Diag(Loc, diag::err_omp_variant_ctx_second_match_extension);
981 StringRef SeenName = llvm::omp::getOpenMPContextTraitPropertyName(
982 SeenProp.Kind, SeenProp.RawString);
983 SourceLocation SeenLoc = Seen[SeenName];
984 P.Diag(SeenLoc, diag::note_omp_declare_variant_ctx_used_here)
985 << CONTEXT_TRAIT_LVL << SeenName;
986 return false;
987 }
988 return true;
989 }
990
991 llvm_unreachable("Unknown extension property!")::llvm::llvm_unreachable_internal("Unknown extension property!"
, "clang/lib/Parse/ParseOpenMP.cpp", 991)
;
992}
993
994void Parser::parseOMPContextProperty(OMPTraitSelector &TISelector,
995 llvm::omp::TraitSet Set,
996 llvm::StringMap<SourceLocation> &Seen) {
997 assert(TISelector.Kind != TraitSelector::user_condition &&(static_cast <bool> (TISelector.Kind != TraitSelector::
user_condition && "User conditions are special properties not handled here!"
) ? void (0) : __assert_fail ("TISelector.Kind != TraitSelector::user_condition && \"User conditions are special properties not handled here!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 998, __extension__ __PRETTY_FUNCTION__
))
998 "User conditions are special properties not handled here!")(static_cast <bool> (TISelector.Kind != TraitSelector::
user_condition && "User conditions are special properties not handled here!"
) ? void (0) : __assert_fail ("TISelector.Kind != TraitSelector::user_condition && \"User conditions are special properties not handled here!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 998, __extension__ __PRETTY_FUNCTION__
))
;
999
1000 SourceLocation PropertyLoc = Tok.getLocation();
1001 OMPTraitProperty TIProperty;
1002 parseOMPTraitPropertyKind(TIProperty, Set, TISelector.Kind, Seen);
1003
1004 if (TISelector.Kind == llvm::omp::TraitSelector::implementation_extension)
1005 if (!checkExtensionProperty(*this, Tok.getLocation(), TIProperty,
1006 TISelector, Seen))
1007 TIProperty.Kind = TraitProperty::invalid;
1008
1009 // If we have an invalid property here we already issued a warning.
1010 if (TIProperty.Kind == TraitProperty::invalid) {
1011 if (PropertyLoc != Tok.getLocation())
1012 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1013 << CONTEXT_TRAIT_LVL;
1014 return;
1015 }
1016
1017 if (isValidTraitPropertyForTraitSetAndSelector(TIProperty.Kind,
1018 TISelector.Kind, Set)) {
1019
1020 // If we make it here the property, selector, set, score, condition, ... are
1021 // all valid (or have been corrected). Thus we can record the property.
1022 TISelector.Properties.push_back(TIProperty);
1023 return;
1024 }
1025
1026 Diag(PropertyLoc, diag::warn_omp_ctx_incompatible_property_for_selector)
1027 << getOpenMPContextTraitPropertyName(TIProperty.Kind,
1028 TIProperty.RawString)
1029 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1030 << getOpenMPContextTraitSetName(Set);
1031 Diag(PropertyLoc, diag::note_omp_ctx_compatible_set_and_selector_for_property)
1032 << getOpenMPContextTraitPropertyName(TIProperty.Kind,
1033 TIProperty.RawString)
1034 << getOpenMPContextTraitSelectorName(
1035 getOpenMPContextTraitSelectorForProperty(TIProperty.Kind))
1036 << getOpenMPContextTraitSetName(
1037 getOpenMPContextTraitSetForProperty(TIProperty.Kind));
1038 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1039 << CONTEXT_TRAIT_LVL;
1040}
1041
1042void Parser::parseOMPTraitSelectorKind(OMPTraitSelector &TISelector,
1043 llvm::omp::TraitSet Set,
1044 llvm::StringMap<SourceLocation> &Seen) {
1045 TISelector.Kind = TraitSelector::invalid;
1046
1047 SourceLocation NameLoc = Tok.getLocation();
1048 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_LVL);
1049 if (Name.empty()) {
1050 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1051 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1052 return;
1053 }
1054
1055 TISelector.Kind = getOpenMPContextTraitSelectorKind(Name);
1056 if (TISelector.Kind != TraitSelector::invalid) {
1057 if (checkForDuplicates(*this, Name, NameLoc, Seen, CONTEXT_SELECTOR_LVL))
1058 TISelector.Kind = TraitSelector::invalid;
1059 return;
1060 }
1061
1062 // It follows diagnosis and helping notes.
1063 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_selector)
1064 << Name << getOpenMPContextTraitSetName(Set);
1065
1066 TraitSet SetForName = getOpenMPContextTraitSetKind(Name);
1067 if (SetForName != TraitSet::invalid) {
1068 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1069 << Name << CONTEXT_SELECTOR_SET_LVL << CONTEXT_SELECTOR_LVL;
1070 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1071 << Name << "<selector-name>"
1072 << "<property-name>";
1073 return;
1074 }
1075 for (const auto &PotentialSet :
1076 {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1077 TraitSet::device}) {
1078 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
1079 PotentialSet, TraitSelector::invalid, Name);
1080 if (PropertyForName == TraitProperty::invalid)
1081 continue;
1082 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1083 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_LVL;
1084 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1085 << getOpenMPContextTraitSetName(
1086 getOpenMPContextTraitSetForProperty(PropertyForName))
1087 << getOpenMPContextTraitSelectorName(
1088 getOpenMPContextTraitSelectorForProperty(PropertyForName))
1089 << ("(" + Name + ")").str();
1090 return;
1091 }
1092 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1093 << CONTEXT_SELECTOR_LVL << listOpenMPContextTraitSelectors(Set);
1094}
1095
1096/// Parse optional 'score' '(' <expr> ')' ':'.
1097static ExprResult parseContextScore(Parser &P) {
1098 ExprResult ScoreExpr;
1099 llvm::SmallString<16> Buffer;
1100 StringRef SelectorName =
1101 P.getPreprocessor().getSpelling(P.getCurToken(), Buffer);
1102 if (!SelectorName.equals("score"))
1103 return ScoreExpr;
1104 (void)P.ConsumeToken();
1105 SourceLocation RLoc;
1106 ScoreExpr = P.ParseOpenMPParensExpr(SelectorName, RLoc);
1107 // Parse ':'
1108 if (P.getCurToken().is(tok::colon))
1109 (void)P.ConsumeAnyToken();
1110 else
1111 P.Diag(P.getCurToken(), diag::warn_omp_declare_variant_expected)
1112 << "':'"
1113 << "score expression";
1114 return ScoreExpr;
1115}
1116
1117/// Parses an OpenMP context selector.
1118///
1119/// <trait-selector-name> ['('[<trait-score>] <trait-property> [, <t-p>]* ')']
1120void Parser::parseOMPContextSelector(
1121 OMPTraitSelector &TISelector, llvm::omp::TraitSet Set,
1122 llvm::StringMap<SourceLocation> &SeenSelectors) {
1123 unsigned short OuterPC = ParenCount;
1124
1125 // If anything went wrong we issue an error or warning and then skip the rest
1126 // of the selector. However, commas are ambiguous so we look for the nesting
1127 // of parentheses here as well.
1128 auto FinishSelector = [OuterPC, this]() -> void {
1129 bool Done = false;
1130 while (!Done) {
1131 while (!SkipUntil({tok::r_brace, tok::r_paren, tok::comma,
1132 tok::annot_pragma_openmp_end},
1133 StopBeforeMatch))
1134 ;
1135 if (Tok.is(tok::r_paren) && OuterPC > ParenCount)
1136 (void)ConsumeParen();
1137 if (OuterPC <= ParenCount) {
1138 Done = true;
1139 break;
1140 }
1141 if (!Tok.is(tok::comma) && !Tok.is(tok::r_paren)) {
1142 Done = true;
1143 break;
1144 }
1145 (void)ConsumeAnyToken();
1146 }
1147 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1148 << CONTEXT_SELECTOR_LVL;
1149 };
1150
1151 SourceLocation SelectorLoc = Tok.getLocation();
1152 parseOMPTraitSelectorKind(TISelector, Set, SeenSelectors);
1153 if (TISelector.Kind == TraitSelector::invalid)
1154 return FinishSelector();
1155
1156 bool AllowsTraitScore = false;
1157 bool RequiresProperty = false;
1158 if (!isValidTraitSelectorForTraitSet(TISelector.Kind, Set, AllowsTraitScore,
1159 RequiresProperty)) {
1160 Diag(SelectorLoc, diag::warn_omp_ctx_incompatible_selector_for_set)
1161 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1162 << getOpenMPContextTraitSetName(Set);
1163 Diag(SelectorLoc, diag::note_omp_ctx_compatible_set_for_selector)
1164 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1165 << getOpenMPContextTraitSetName(
1166 getOpenMPContextTraitSetForSelector(TISelector.Kind))
1167 << RequiresProperty;
1168 return FinishSelector();
1169 }
1170
1171 if (!RequiresProperty) {
1172 TISelector.Properties.push_back(
1173 {getOpenMPContextTraitPropertyForSelector(TISelector.Kind),
1174 getOpenMPContextTraitSelectorName(TISelector.Kind)});
1175 return;
1176 }
1177
1178 if (!Tok.is(tok::l_paren)) {
1179 Diag(SelectorLoc, diag::warn_omp_ctx_selector_without_properties)
1180 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1181 << getOpenMPContextTraitSetName(Set);
1182 return FinishSelector();
1183 }
1184
1185 if (TISelector.Kind == TraitSelector::user_condition) {
1186 SourceLocation RLoc;
1187 ExprResult Condition = ParseOpenMPParensExpr("user condition", RLoc);
1188 if (!Condition.isUsable())
1189 return FinishSelector();
1190 TISelector.ScoreOrCondition = Condition.get();
1191 TISelector.Properties.push_back(
1192 {TraitProperty::user_condition_unknown, "<condition>"});
1193 return;
1194 }
1195
1196 BalancedDelimiterTracker BDT(*this, tok::l_paren,
1197 tok::annot_pragma_openmp_end);
1198 // Parse '('.
1199 (void)BDT.consumeOpen();
1200
1201 SourceLocation ScoreLoc = Tok.getLocation();
1202 ExprResult Score = parseContextScore(*this);
1203
1204 if (!AllowsTraitScore && !Score.isUnset()) {
1205 if (Score.isUsable()) {
1206 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1207 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1208 << getOpenMPContextTraitSetName(Set) << Score.get();
1209 } else {
1210 Diag(ScoreLoc, diag::warn_omp_ctx_incompatible_score_for_property)
1211 << getOpenMPContextTraitSelectorName(TISelector.Kind)
1212 << getOpenMPContextTraitSetName(Set) << "<invalid>";
1213 }
1214 Score = ExprResult();
1215 }
1216
1217 if (Score.isUsable())
1218 TISelector.ScoreOrCondition = Score.get();
1219
1220 llvm::StringMap<SourceLocation> SeenProperties;
1221 do {
1222 parseOMPContextProperty(TISelector, Set, SeenProperties);
1223 } while (TryConsumeToken(tok::comma));
1224
1225 // Parse ')'.
1226 BDT.consumeClose();
1227}
1228
1229void Parser::parseOMPTraitSetKind(OMPTraitSet &TISet,
1230 llvm::StringMap<SourceLocation> &Seen) {
1231 TISet.Kind = TraitSet::invalid;
1232
1233 SourceLocation NameLoc = Tok.getLocation();
1234 StringRef Name = getNameFromIdOrString(*this, Tok, CONTEXT_SELECTOR_SET_LVL);
1235 if (Name.empty()) {
1236 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_options)
1237 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1238 return;
1239 }
1240
1241 TISet.Kind = getOpenMPContextTraitSetKind(Name);
1242 if (TISet.Kind != TraitSet::invalid) {
1243 if (checkForDuplicates(*this, Name, NameLoc, Seen,
1244 CONTEXT_SELECTOR_SET_LVL))
1245 TISet.Kind = TraitSet::invalid;
1246 return;
1247 }
1248
1249 // It follows diagnosis and helping notes.
1250 Diag(NameLoc, diag::warn_omp_declare_variant_ctx_not_a_set) << Name;
1251
1252 TraitSelector SelectorForName = getOpenMPContextTraitSelectorKind(Name);
1253 if (SelectorForName != TraitSelector::invalid) {
1254 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1255 << Name << CONTEXT_SELECTOR_LVL << CONTEXT_SELECTOR_SET_LVL;
1256 bool AllowsTraitScore = false;
1257 bool RequiresProperty = false;
1258 isValidTraitSelectorForTraitSet(
1259 SelectorForName, getOpenMPContextTraitSetForSelector(SelectorForName),
1260 AllowsTraitScore, RequiresProperty);
1261 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1262 << getOpenMPContextTraitSetName(
1263 getOpenMPContextTraitSetForSelector(SelectorForName))
1264 << Name << (RequiresProperty ? "(<property-name>)" : "");
1265 return;
1266 }
1267 for (const auto &PotentialSet :
1268 {TraitSet::construct, TraitSet::user, TraitSet::implementation,
1269 TraitSet::device}) {
1270 TraitProperty PropertyForName = getOpenMPContextTraitPropertyKind(
1271 PotentialSet, TraitSelector::invalid, Name);
1272 if (PropertyForName == TraitProperty::invalid)
1273 continue;
1274 Diag(NameLoc, diag::note_omp_declare_variant_ctx_is_a)
1275 << Name << CONTEXT_TRAIT_LVL << CONTEXT_SELECTOR_SET_LVL;
1276 Diag(NameLoc, diag::note_omp_declare_variant_ctx_try)
1277 << getOpenMPContextTraitSetName(
1278 getOpenMPContextTraitSetForProperty(PropertyForName))
1279 << getOpenMPContextTraitSelectorName(
1280 getOpenMPContextTraitSelectorForProperty(PropertyForName))
1281 << ("(" + Name + ")").str();
1282 return;
1283 }
1284 Diag(NameLoc, diag::note_omp_declare_variant_ctx_options)
1285 << CONTEXT_SELECTOR_SET_LVL << listOpenMPContextTraitSets();
1286}
1287
1288/// Parses an OpenMP context selector set.
1289///
1290/// <trait-set-selector-name> '=' '{' <trait-selector> [, <trait-selector>]* '}'
1291void Parser::parseOMPContextSelectorSet(
1292 OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets) {
1293 auto OuterBC = BraceCount;
1294
1295 // If anything went wrong we issue an error or warning and then skip the rest
1296 // of the set. However, commas are ambiguous so we look for the nesting
1297 // of braces here as well.
1298 auto FinishSelectorSet = [this, OuterBC]() -> void {
1299 bool Done = false;
1300 while (!Done) {
1301 while (!SkipUntil({tok::comma, tok::r_brace, tok::r_paren,
1302 tok::annot_pragma_openmp_end},
1303 StopBeforeMatch))
1304 ;
1305 if (Tok.is(tok::r_brace) && OuterBC > BraceCount)
1306 (void)ConsumeBrace();
1307 if (OuterBC <= BraceCount) {
1308 Done = true;
1309 break;
1310 }
1311 if (!Tok.is(tok::comma) && !Tok.is(tok::r_brace)) {
1312 Done = true;
1313 break;
1314 }
1315 (void)ConsumeAnyToken();
1316 }
1317 Diag(Tok.getLocation(), diag::note_omp_declare_variant_ctx_continue_here)
1318 << CONTEXT_SELECTOR_SET_LVL;
1319 };
1320
1321 parseOMPTraitSetKind(TISet, SeenSets);
1322 if (TISet.Kind == TraitSet::invalid)
1323 return FinishSelectorSet();
1324
1325 // Parse '='.
1326 if (!TryConsumeToken(tok::equal))
1327 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1328 << "="
1329 << ("context set name \"" + getOpenMPContextTraitSetName(TISet.Kind) +
1330 "\"")
1331 .str();
1332
1333 // Parse '{'.
1334 if (Tok.is(tok::l_brace)) {
1335 (void)ConsumeBrace();
1336 } else {
1337 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1338 << "{"
1339 << ("'=' that follows the context set name \"" +
1340 getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1341 .str();
1342 }
1343
1344 llvm::StringMap<SourceLocation> SeenSelectors;
1345 do {
1346 OMPTraitSelector TISelector;
1347 parseOMPContextSelector(TISelector, TISet.Kind, SeenSelectors);
1348 if (TISelector.Kind != TraitSelector::invalid &&
1349 !TISelector.Properties.empty())
1350 TISet.Selectors.push_back(TISelector);
1351 } while (TryConsumeToken(tok::comma));
1352
1353 // Parse '}'.
1354 if (Tok.is(tok::r_brace)) {
1355 (void)ConsumeBrace();
1356 } else {
1357 Diag(Tok.getLocation(), diag::warn_omp_declare_variant_expected)
1358 << "}"
1359 << ("context selectors for the context set \"" +
1360 getOpenMPContextTraitSetName(TISet.Kind) + "\"")
1361 .str();
1362 }
1363}
1364
1365/// Parse OpenMP context selectors:
1366///
1367/// <trait-set-selector> [, <trait-set-selector>]*
1368bool Parser::parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI) {
1369 llvm::StringMap<SourceLocation> SeenSets;
1370 do {
1371 OMPTraitSet TISet;
1372 parseOMPContextSelectorSet(TISet, SeenSets);
1373 if (TISet.Kind != TraitSet::invalid && !TISet.Selectors.empty())
1374 TI.Sets.push_back(TISet);
1375 } while (TryConsumeToken(tok::comma));
1376
1377 return false;
1378}
1379
1380/// Parse clauses for '#pragma omp declare variant ( variant-func-id ) clause'.
1381void Parser::ParseOMPDeclareVariantClauses(Parser::DeclGroupPtrTy Ptr,
1382 CachedTokens &Toks,
1383 SourceLocation Loc) {
1384 PP.EnterToken(Tok, /*IsReinject*/ true);
1385 PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
1386 /*IsReinject*/ true);
1387 // Consume the previously pushed token.
1388 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1389 ConsumeAnyToken(/*ConsumeCodeCompletionTok=*/true);
1390
1391 FNContextRAII FnContext(*this, Ptr);
1392 // Parse function declaration id.
1393 SourceLocation RLoc;
1394 // Parse with IsAddressOfOperand set to true to parse methods as DeclRefExprs
1395 // instead of MemberExprs.
1396 ExprResult AssociatedFunction;
1397 {
1398 // Do not mark function as is used to prevent its emission if this is the
1399 // only place where it is used.
1400 EnterExpressionEvaluationContext Unevaluated(
1401 Actions, Sema::ExpressionEvaluationContext::Unevaluated);
1402 AssociatedFunction = ParseOpenMPParensExpr(
1403 getOpenMPDirectiveName(OMPD_declare_variant), RLoc,
1404 /*IsAddressOfOperand=*/true);
1405 }
1406 if (!AssociatedFunction.isUsable()) {
1407 if (!Tok.is(tok::annot_pragma_openmp_end))
1408 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1409 ;
1410 // Skip the last annot_pragma_openmp_end.
1411 (void)ConsumeAnnotationToken();
1412 return;
1413 }
1414
1415 OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope();
1416 ASTContext &ASTCtx = Actions.getASTContext();
1417 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
1418 SmallVector<Expr *, 6> AdjustNothing;
1419 SmallVector<Expr *, 6> AdjustNeedDevicePtr;
1420 SmallVector<OMPInteropInfo, 3> AppendArgs;
1421 SourceLocation AdjustArgsLoc, AppendArgsLoc;
1422
1423 // At least one clause is required.
1424 if (Tok.is(tok::annot_pragma_openmp_end)) {
1425 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1426 << (getLangOpts().OpenMP < 51 ? 0 : 1);
1427 }
1428
1429 bool IsError = false;
1430 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1431 OpenMPClauseKind CKind = Tok.isAnnotation()
1432 ? OMPC_unknown
1433 : getOpenMPClauseKind(PP.getSpelling(Tok));
1434 if (!isAllowedClauseForDirective(OMPD_declare_variant, CKind,
1435 getLangOpts().OpenMP)) {
1436 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1437 << (getLangOpts().OpenMP < 51 ? 0 : 1);
1438 IsError = true;
1439 }
1440 if (!IsError) {
1441 switch (CKind) {
1442 case OMPC_match:
1443 IsError = parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI);
1444 break;
1445 case OMPC_adjust_args: {
1446 AdjustArgsLoc = Tok.getLocation();
1447 ConsumeToken();
1448 Sema::OpenMPVarListDataTy Data;
1449 SmallVector<Expr *> Vars;
1450 IsError = ParseOpenMPVarList(OMPD_declare_variant, OMPC_adjust_args,
1451 Vars, Data);
1452 if (!IsError)
1453 llvm::append_range(Data.ExtraModifier == OMPC_ADJUST_ARGS_nothing
1454 ? AdjustNothing
1455 : AdjustNeedDevicePtr,
1456 Vars);
1457 break;
1458 }
1459 case OMPC_append_args:
1460 if (!AppendArgs.empty()) {
1461 Diag(AppendArgsLoc, diag::err_omp_more_one_clause)
1462 << getOpenMPDirectiveName(OMPD_declare_variant)
1463 << getOpenMPClauseName(CKind) << 0;
1464 IsError = true;
1465 }
1466 if (!IsError) {
1467 AppendArgsLoc = Tok.getLocation();
1468 ConsumeToken();
1469 IsError = parseOpenMPAppendArgs(AppendArgs);
1470 }
1471 break;
1472 default:
1473 llvm_unreachable("Unexpected clause for declare variant.")::llvm::llvm_unreachable_internal("Unexpected clause for declare variant."
, "clang/lib/Parse/ParseOpenMP.cpp", 1473)
;
1474 }
1475 }
1476 if (IsError) {
1477 while (!SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch))
1478 ;
1479 // Skip the last annot_pragma_openmp_end.
1480 (void)ConsumeAnnotationToken();
1481 return;
1482 }
1483 // Skip ',' if any.
1484 if (Tok.is(tok::comma))
1485 ConsumeToken();
1486 }
1487
1488 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
1489 Actions.checkOpenMPDeclareVariantFunction(
1490 Ptr, AssociatedFunction.get(), TI, AppendArgs.size(),
1491 SourceRange(Loc, Tok.getLocation()));
1492
1493 if (DeclVarData && !TI.Sets.empty())
1494 Actions.ActOnOpenMPDeclareVariantDirective(
1495 DeclVarData->first, DeclVarData->second, TI, AdjustNothing,
1496 AdjustNeedDevicePtr, AppendArgs, AdjustArgsLoc, AppendArgsLoc,
1497 SourceRange(Loc, Tok.getLocation()));
1498
1499 // Skip the last annot_pragma_openmp_end.
1500 (void)ConsumeAnnotationToken();
1501}
1502
1503bool Parser::parseOpenMPAppendArgs(
1504 SmallVectorImpl<OMPInteropInfo> &InteropInfos) {
1505 bool HasError = false;
1506 // Parse '('.
1507 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1508 if (T.expectAndConsume(diag::err_expected_lparen_after,
1509 getOpenMPClauseName(OMPC_append_args).data()))
1510 return true;
1511
1512 // Parse the list of append-ops, each is;
1513 // interop(interop-type[,interop-type]...)
1514 while (Tok.is(tok::identifier) && Tok.getIdentifierInfo()->isStr("interop")) {
1515 ConsumeToken();
1516 BalancedDelimiterTracker IT(*this, tok::l_paren,
1517 tok::annot_pragma_openmp_end);
1518 if (IT.expectAndConsume(diag::err_expected_lparen_after, "interop"))
1519 return true;
1520
1521 OMPInteropInfo InteropInfo;
1522 if (ParseOMPInteropInfo(InteropInfo, OMPC_append_args))
1523 HasError = true;
1524 else
1525 InteropInfos.push_back(InteropInfo);
1526
1527 IT.consumeClose();
1528 if (Tok.is(tok::comma))
1529 ConsumeToken();
1530 }
1531 if (!HasError && InteropInfos.empty()) {
1532 HasError = true;
1533 Diag(Tok.getLocation(), diag::err_omp_unexpected_append_op);
1534 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
1535 StopBeforeMatch);
1536 }
1537 HasError = T.consumeClose() || HasError;
1538 return HasError;
1539}
1540
1541bool Parser::parseOMPDeclareVariantMatchClause(SourceLocation Loc,
1542 OMPTraitInfo &TI,
1543 OMPTraitInfo *ParentTI) {
1544 // Parse 'match'.
1545 OpenMPClauseKind CKind = Tok.isAnnotation()
1546 ? OMPC_unknown
1547 : getOpenMPClauseKind(PP.getSpelling(Tok));
1548 if (CKind != OMPC_match) {
1549 Diag(Tok.getLocation(), diag::err_omp_declare_variant_wrong_clause)
1550 << (getLangOpts().OpenMP < 51 ? 0 : 1);
1551 return true;
1552 }
1553 (void)ConsumeToken();
1554 // Parse '('.
1555 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
1556 if (T.expectAndConsume(diag::err_expected_lparen_after,
1557 getOpenMPClauseName(OMPC_match).data()))
1558 return true;
1559
1560 // Parse inner context selectors.
1561 parseOMPContextSelectors(Loc, TI);
1562
1563 // Parse ')'
1564 (void)T.consumeClose();
1565
1566 if (!ParentTI)
1567 return false;
1568
1569 // Merge the parent/outer trait info into the one we just parsed and diagnose
1570 // problems.
1571 // TODO: Keep some source location in the TI to provide better diagnostics.
1572 // TODO: Perform some kind of equivalence check on the condition and score
1573 // expressions.
1574 for (const OMPTraitSet &ParentSet : ParentTI->Sets) {
1575 bool MergedSet = false;
1576 for (OMPTraitSet &Set : TI.Sets) {
1577 if (Set.Kind != ParentSet.Kind)
1578 continue;
1579 MergedSet = true;
1580 for (const OMPTraitSelector &ParentSelector : ParentSet.Selectors) {
1581 bool MergedSelector = false;
1582 for (OMPTraitSelector &Selector : Set.Selectors) {
1583 if (Selector.Kind != ParentSelector.Kind)
1584 continue;
1585 MergedSelector = true;
1586 for (const OMPTraitProperty &ParentProperty :
1587 ParentSelector.Properties) {
1588 bool MergedProperty = false;
1589 for (OMPTraitProperty &Property : Selector.Properties) {
1590 // Ignore "equivalent" properties.
1591 if (Property.Kind != ParentProperty.Kind)
1592 continue;
1593
1594 // If the kind is the same but the raw string not, we don't want
1595 // to skip out on the property.
1596 MergedProperty |= Property.RawString == ParentProperty.RawString;
1597
1598 if (Property.RawString == ParentProperty.RawString &&
1599 Selector.ScoreOrCondition == ParentSelector.ScoreOrCondition)
1600 continue;
1601
1602 if (Selector.Kind == llvm::omp::TraitSelector::user_condition) {
1603 Diag(Loc, diag::err_omp_declare_variant_nested_user_condition);
1604 } else if (Selector.ScoreOrCondition !=
1605 ParentSelector.ScoreOrCondition) {
1606 Diag(Loc, diag::err_omp_declare_variant_duplicate_nested_trait)
1607 << getOpenMPContextTraitPropertyName(
1608 ParentProperty.Kind, ParentProperty.RawString)
1609 << getOpenMPContextTraitSelectorName(ParentSelector.Kind)
1610 << getOpenMPContextTraitSetName(ParentSet.Kind);
1611 }
1612 }
1613 if (!MergedProperty)
1614 Selector.Properties.push_back(ParentProperty);
1615 }
1616 }
1617 if (!MergedSelector)
1618 Set.Selectors.push_back(ParentSelector);
1619 }
1620 }
1621 if (!MergedSet)
1622 TI.Sets.push_back(ParentSet);
1623 }
1624
1625 return false;
1626}
1627
1628/// <clause> [clause[ [,] clause] ... ]
1629///
1630/// clauses: for error directive
1631/// 'at' '(' compilation | execution ')'
1632/// 'severity' '(' fatal | warning ')'
1633/// 'message' '(' msg-string ')'
1634/// ....
1635void Parser::ParseOpenMPClauses(OpenMPDirectiveKind DKind,
1636 SmallVectorImpl<OMPClause *> &Clauses,
1637 SourceLocation Loc) {
1638 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
1639 llvm::omp::Clause_enumSize + 1>
1640 FirstClauses(llvm::omp::Clause_enumSize + 1);
1641 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1642 OpenMPClauseKind CKind = Tok.isAnnotation()
1643 ? OMPC_unknown
1644 : getOpenMPClauseKind(PP.getSpelling(Tok));
1645 Actions.StartOpenMPClause(CKind);
1646 OMPClause *Clause = ParseOpenMPClause(
1647 DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
1648 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
1649 StopBeforeMatch);
1650 FirstClauses[unsigned(CKind)].setInt(true);
1651 if (Clause != nullptr)
1652 Clauses.push_back(Clause);
1653 if (Tok.is(tok::annot_pragma_openmp_end)) {
1654 Actions.EndOpenMPClause();
1655 break;
1656 }
1657 // Skip ',' if any.
1658 if (Tok.is(tok::comma))
1659 ConsumeToken();
1660 Actions.EndOpenMPClause();
1661 }
1662}
1663
1664/// `omp assumes` or `omp begin/end assumes` <clause> [[,]<clause>]...
1665/// where
1666///
1667/// clause:
1668/// 'ext_IMPL_DEFINED'
1669/// 'absent' '(' directive-name [, directive-name]* ')'
1670/// 'contains' '(' directive-name [, directive-name]* ')'
1671/// 'holds' '(' scalar-expression ')'
1672/// 'no_openmp'
1673/// 'no_openmp_routines'
1674/// 'no_parallelism'
1675///
1676void Parser::ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind,
1677 SourceLocation Loc) {
1678 SmallVector<std::string, 4> Assumptions;
1679 bool SkippedClauses = false;
1680
1681 auto SkipBraces = [&](llvm::StringRef Spelling, bool IssueNote) {
1682 BalancedDelimiterTracker T(*this, tok::l_paren,
1683 tok::annot_pragma_openmp_end);
1684 if (T.expectAndConsume(diag::err_expected_lparen_after, Spelling.data()))
1685 return;
1686 T.skipToEnd();
1687 if (IssueNote && T.getCloseLocation().isValid())
1688 Diag(T.getCloseLocation(),
1689 diag::note_omp_assumption_clause_continue_here);
1690 };
1691
1692 /// Helper to determine which AssumptionClauseMapping (ACM) in the
1693 /// AssumptionClauseMappings table matches \p RawString. The return value is
1694 /// the index of the matching ACM into the table or -1 if there was no match.
1695 auto MatchACMClause = [&](StringRef RawString) {
1696 llvm::StringSwitch<int> SS(RawString);
1697 unsigned ACMIdx = 0;
1698 for (const AssumptionClauseMappingInfo &ACMI : AssumptionClauseMappings) {
1699 if (ACMI.StartsWith)
1700 SS.StartsWith(ACMI.Identifier, ACMIdx++);
1701 else
1702 SS.Case(ACMI.Identifier, ACMIdx++);
1703 }
1704 return SS.Default(-1);
1705 };
1706
1707 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1708 IdentifierInfo *II = nullptr;
1709 SourceLocation StartLoc = Tok.getLocation();
1710 int Idx = -1;
1711 if (Tok.isAnyIdentifier()) {
1712 II = Tok.getIdentifierInfo();
1713 Idx = MatchACMClause(II->getName());
1714 }
1715 ConsumeAnyToken();
1716
1717 bool NextIsLPar = Tok.is(tok::l_paren);
1718 // Handle unknown clauses by skipping them.
1719 if (Idx == -1) {
1720 Diag(StartLoc, diag::warn_omp_unknown_assumption_clause_missing_id)
1721 << llvm::omp::getOpenMPDirectiveName(DKind)
1722 << llvm::omp::getAllAssumeClauseOptions() << NextIsLPar;
1723 if (NextIsLPar)
1724 SkipBraces(II ? II->getName() : "", /* IssueNote */ true);
1725 SkippedClauses = true;
1726 continue;
1727 }
1728 const AssumptionClauseMappingInfo &ACMI = AssumptionClauseMappings[Idx];
1729 if (ACMI.HasDirectiveList || ACMI.HasExpression) {
1730 // TODO: We ignore absent, contains, and holds assumptions for now. We
1731 // also do not verify the content in the parenthesis at all.
1732 SkippedClauses = true;
1733 SkipBraces(II->getName(), /* IssueNote */ false);
1734 continue;
1735 }
1736
1737 if (NextIsLPar) {
1738 Diag(Tok.getLocation(),
1739 diag::warn_omp_unknown_assumption_clause_without_args)
1740 << II;
1741 SkipBraces(II->getName(), /* IssueNote */ true);
1742 }
1743
1744 assert(II && "Expected an identifier clause!")(static_cast <bool> (II && "Expected an identifier clause!"
) ? void (0) : __assert_fail ("II && \"Expected an identifier clause!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 1744, __extension__ __PRETTY_FUNCTION__
))
;
1745 std::string Assumption = II->getName().str();
1746 if (ACMI.StartsWith)
1747 Assumption = "ompx_" + Assumption.substr(ACMI.Identifier.size());
1748 else
1749 Assumption = "omp_" + Assumption;
1750 Assumptions.push_back(Assumption);
1751 }
1752
1753 Actions.ActOnOpenMPAssumesDirective(Loc, DKind, Assumptions, SkippedClauses);
1754}
1755
1756void Parser::ParseOpenMPEndAssumesDirective(SourceLocation Loc) {
1757 if (Actions.isInOpenMPAssumeScope())
1758 Actions.ActOnOpenMPEndAssumesDirective();
1759 else
1760 Diag(Loc, diag::err_expected_begin_assumes);
1761}
1762
1763/// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
1764///
1765/// default-clause:
1766/// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')
1767///
1768/// proc_bind-clause:
1769/// 'proc_bind' '(' 'master' | 'close' | 'spread' ')
1770///
1771/// device_type-clause:
1772/// 'device_type' '(' 'host' | 'nohost' | 'any' )'
1773namespace {
1774struct SimpleClauseData {
1775 unsigned Type;
1776 SourceLocation Loc;
1777 SourceLocation LOpen;
1778 SourceLocation TypeLoc;
1779 SourceLocation RLoc;
1780 SimpleClauseData(unsigned Type, SourceLocation Loc, SourceLocation LOpen,
1781 SourceLocation TypeLoc, SourceLocation RLoc)
1782 : Type(Type), Loc(Loc), LOpen(LOpen), TypeLoc(TypeLoc), RLoc(RLoc) {}
1783};
1784} // anonymous namespace
1785
1786static std::optional<SimpleClauseData>
1787parseOpenMPSimpleClause(Parser &P, OpenMPClauseKind Kind) {
1788 const Token &Tok = P.getCurToken();
1789 SourceLocation Loc = Tok.getLocation();
1790 SourceLocation LOpen = P.ConsumeToken();
1791 // Parse '('.
1792 BalancedDelimiterTracker T(P, tok::l_paren, tok::annot_pragma_openmp_end);
1793 if (T.expectAndConsume(diag::err_expected_lparen_after,
1794 getOpenMPClauseName(Kind).data()))
1795 return std::nullopt;
1796
1797 unsigned Type = getOpenMPSimpleClauseType(
1798 Kind, Tok.isAnnotation() ? "" : P.getPreprocessor().getSpelling(Tok),
1799 P.getLangOpts());
1800 SourceLocation TypeLoc = Tok.getLocation();
1801 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
1802 Tok.isNot(tok::annot_pragma_openmp_end))
1803 P.ConsumeAnyToken();
1804
1805 // Parse ')'.
1806 SourceLocation RLoc = Tok.getLocation();
1807 if (!T.consumeClose())
1808 RLoc = T.getCloseLocation();
1809
1810 return SimpleClauseData(Type, Loc, LOpen, TypeLoc, RLoc);
1811}
1812
1813void Parser::ParseOMPDeclareTargetClauses(
1814 Sema::DeclareTargetContextInfo &DTCI) {
1815 SourceLocation DeviceTypeLoc;
1816 bool RequiresToOrLinkOrIndirectClause = false;
1817 bool HasToOrLinkOrIndirectClause = false;
1818 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
1819 OMPDeclareTargetDeclAttr::MapTypeTy MT = OMPDeclareTargetDeclAttr::MT_To;
1820 bool HasIdentifier = Tok.is(tok::identifier);
1821 if (HasIdentifier) {
1822 // If we see any clause we need a to or link clause.
1823 RequiresToOrLinkOrIndirectClause = true;
1824 IdentifierInfo *II = Tok.getIdentifierInfo();
1825 StringRef ClauseName = II->getName();
1826 bool IsDeviceTypeClause =
1827 getLangOpts().OpenMP >= 50 &&
1828 getOpenMPClauseKind(ClauseName) == OMPC_device_type;
1829
1830 bool IsIndirectClause = getLangOpts().OpenMP >= 51 &&
1831 getOpenMPClauseKind(ClauseName) == OMPC_indirect;
1832 if (DTCI.Indirect && IsIndirectClause) {
1833 Diag(Tok, diag::err_omp_more_one_clause)
1834 << getOpenMPDirectiveName(OMPD_declare_target)
1835 << getOpenMPClauseName(OMPC_indirect) << 0;
1836 break;
1837 }
1838 bool IsToEnterOrLinkClause =
1839 OMPDeclareTargetDeclAttr::ConvertStrToMapTypeTy(ClauseName, MT);
1840 assert((!IsDeviceTypeClause || !IsToEnterOrLinkClause) &&(static_cast <bool> ((!IsDeviceTypeClause || !IsToEnterOrLinkClause
) && "Cannot be both!") ? void (0) : __assert_fail ("(!IsDeviceTypeClause || !IsToEnterOrLinkClause) && \"Cannot be both!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 1841, __extension__ __PRETTY_FUNCTION__
))
1841 "Cannot be both!")(static_cast <bool> ((!IsDeviceTypeClause || !IsToEnterOrLinkClause
) && "Cannot be both!") ? void (0) : __assert_fail ("(!IsDeviceTypeClause || !IsToEnterOrLinkClause) && \"Cannot be both!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 1841, __extension__ __PRETTY_FUNCTION__
))
;
1842
1843 // Starting with OpenMP 5.2 the `to` clause has been replaced by the
1844 // `enter` clause.
1845 if (getLangOpts().OpenMP >= 52 && ClauseName == "to") {
1846 Diag(Tok, diag::err_omp_declare_target_unexpected_to_clause);
1847 break;
1848 }
1849 if (getLangOpts().OpenMP <= 51 && ClauseName == "enter") {
1850 Diag(Tok, diag::err_omp_declare_target_unexpected_enter_clause);
1851 break;
1852 }
1853
1854 if (!IsDeviceTypeClause && !IsIndirectClause &&
1855 DTCI.Kind == OMPD_begin_declare_target) {
1856 Diag(Tok, diag::err_omp_declare_target_unexpected_clause)
1857 << ClauseName << (getLangOpts().OpenMP >= 51 ? 3 : 0);
1858 break;
1859 }
1860 if (!IsDeviceTypeClause && !IsToEnterOrLinkClause && !IsIndirectClause) {
1861 Diag(Tok, getLangOpts().OpenMP >= 52
1862 ? diag::err_omp_declare_target_unexpected_clause_52
1863 : diag::err_omp_declare_target_unexpected_clause)
1864 << ClauseName
1865 << (getLangOpts().OpenMP >= 51
1866 ? 4
1867 : getLangOpts().OpenMP >= 50 ? 2 : 1);
1868 break;
1869 }
1870
1871 if (IsToEnterOrLinkClause || IsIndirectClause)
1872 HasToOrLinkOrIndirectClause = true;
1873
1874 if (IsIndirectClause) {
1875 if (!ParseOpenMPIndirectClause(DTCI, /*ParseOnly*/ false))
1876 break;
1877 continue;
1878 }
1879 // Parse 'device_type' clause and go to next clause if any.
1880 if (IsDeviceTypeClause) {
1881 std::optional<SimpleClauseData> DevTypeData =
1882 parseOpenMPSimpleClause(*this, OMPC_device_type);
1883 if (DevTypeData) {
1884 if (DeviceTypeLoc.isValid()) {
1885 // We already saw another device_type clause, diagnose it.
1886 Diag(DevTypeData->Loc,
1887 diag::warn_omp_more_one_device_type_clause);
1888 break;
1889 }
1890 switch (static_cast<OpenMPDeviceType>(DevTypeData->Type)) {
1891 case OMPC_DEVICE_TYPE_any:
1892 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Any;
1893 break;
1894 case OMPC_DEVICE_TYPE_host:
1895 DTCI.DT = OMPDeclareTargetDeclAttr::DT_Host;
1896 break;
1897 case OMPC_DEVICE_TYPE_nohost:
1898 DTCI.DT = OMPDeclareTargetDeclAttr::DT_NoHost;
1899 break;
1900 case OMPC_DEVICE_TYPE_unknown:
1901 llvm_unreachable("Unexpected device_type")::llvm::llvm_unreachable_internal("Unexpected device_type", "clang/lib/Parse/ParseOpenMP.cpp"
, 1901)
;
1902 }
1903 DeviceTypeLoc = DevTypeData->Loc;
1904 }
1905 continue;
1906 }
1907 ConsumeToken();
1908 }
1909
1910 if (DTCI.Kind == OMPD_declare_target || HasIdentifier) {
1911 auto &&Callback = [this, MT, &DTCI](CXXScopeSpec &SS,
1912 DeclarationNameInfo NameInfo) {
1913 NamedDecl *ND =
1914 Actions.lookupOpenMPDeclareTargetName(getCurScope(), SS, NameInfo);
1915 if (!ND)
1916 return;
1917 Sema::DeclareTargetContextInfo::MapInfo MI{MT, NameInfo.getLoc()};
1918 bool FirstMapping = DTCI.ExplicitlyMapped.try_emplace(ND, MI).second;
1919 if (!FirstMapping)
1920 Diag(NameInfo.getLoc(), diag::err_omp_declare_target_multiple)
1921 << NameInfo.getName();
1922 };
1923 if (ParseOpenMPSimpleVarList(OMPD_declare_target, Callback,
1924 /*AllowScopeSpecifier=*/true))
1925 break;
1926 }
1927
1928 if (Tok.is(tok::l_paren)) {
1929 Diag(Tok,
1930 diag::err_omp_begin_declare_target_unexpected_implicit_to_clause);
1931 break;
1932 }
1933 if (!HasIdentifier && Tok.isNot(tok::annot_pragma_openmp_end)) {
1934 Diag(Tok,
1935 getLangOpts().OpenMP >= 52
1936 ? diag::err_omp_declare_target_wrong_clause_after_implicit_enter
1937 : diag::err_omp_declare_target_wrong_clause_after_implicit_to);
1938 break;
1939 }
1940
1941 // Consume optional ','.
1942 if (Tok.is(tok::comma))
1943 ConsumeToken();
1944 }
1945
1946 if (DTCI.Indirect && DTCI.DT != OMPDeclareTargetDeclAttr::DT_Any)
1947 Diag(DeviceTypeLoc, diag::err_omp_declare_target_indirect_device_type);
1948
1949 // For declare target require at least 'to' or 'link' to be present.
1950 if (DTCI.Kind == OMPD_declare_target && RequiresToOrLinkOrIndirectClause &&
1951 !HasToOrLinkOrIndirectClause)
1952 Diag(DTCI.Loc,
1953 getLangOpts().OpenMP >= 52
1954 ? diag::err_omp_declare_target_missing_enter_or_link_clause
1955 : diag::err_omp_declare_target_missing_to_or_link_clause)
1956 << (getLangOpts().OpenMP >= 51 ? 1 : 0);
1957
1958 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1959}
1960
1961void Parser::skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind) {
1962 // The last seen token is annot_pragma_openmp_end - need to check for
1963 // extra tokens.
1964 if (Tok.is(tok::annot_pragma_openmp_end))
1965 return;
1966
1967 Diag(Tok, diag::warn_omp_extra_tokens_at_eol)
1968 << getOpenMPDirectiveName(DKind);
1969 while (Tok.isNot(tok::annot_pragma_openmp_end))
1970 ConsumeAnyToken();
1971}
1972
1973void Parser::parseOMPEndDirective(OpenMPDirectiveKind BeginKind,
1974 OpenMPDirectiveKind ExpectedKind,
1975 OpenMPDirectiveKind FoundKind,
1976 SourceLocation BeginLoc,
1977 SourceLocation FoundLoc,
1978 bool SkipUntilOpenMPEnd) {
1979 int DiagSelection = ExpectedKind == OMPD_end_declare_target ? 0 : 1;
1980
1981 if (FoundKind == ExpectedKind) {
1982 ConsumeAnyToken();
1983 skipUntilPragmaOpenMPEnd(ExpectedKind);
1984 return;
1985 }
1986
1987 Diag(FoundLoc, diag::err_expected_end_declare_target_or_variant)
1988 << DiagSelection;
1989 Diag(BeginLoc, diag::note_matching)
1990 << ("'#pragma omp " + getOpenMPDirectiveName(BeginKind) + "'").str();
1991 if (SkipUntilOpenMPEnd)
1992 SkipUntil(tok::annot_pragma_openmp_end, StopBeforeMatch);
1993}
1994
1995void Parser::ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind,
1996 OpenMPDirectiveKind EndDKind,
1997 SourceLocation DKLoc) {
1998 parseOMPEndDirective(BeginDKind, OMPD_end_declare_target, EndDKind, DKLoc,
1999 Tok.getLocation(),
2000 /* SkipUntilOpenMPEnd */ false);
2001 // Skip the last annot_pragma_openmp_end.
2002 if (Tok.is(tok::annot_pragma_openmp_end))
2003 ConsumeAnnotationToken();
2004}
2005
2006/// Parsing of declarative OpenMP directives.
2007///
2008/// threadprivate-directive:
2009/// annot_pragma_openmp 'threadprivate' simple-variable-list
2010/// annot_pragma_openmp_end
2011///
2012/// allocate-directive:
2013/// annot_pragma_openmp 'allocate' simple-variable-list [<clause>]
2014/// annot_pragma_openmp_end
2015///
2016/// declare-reduction-directive:
2017/// annot_pragma_openmp 'declare' 'reduction' [...]
2018/// annot_pragma_openmp_end
2019///
2020/// declare-mapper-directive:
2021/// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
2022/// <type> <var> ')' [<clause>[[,] <clause>] ... ]
2023/// annot_pragma_openmp_end
2024///
2025/// declare-simd-directive:
2026/// annot_pragma_openmp 'declare simd' {<clause> [,]}
2027/// annot_pragma_openmp_end
2028/// <function declaration/definition>
2029///
2030/// requires directive:
2031/// annot_pragma_openmp 'requires' <clause> [[[,] <clause>] ... ]
2032/// annot_pragma_openmp_end
2033///
2034/// assumes directive:
2035/// annot_pragma_openmp 'assumes' <clause> [[[,] <clause>] ... ]
2036/// annot_pragma_openmp_end
2037/// or
2038/// annot_pragma_openmp 'begin assumes' <clause> [[[,] <clause>] ... ]
2039/// annot_pragma_openmp 'end assumes'
2040/// annot_pragma_openmp_end
2041///
2042Parser::DeclGroupPtrTy Parser::ParseOpenMPDeclarativeDirectiveWithExtDecl(
2043 AccessSpecifier &AS, ParsedAttributes &Attrs, bool Delayed,
2044 DeclSpec::TST TagType, Decl *Tag) {
2045 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&(static_cast <bool> (Tok.isOneOf(tok::annot_pragma_openmp
, tok::annot_attr_openmp) && "Not an OpenMP directive!"
) ? void (0) : __assert_fail ("Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && \"Not an OpenMP directive!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2046, __extension__ __PRETTY_FUNCTION__
))
2046 "Not an OpenMP directive!")(static_cast <bool> (Tok.isOneOf(tok::annot_pragma_openmp
, tok::annot_attr_openmp) && "Not an OpenMP directive!"
) ? void (0) : __assert_fail ("Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && \"Not an OpenMP directive!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2046, __extension__ __PRETTY_FUNCTION__
))
;
2047 ParsingOpenMPDirectiveRAII DirScope(*this);
2048 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2049
2050 SourceLocation Loc;
2051 OpenMPDirectiveKind DKind;
2052 if (Delayed) {
2053 TentativeParsingAction TPA(*this);
2054 Loc = ConsumeAnnotationToken();
2055 DKind = parseOpenMPDirectiveKind(*this);
2056 if (DKind == OMPD_declare_reduction || DKind == OMPD_declare_mapper) {
2057 // Need to delay parsing until completion of the parent class.
2058 TPA.Revert();
2059 CachedTokens Toks;
2060 unsigned Cnt = 1;
2061 Toks.push_back(Tok);
2062 while (Cnt && Tok.isNot(tok::eof)) {
2063 (void)ConsumeAnyToken();
2064 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp))
2065 ++Cnt;
2066 else if (Tok.is(tok::annot_pragma_openmp_end))
2067 --Cnt;
2068 Toks.push_back(Tok);
2069 }
2070 // Skip last annot_pragma_openmp_end.
2071 if (Cnt == 0)
2072 (void)ConsumeAnyToken();
2073 auto *LP = new LateParsedPragma(this, AS);
2074 LP->takeToks(Toks);
2075 getCurrentClass().LateParsedDeclarations.push_back(LP);
2076 return nullptr;
2077 }
2078 TPA.Commit();
2079 } else {
2080 Loc = ConsumeAnnotationToken();
2081 DKind = parseOpenMPDirectiveKind(*this);
2082 }
2083
2084 switch (DKind) {
2085 case OMPD_threadprivate: {
2086 ConsumeToken();
2087 DeclDirectiveListParserHelper Helper(this, DKind);
2088 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2089 /*AllowScopeSpecifier=*/true)) {
2090 skipUntilPragmaOpenMPEnd(DKind);
2091 // Skip the last annot_pragma_openmp_end.
2092 ConsumeAnnotationToken();
2093 return Actions.ActOnOpenMPThreadprivateDirective(Loc,
2094 Helper.getIdentifiers());
2095 }
2096 break;
2097 }
2098 case OMPD_allocate: {
2099 ConsumeToken();
2100 DeclDirectiveListParserHelper Helper(this, DKind);
2101 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2102 /*AllowScopeSpecifier=*/true)) {
2103 SmallVector<OMPClause *, 1> Clauses;
2104 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2105 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2106 llvm::omp::Clause_enumSize + 1>
2107 FirstClauses(llvm::omp::Clause_enumSize + 1);
2108 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2109 OpenMPClauseKind CKind =
2110 Tok.isAnnotation() ? OMPC_unknown
2111 : getOpenMPClauseKind(PP.getSpelling(Tok));
2112 Actions.StartOpenMPClause(CKind);
2113 OMPClause *Clause = ParseOpenMPClause(
2114 OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
2115 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2116 StopBeforeMatch);
2117 FirstClauses[unsigned(CKind)].setInt(true);
2118 if (Clause != nullptr)
2119 Clauses.push_back(Clause);
2120 if (Tok.is(tok::annot_pragma_openmp_end)) {
2121 Actions.EndOpenMPClause();
2122 break;
2123 }
2124 // Skip ',' if any.
2125 if (Tok.is(tok::comma))
2126 ConsumeToken();
2127 Actions.EndOpenMPClause();
2128 }
2129 skipUntilPragmaOpenMPEnd(DKind);
2130 }
2131 // Skip the last annot_pragma_openmp_end.
2132 ConsumeAnnotationToken();
2133 return Actions.ActOnOpenMPAllocateDirective(Loc, Helper.getIdentifiers(),
2134 Clauses);
2135 }
2136 break;
2137 }
2138 case OMPD_requires: {
2139 SourceLocation StartLoc = ConsumeToken();
2140 SmallVector<OMPClause *, 5> Clauses;
2141 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2142 llvm::omp::Clause_enumSize + 1>
2143 FirstClauses(llvm::omp::Clause_enumSize + 1);
2144 if (Tok.is(tok::annot_pragma_openmp_end)) {
2145 Diag(Tok, diag::err_omp_expected_clause)
2146 << getOpenMPDirectiveName(OMPD_requires);
2147 break;
2148 }
2149 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2150 OpenMPClauseKind CKind = Tok.isAnnotation()
2151 ? OMPC_unknown
2152 : getOpenMPClauseKind(PP.getSpelling(Tok));
2153 Actions.StartOpenMPClause(CKind);
2154 OMPClause *Clause = ParseOpenMPClause(
2155 OMPD_requires, CKind, !FirstClauses[unsigned(CKind)].getInt());
2156 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2157 StopBeforeMatch);
2158 FirstClauses[unsigned(CKind)].setInt(true);
2159 if (Clause != nullptr)
2160 Clauses.push_back(Clause);
2161 if (Tok.is(tok::annot_pragma_openmp_end)) {
2162 Actions.EndOpenMPClause();
2163 break;
2164 }
2165 // Skip ',' if any.
2166 if (Tok.is(tok::comma))
2167 ConsumeToken();
2168 Actions.EndOpenMPClause();
2169 }
2170 // Consume final annot_pragma_openmp_end
2171 if (Clauses.empty()) {
2172 Diag(Tok, diag::err_omp_expected_clause)
2173 << getOpenMPDirectiveName(OMPD_requires);
2174 ConsumeAnnotationToken();
2175 return nullptr;
2176 }
2177 ConsumeAnnotationToken();
2178 return Actions.ActOnOpenMPRequiresDirective(StartLoc, Clauses);
2179 }
2180 case OMPD_error: {
2181 SmallVector<OMPClause *, 1> Clauses;
2182 SourceLocation StartLoc = ConsumeToken();
2183 ParseOpenMPClauses(DKind, Clauses, StartLoc);
2184 Actions.ActOnOpenMPErrorDirective(Clauses, StartLoc, SourceLocation(),
2185 /*InExContext = */ false);
2186 break;
2187 }
2188 case OMPD_assumes:
2189 case OMPD_begin_assumes:
2190 ParseOpenMPAssumesDirective(DKind, ConsumeToken());
2191 break;
2192 case OMPD_end_assumes:
2193 ParseOpenMPEndAssumesDirective(ConsumeToken());
2194 break;
2195 case OMPD_declare_reduction:
2196 ConsumeToken();
2197 if (DeclGroupPtrTy Res = ParseOpenMPDeclareReductionDirective(AS)) {
2198 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2199 // Skip the last annot_pragma_openmp_end.
2200 ConsumeAnnotationToken();
2201 return Res;
2202 }
2203 break;
2204 case OMPD_declare_mapper: {
2205 ConsumeToken();
2206 if (DeclGroupPtrTy Res = ParseOpenMPDeclareMapperDirective(AS)) {
2207 // Skip the last annot_pragma_openmp_end.
2208 ConsumeAnnotationToken();
2209 return Res;
2210 }
2211 break;
2212 }
2213 case OMPD_begin_declare_variant: {
2214 // The syntax is:
2215 // { #pragma omp begin declare variant clause }
2216 // <function-declaration-or-definition-sequence>
2217 // { #pragma omp end declare variant }
2218 //
2219 ConsumeToken();
2220 OMPTraitInfo *ParentTI = Actions.getOMPTraitInfoForSurroundingScope();
2221 ASTContext &ASTCtx = Actions.getASTContext();
2222 OMPTraitInfo &TI = ASTCtx.getNewOMPTraitInfo();
2223 if (parseOMPDeclareVariantMatchClause(Loc, TI, ParentTI)) {
2224 while (!SkipUntil(tok::annot_pragma_openmp_end, Parser::StopBeforeMatch))
2225 ;
2226 // Skip the last annot_pragma_openmp_end.
2227 (void)ConsumeAnnotationToken();
2228 break;
2229 }
2230
2231 // Skip last tokens.
2232 skipUntilPragmaOpenMPEnd(OMPD_begin_declare_variant);
2233
2234 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2235
2236 VariantMatchInfo VMI;
2237 TI.getAsVariantMatchInfo(ASTCtx, VMI);
2238
2239 std::function<void(StringRef)> DiagUnknownTrait =
2240 [this, Loc](StringRef ISATrait) {
2241 // TODO Track the selector locations in a way that is accessible here
2242 // to improve the diagnostic location.
2243 Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
2244 };
2245 TargetOMPContext OMPCtx(
2246 ASTCtx, std::move(DiagUnknownTrait),
2247 /* CurrentFunctionDecl */ nullptr,
2248 /* ConstructTraits */ ArrayRef<llvm::omp::TraitProperty>());
2249
2250 if (isVariantApplicableInContext(VMI, OMPCtx, /* DeviceSetOnly */ true)) {
2251 Actions.ActOnOpenMPBeginDeclareVariant(Loc, TI);
2252 break;
2253 }
2254
2255 // Elide all the code till the matching end declare variant was found.
2256 unsigned Nesting = 1;
2257 SourceLocation DKLoc;
2258 OpenMPDirectiveKind DK = OMPD_unknown;
2259 do {
2260 DKLoc = Tok.getLocation();
2261 DK = parseOpenMPDirectiveKind(*this);
2262 if (DK == OMPD_end_declare_variant)
2263 --Nesting;
2264 else if (DK == OMPD_begin_declare_variant)
2265 ++Nesting;
2266 if (!Nesting || isEofOrEom())
2267 break;
2268 ConsumeAnyToken();
2269 } while (true);
2270
2271 parseOMPEndDirective(OMPD_begin_declare_variant, OMPD_end_declare_variant,
2272 DK, Loc, DKLoc, /* SkipUntilOpenMPEnd */ true);
2273 if (isEofOrEom())
2274 return nullptr;
2275 break;
2276 }
2277 case OMPD_end_declare_variant: {
2278 if (Actions.isInOpenMPDeclareVariantScope())
2279 Actions.ActOnOpenMPEndDeclareVariant();
2280 else
2281 Diag(Loc, diag::err_expected_begin_declare_variant);
2282 ConsumeToken();
2283 break;
2284 }
2285 case OMPD_declare_variant:
2286 case OMPD_declare_simd: {
2287 // The syntax is:
2288 // { #pragma omp declare {simd|variant} }
2289 // <function-declaration-or-definition>
2290 //
2291 CachedTokens Toks;
2292 Toks.push_back(Tok);
2293 ConsumeToken();
2294 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2295 Toks.push_back(Tok);
2296 ConsumeAnyToken();
2297 }
2298 Toks.push_back(Tok);
2299 ConsumeAnyToken();
2300
2301 DeclGroupPtrTy Ptr;
2302 if (Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp)) {
2303 Ptr = ParseOpenMPDeclarativeDirectiveWithExtDecl(AS, Attrs, Delayed,
2304 TagType, Tag);
2305 } else if (Tok.isNot(tok::r_brace) && !isEofOrEom()) {
2306 // Here we expect to see some function declaration.
2307 if (AS == AS_none) {
2308 assert(TagType == DeclSpec::TST_unspecified)(static_cast <bool> (TagType == DeclSpec::TST_unspecified
) ? void (0) : __assert_fail ("TagType == DeclSpec::TST_unspecified"
, "clang/lib/Parse/ParseOpenMP.cpp", 2308, __extension__ __PRETTY_FUNCTION__
))
;
2309 ParsedAttributes EmptyDeclSpecAttrs(AttrFactory);
2310 MaybeParseCXX11Attributes(Attrs);
2311 ParsingDeclSpec PDS(*this);
2312 Ptr = ParseExternalDeclaration(Attrs, EmptyDeclSpecAttrs, &PDS);
2313 } else {
2314 Ptr =
2315 ParseCXXClassMemberDeclarationWithPragmas(AS, Attrs, TagType, Tag);
2316 }
2317 }
2318 if (!Ptr) {
2319 Diag(Loc, diag::err_omp_decl_in_declare_simd_variant)
2320 << (DKind == OMPD_declare_simd ? 0 : 1);
2321 return DeclGroupPtrTy();
2322 }
2323 if (DKind == OMPD_declare_simd)
2324 return ParseOMPDeclareSimdClauses(Ptr, Toks, Loc);
2325 assert(DKind == OMPD_declare_variant &&(static_cast <bool> (DKind == OMPD_declare_variant &&
"Expected declare variant directive only") ? void (0) : __assert_fail
("DKind == OMPD_declare_variant && \"Expected declare variant directive only\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2326, __extension__ __PRETTY_FUNCTION__
))
2326 "Expected declare variant directive only")(static_cast <bool> (DKind == OMPD_declare_variant &&
"Expected declare variant directive only") ? void (0) : __assert_fail
("DKind == OMPD_declare_variant && \"Expected declare variant directive only\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2326, __extension__ __PRETTY_FUNCTION__
))
;
2327 ParseOMPDeclareVariantClauses(Ptr, Toks, Loc);
2328 return Ptr;
2329 }
2330 case OMPD_begin_declare_target:
2331 case OMPD_declare_target: {
2332 SourceLocation DTLoc = ConsumeAnyToken();
2333 bool HasClauses = Tok.isNot(tok::annot_pragma_openmp_end);
2334 Sema::DeclareTargetContextInfo DTCI(DKind, DTLoc);
2335 if (HasClauses)
2336 ParseOMPDeclareTargetClauses(DTCI);
2337 bool HasImplicitMappings = DKind == OMPD_begin_declare_target ||
2338 !HasClauses ||
2339 (DTCI.ExplicitlyMapped.empty() && DTCI.Indirect);
2340
2341 // Skip the last annot_pragma_openmp_end.
2342 ConsumeAnyToken();
2343
2344 if (HasImplicitMappings) {
2345 Actions.ActOnStartOpenMPDeclareTargetContext(DTCI);
2346 return nullptr;
2347 }
2348
2349 Actions.ActOnFinishedOpenMPDeclareTargetContext(DTCI);
2350 llvm::SmallVector<Decl *, 4> Decls;
2351 for (auto &It : DTCI.ExplicitlyMapped)
2352 Decls.push_back(It.first);
2353 return Actions.BuildDeclaratorGroup(Decls);
2354 }
2355 case OMPD_end_declare_target: {
2356 if (!Actions.isInOpenMPDeclareTargetContext()) {
2357 Diag(Tok, diag::err_omp_unexpected_directive)
2358 << 1 << getOpenMPDirectiveName(DKind);
2359 break;
2360 }
2361 const Sema::DeclareTargetContextInfo &DTCI =
2362 Actions.ActOnOpenMPEndDeclareTargetDirective();
2363 ParseOMPEndDeclareTargetDirective(DTCI.Kind, DKind, DTCI.Loc);
2364 return nullptr;
2365 }
2366 case OMPD_unknown:
2367 Diag(Tok, diag::err_omp_unknown_directive);
2368 break;
2369 case OMPD_parallel:
2370 case OMPD_simd:
2371 case OMPD_tile:
2372 case OMPD_unroll:
2373 case OMPD_task:
2374 case OMPD_taskyield:
2375 case OMPD_barrier:
2376 case OMPD_taskwait:
2377 case OMPD_taskgroup:
2378 case OMPD_flush:
2379 case OMPD_depobj:
2380 case OMPD_scan:
2381 case OMPD_for:
2382 case OMPD_for_simd:
2383 case OMPD_sections:
2384 case OMPD_section:
2385 case OMPD_single:
2386 case OMPD_master:
2387 case OMPD_ordered:
2388 case OMPD_critical:
2389 case OMPD_parallel_for:
2390 case OMPD_parallel_for_simd:
2391 case OMPD_parallel_sections:
2392 case OMPD_parallel_master:
2393 case OMPD_parallel_masked:
2394 case OMPD_atomic:
2395 case OMPD_target:
2396 case OMPD_teams:
2397 case OMPD_cancellation_point:
2398 case OMPD_cancel:
2399 case OMPD_target_data:
2400 case OMPD_target_enter_data:
2401 case OMPD_target_exit_data:
2402 case OMPD_target_parallel:
2403 case OMPD_target_parallel_for:
2404 case OMPD_taskloop:
2405 case OMPD_taskloop_simd:
2406 case OMPD_master_taskloop:
2407 case OMPD_master_taskloop_simd:
2408 case OMPD_parallel_master_taskloop:
2409 case OMPD_parallel_master_taskloop_simd:
2410 case OMPD_masked_taskloop:
2411 case OMPD_masked_taskloop_simd:
2412 case OMPD_parallel_masked_taskloop:
2413 case OMPD_parallel_masked_taskloop_simd:
2414 case OMPD_distribute:
2415 case OMPD_target_update:
2416 case OMPD_distribute_parallel_for:
2417 case OMPD_distribute_parallel_for_simd:
2418 case OMPD_distribute_simd:
2419 case OMPD_target_parallel_for_simd:
2420 case OMPD_target_simd:
2421 case OMPD_teams_distribute:
2422 case OMPD_teams_distribute_simd:
2423 case OMPD_teams_distribute_parallel_for_simd:
2424 case OMPD_teams_distribute_parallel_for:
2425 case OMPD_target_teams:
2426 case OMPD_target_teams_distribute:
2427 case OMPD_target_teams_distribute_parallel_for:
2428 case OMPD_target_teams_distribute_parallel_for_simd:
2429 case OMPD_target_teams_distribute_simd:
2430 case OMPD_dispatch:
2431 case OMPD_masked:
2432 case OMPD_metadirective:
2433 case OMPD_loop:
2434 case OMPD_teams_loop:
2435 case OMPD_target_teams_loop:
2436 case OMPD_parallel_loop:
2437 case OMPD_target_parallel_loop:
2438 Diag(Tok, diag::err_omp_unexpected_directive)
2439 << 1 << getOpenMPDirectiveName(DKind);
2440 break;
2441 default:
2442 break;
2443 }
2444 while (Tok.isNot(tok::annot_pragma_openmp_end))
2445 ConsumeAnyToken();
2446 ConsumeAnyToken();
2447 return nullptr;
2448}
2449
2450/// Parsing of declarative or executable OpenMP directives.
2451///
2452/// threadprivate-directive:
2453/// annot_pragma_openmp 'threadprivate' simple-variable-list
2454/// annot_pragma_openmp_end
2455///
2456/// allocate-directive:
2457/// annot_pragma_openmp 'allocate' simple-variable-list
2458/// annot_pragma_openmp_end
2459///
2460/// declare-reduction-directive:
2461/// annot_pragma_openmp 'declare' 'reduction' '(' <reduction_id> ':'
2462/// <type> {',' <type>} ':' <expression> ')' ['initializer' '('
2463/// ('omp_priv' '=' <expression>|<function_call>) ')']
2464/// annot_pragma_openmp_end
2465///
2466/// declare-mapper-directive:
2467/// annot_pragma_openmp 'declare' 'mapper' '(' [<mapper-identifer> ':']
2468/// <type> <var> ')' [<clause>[[,] <clause>] ... ]
2469/// annot_pragma_openmp_end
2470///
2471/// executable-directive:
2472/// annot_pragma_openmp 'parallel' | 'simd' | 'for' | 'sections' |
2473/// 'section' | 'single' | 'master' | 'critical' [ '(' <name> ')' ] |
2474/// 'parallel for' | 'parallel sections' | 'parallel master' | 'task' |
2475/// 'taskyield' | 'barrier' | 'taskwait' | 'flush' | 'ordered' | 'error'
2476/// | 'atomic' | 'for simd' | 'parallel for simd' | 'target' | 'target
2477/// data' | 'taskgroup' | 'teams' | 'taskloop' | 'taskloop simd' |
2478/// 'master taskloop' | 'master taskloop simd' | 'parallel master
2479/// taskloop' | 'parallel master taskloop simd' | 'distribute' | 'target
2480/// enter data' | 'target exit data' | 'target parallel' | 'target
2481/// parallel for' | 'target update' | 'distribute parallel for' |
2482/// 'distribute paralle for simd' | 'distribute simd' | 'target parallel
2483/// for simd' | 'target simd' | 'teams distribute' | 'teams distribute
2484/// simd' | 'teams distribute parallel for simd' | 'teams distribute
2485/// parallel for' | 'target teams' | 'target teams distribute' | 'target
2486/// teams distribute parallel for' | 'target teams distribute parallel
2487/// for simd' | 'target teams distribute simd' | 'masked' |
2488/// 'parallel masked' {clause} annot_pragma_openmp_end
2489///
2490StmtResult Parser::ParseOpenMPDeclarativeOrExecutableDirective(
2491 ParsedStmtContext StmtCtx, bool ReadDirectiveWithinMetadirective) {
2492 if (!ReadDirectiveWithinMetadirective)
2493 assert(Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) &&(static_cast <bool> (Tok.isOneOf(tok::annot_pragma_openmp
, tok::annot_attr_openmp) && "Not an OpenMP directive!"
) ? void (0) : __assert_fail ("Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && \"Not an OpenMP directive!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2494, __extension__ __PRETTY_FUNCTION__
))
2494 "Not an OpenMP directive!")(static_cast <bool> (Tok.isOneOf(tok::annot_pragma_openmp
, tok::annot_attr_openmp) && "Not an OpenMP directive!"
) ? void (0) : __assert_fail ("Tok.isOneOf(tok::annot_pragma_openmp, tok::annot_attr_openmp) && \"Not an OpenMP directive!\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2494, __extension__ __PRETTY_FUNCTION__
))
;
2495 ParsingOpenMPDirectiveRAII DirScope(*this);
2496 ParenBraceBracketBalancer BalancerRAIIObj(*this);
2497 SmallVector<OMPClause *, 5> Clauses;
2498 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2499 llvm::omp::Clause_enumSize + 1>
2500 FirstClauses(llvm::omp::Clause_enumSize + 1);
2501 unsigned ScopeFlags = Scope::FnScope | Scope::DeclScope |
2502 Scope::CompoundStmtScope | Scope::OpenMPDirectiveScope;
2503 SourceLocation Loc = ReadDirectiveWithinMetadirective
2504 ? Tok.getLocation()
2505 : ConsumeAnnotationToken(),
2506 EndLoc;
2507 OpenMPDirectiveKind DKind = parseOpenMPDirectiveKind(*this);
2508 if (ReadDirectiveWithinMetadirective && DKind == OMPD_unknown) {
2509 Diag(Tok, diag::err_omp_unknown_directive);
2510 return StmtError();
2511 }
2512 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
2513 // Name of critical directive.
2514 DeclarationNameInfo DirName;
2515 StmtResult Directive = StmtError();
2516 bool HasAssociatedStatement = true;
2517
2518 switch (DKind) {
2519 case OMPD_nothing:
2520 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2521 ParsedStmtContext())
2522 Diag(Tok, diag::err_omp_immediate_directive)
2523 << getOpenMPDirectiveName(DKind) << 0;
2524 ConsumeToken();
2525 skipUntilPragmaOpenMPEnd(DKind);
2526 if (Tok.is(tok::annot_pragma_openmp_end))
2527 ConsumeAnnotationToken();
2528 break;
2529 case OMPD_metadirective: {
2530 ConsumeToken();
2531 SmallVector<VariantMatchInfo, 4> VMIs;
2532
2533 // First iteration of parsing all clauses of metadirective.
2534 // This iteration only parses and collects all context selector ignoring the
2535 // associated directives.
2536 TentativeParsingAction TPA(*this);
2537 ASTContext &ASTContext = Actions.getASTContext();
2538
2539 BalancedDelimiterTracker T(*this, tok::l_paren,
2540 tok::annot_pragma_openmp_end);
2541 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2542 OpenMPClauseKind CKind = Tok.isAnnotation()
2543 ? OMPC_unknown
2544 : getOpenMPClauseKind(PP.getSpelling(Tok));
2545 SourceLocation Loc = ConsumeToken();
2546
2547 // Parse '('.
2548 if (T.expectAndConsume(diag::err_expected_lparen_after,
2549 getOpenMPClauseName(CKind).data()))
2550 return Directive;
2551
2552 OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2553 if (CKind == OMPC_when) {
2554 // parse and get OMPTraitInfo to pass to the When clause
2555 parseOMPContextSelectors(Loc, TI);
2556 if (TI.Sets.size() == 0) {
2557 Diag(Tok, diag::err_omp_expected_context_selector) << "when clause";
2558 TPA.Commit();
2559 return Directive;
2560 }
2561
2562 // Parse ':'
2563 if (Tok.is(tok::colon))
2564 ConsumeAnyToken();
2565 else {
2566 Diag(Tok, diag::err_omp_expected_colon) << "when clause";
2567 TPA.Commit();
2568 return Directive;
2569 }
2570 }
2571 // Skip Directive for now. We will parse directive in the second iteration
2572 int paren = 0;
2573 while (Tok.isNot(tok::r_paren) || paren != 0) {
2574 if (Tok.is(tok::l_paren))
2575 paren++;
2576 if (Tok.is(tok::r_paren))
2577 paren--;
2578 if (Tok.is(tok::annot_pragma_openmp_end)) {
2579 Diag(Tok, diag::err_omp_expected_punc)
2580 << getOpenMPClauseName(CKind) << 0;
2581 TPA.Commit();
2582 return Directive;
2583 }
2584 ConsumeAnyToken();
2585 }
2586 // Parse ')'
2587 if (Tok.is(tok::r_paren))
2588 T.consumeClose();
2589
2590 VariantMatchInfo VMI;
2591 TI.getAsVariantMatchInfo(ASTContext, VMI);
2592
2593 VMIs.push_back(VMI);
2594 }
2595
2596 TPA.Revert();
2597 // End of the first iteration. Parser is reset to the start of metadirective
2598
2599 std::function<void(StringRef)> DiagUnknownTrait =
2600 [this, Loc](StringRef ISATrait) {
2601 // TODO Track the selector locations in a way that is accessible here
2602 // to improve the diagnostic location.
2603 Diag(Loc, diag::warn_unknown_declare_variant_isa_trait) << ISATrait;
2604 };
2605 TargetOMPContext OMPCtx(ASTContext, std::move(DiagUnknownTrait),
2606 /* CurrentFunctionDecl */ nullptr,
2607 ArrayRef<llvm::omp::TraitProperty>());
2608
2609 // A single match is returned for OpenMP 5.0
2610 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx);
2611
2612 int Idx = 0;
2613 // In OpenMP 5.0 metadirective is either replaced by another directive or
2614 // ignored.
2615 // TODO: In OpenMP 5.1 generate multiple directives based upon the matches
2616 // found by getBestWhenMatchForContext.
2617 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2618 // OpenMP 5.0 implementation - Skip to the best index found.
2619 if (Idx++ != BestIdx) {
2620 ConsumeToken(); // Consume clause name
2621 T.consumeOpen(); // Consume '('
2622 int paren = 0;
2623 // Skip everything inside the clause
2624 while (Tok.isNot(tok::r_paren) || paren != 0) {
2625 if (Tok.is(tok::l_paren))
2626 paren++;
2627 if (Tok.is(tok::r_paren))
2628 paren--;
2629 ConsumeAnyToken();
2630 }
2631 // Parse ')'
2632 if (Tok.is(tok::r_paren))
2633 T.consumeClose();
2634 continue;
2635 }
2636
2637 OpenMPClauseKind CKind = Tok.isAnnotation()
2638 ? OMPC_unknown
2639 : getOpenMPClauseKind(PP.getSpelling(Tok));
2640 SourceLocation Loc = ConsumeToken();
2641
2642 // Parse '('.
2643 T.consumeOpen();
2644
2645 // Skip ContextSelectors for when clause
2646 if (CKind == OMPC_when) {
2647 OMPTraitInfo &TI = Actions.getASTContext().getNewOMPTraitInfo();
2648 // parse and skip the ContextSelectors
2649 parseOMPContextSelectors(Loc, TI);
2650
2651 // Parse ':'
2652 ConsumeAnyToken();
2653 }
2654
2655 // If no directive is passed, skip in OpenMP 5.0.
2656 // TODO: Generate nothing directive from OpenMP 5.1.
2657 if (Tok.is(tok::r_paren)) {
2658 SkipUntil(tok::annot_pragma_openmp_end);
2659 break;
2660 }
2661
2662 // Parse Directive
2663 Directive = ParseOpenMPDeclarativeOrExecutableDirective(
2664 StmtCtx,
2665 /*ReadDirectiveWithinMetadirective=*/true);
2666 break;
2667 }
2668 break;
2669 }
2670 case OMPD_threadprivate: {
2671 // FIXME: Should this be permitted in C++?
2672 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2673 ParsedStmtContext()) {
2674 Diag(Tok, diag::err_omp_immediate_directive)
2675 << getOpenMPDirectiveName(DKind) << 0;
2676 }
2677 ConsumeToken();
2678 DeclDirectiveListParserHelper Helper(this, DKind);
2679 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2680 /*AllowScopeSpecifier=*/false)) {
2681 skipUntilPragmaOpenMPEnd(DKind);
2682 DeclGroupPtrTy Res = Actions.ActOnOpenMPThreadprivateDirective(
2683 Loc, Helper.getIdentifiers());
2684 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2685 }
2686 SkipUntil(tok::annot_pragma_openmp_end);
2687 break;
2688 }
2689 case OMPD_allocate: {
2690 // FIXME: Should this be permitted in C++?
2691 if ((StmtCtx & ParsedStmtContext::AllowDeclarationsInC) ==
2692 ParsedStmtContext()) {
2693 Diag(Tok, diag::err_omp_immediate_directive)
2694 << getOpenMPDirectiveName(DKind) << 0;
2695 }
2696 ConsumeToken();
2697 DeclDirectiveListParserHelper Helper(this, DKind);
2698 if (!ParseOpenMPSimpleVarList(DKind, Helper,
2699 /*AllowScopeSpecifier=*/false)) {
2700 SmallVector<OMPClause *, 1> Clauses;
2701 if (Tok.isNot(tok::annot_pragma_openmp_end)) {
2702 SmallVector<llvm::PointerIntPair<OMPClause *, 1, bool>,
2703 llvm::omp::Clause_enumSize + 1>
2704 FirstClauses(llvm::omp::Clause_enumSize + 1);
2705 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2706 OpenMPClauseKind CKind =
2707 Tok.isAnnotation() ? OMPC_unknown
2708 : getOpenMPClauseKind(PP.getSpelling(Tok));
2709 Actions.StartOpenMPClause(CKind);
2710 OMPClause *Clause = ParseOpenMPClause(
2711 OMPD_allocate, CKind, !FirstClauses[unsigned(CKind)].getInt());
2712 SkipUntil(tok::comma, tok::identifier, tok::annot_pragma_openmp_end,
2713 StopBeforeMatch);
2714 FirstClauses[unsigned(CKind)].setInt(true);
2715 if (Clause != nullptr)
2716 Clauses.push_back(Clause);
2717 if (Tok.is(tok::annot_pragma_openmp_end)) {
2718 Actions.EndOpenMPClause();
2719 break;
2720 }
2721 // Skip ',' if any.
2722 if (Tok.is(tok::comma))
2723 ConsumeToken();
2724 Actions.EndOpenMPClause();
2725 }
2726 skipUntilPragmaOpenMPEnd(DKind);
2727 }
2728 DeclGroupPtrTy Res = Actions.ActOnOpenMPAllocateDirective(
2729 Loc, Helper.getIdentifiers(), Clauses);
2730 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2731 }
2732 SkipUntil(tok::annot_pragma_openmp_end);
2733 break;
2734 }
2735 case OMPD_declare_reduction:
2736 ConsumeToken();
2737 if (DeclGroupPtrTy Res =
2738 ParseOpenMPDeclareReductionDirective(/*AS=*/AS_none)) {
2739 skipUntilPragmaOpenMPEnd(OMPD_declare_reduction);
2740 ConsumeAnyToken();
2741 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2742 } else {
2743 SkipUntil(tok::annot_pragma_openmp_end);
2744 }
2745 break;
2746 case OMPD_declare_mapper: {
2747 ConsumeToken();
2748 if (DeclGroupPtrTy Res =
2749 ParseOpenMPDeclareMapperDirective(/*AS=*/AS_none)) {
2750 // Skip the last annot_pragma_openmp_end.
2751 ConsumeAnnotationToken();
2752 Directive = Actions.ActOnDeclStmt(Res, Loc, Tok.getLocation());
2753 } else {
2754 SkipUntil(tok::annot_pragma_openmp_end);
2755 }
2756 break;
2757 }
2758 case OMPD_flush:
2759 case OMPD_depobj:
2760 case OMPD_scan:
2761 case OMPD_taskyield:
2762 case OMPD_error:
2763 case OMPD_barrier:
2764 case OMPD_taskwait:
2765 case OMPD_cancellation_point:
2766 case OMPD_cancel:
2767 case OMPD_target_enter_data:
2768 case OMPD_target_exit_data:
2769 case OMPD_target_update:
2770 case OMPD_interop:
2771 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2772 ParsedStmtContext()) {
2773 Diag(Tok, diag::err_omp_immediate_directive)
2774 << getOpenMPDirectiveName(DKind) << 0;
2775 if (DKind == OMPD_error) {
2776 SkipUntil(tok::annot_pragma_openmp_end);
2777 break;
2778 }
2779 }
2780 HasAssociatedStatement = false;
2781 // Fall through for further analysis.
2782 [[fallthrough]];
2783 case OMPD_parallel:
2784 case OMPD_simd:
2785 case OMPD_tile:
2786 case OMPD_unroll:
2787 case OMPD_for:
2788 case OMPD_for_simd:
2789 case OMPD_sections:
2790 case OMPD_single:
2791 case OMPD_section:
2792 case OMPD_master:
2793 case OMPD_critical:
2794 case OMPD_parallel_for:
2795 case OMPD_parallel_for_simd:
2796 case OMPD_parallel_sections:
2797 case OMPD_parallel_master:
2798 case OMPD_parallel_masked:
2799 case OMPD_task:
2800 case OMPD_ordered:
2801 case OMPD_atomic:
2802 case OMPD_target:
2803 case OMPD_teams:
2804 case OMPD_taskgroup:
2805 case OMPD_target_data:
2806 case OMPD_target_parallel:
2807 case OMPD_target_parallel_for:
2808 case OMPD_loop:
2809 case OMPD_teams_loop:
2810 case OMPD_target_teams_loop:
2811 case OMPD_parallel_loop:
2812 case OMPD_target_parallel_loop:
2813 case OMPD_taskloop:
2814 case OMPD_taskloop_simd:
2815 case OMPD_master_taskloop:
2816 case OMPD_masked_taskloop:
2817 case OMPD_master_taskloop_simd:
2818 case OMPD_masked_taskloop_simd:
2819 case OMPD_parallel_master_taskloop:
2820 case OMPD_parallel_masked_taskloop:
2821 case OMPD_parallel_master_taskloop_simd:
2822 case OMPD_parallel_masked_taskloop_simd:
2823 case OMPD_distribute:
2824 case OMPD_distribute_parallel_for:
2825 case OMPD_distribute_parallel_for_simd:
2826 case OMPD_distribute_simd:
2827 case OMPD_target_parallel_for_simd:
2828 case OMPD_target_simd:
2829 case OMPD_teams_distribute:
2830 case OMPD_teams_distribute_simd:
2831 case OMPD_teams_distribute_parallel_for_simd:
2832 case OMPD_teams_distribute_parallel_for:
2833 case OMPD_target_teams:
2834 case OMPD_target_teams_distribute:
2835 case OMPD_target_teams_distribute_parallel_for:
2836 case OMPD_target_teams_distribute_parallel_for_simd:
2837 case OMPD_target_teams_distribute_simd:
2838 case OMPD_dispatch:
2839 case OMPD_masked: {
2840 // Special processing for flush and depobj clauses.
2841 Token ImplicitTok;
2842 bool ImplicitClauseAllowed = false;
2843 if (DKind == OMPD_flush || DKind == OMPD_depobj) {
2844 ImplicitTok = Tok;
2845 ImplicitClauseAllowed = true;
2846 }
2847 ConsumeToken();
2848 // Parse directive name of the 'critical' directive if any.
2849 if (DKind == OMPD_critical) {
2850 BalancedDelimiterTracker T(*this, tok::l_paren,
2851 tok::annot_pragma_openmp_end);
2852 if (!T.consumeOpen()) {
2853 if (Tok.isAnyIdentifier()) {
2854 DirName =
2855 DeclarationNameInfo(Tok.getIdentifierInfo(), Tok.getLocation());
2856 ConsumeAnyToken();
2857 } else {
2858 Diag(Tok, diag::err_omp_expected_identifier_for_critical);
2859 }
2860 T.consumeClose();
2861 }
2862 } else if (DKind == OMPD_cancellation_point || DKind == OMPD_cancel) {
2863 CancelRegion = parseOpenMPDirectiveKind(*this);
2864 if (Tok.isNot(tok::annot_pragma_openmp_end))
2865 ConsumeToken();
2866 }
2867
2868 if (isOpenMPLoopDirective(DKind))
2869 ScopeFlags |= Scope::OpenMPLoopDirectiveScope;
2870 if (isOpenMPSimdDirective(DKind))
2871 ScopeFlags |= Scope::OpenMPSimdDirectiveScope;
2872 ParseScope OMPDirectiveScope(this, ScopeFlags);
2873 Actions.StartOpenMPDSABlock(DKind, DirName, Actions.getCurScope(), Loc);
2874
2875 while (Tok.isNot(tok::annot_pragma_openmp_end)) {
2876 // If we are parsing for a directive within a metadirective, the directive
2877 // ends with a ')'.
2878 if (ReadDirectiveWithinMetadirective && Tok.is(tok::r_paren)) {
2879 while (Tok.isNot(tok::annot_pragma_openmp_end))
2880 ConsumeAnyToken();
2881 break;
2882 }
2883 bool HasImplicitClause = false;
2884 if (ImplicitClauseAllowed && Tok.is(tok::l_paren)) {
2885 HasImplicitClause = true;
2886 // Push copy of the current token back to stream to properly parse
2887 // pseudo-clause OMPFlushClause or OMPDepobjClause.
2888 PP.EnterToken(Tok, /*IsReinject*/ true);
2889 PP.EnterToken(ImplicitTok, /*IsReinject*/ true);
2890 ConsumeAnyToken();
2891 }
2892 OpenMPClauseKind CKind = Tok.isAnnotation()
2893 ? OMPC_unknown
2894 : getOpenMPClauseKind(PP.getSpelling(Tok));
2895 if (HasImplicitClause) {
2896 assert(CKind == OMPC_unknown && "Must be unknown implicit clause.")(static_cast <bool> (CKind == OMPC_unknown && "Must be unknown implicit clause."
) ? void (0) : __assert_fail ("CKind == OMPC_unknown && \"Must be unknown implicit clause.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2896, __extension__ __PRETTY_FUNCTION__
))
;
2897 if (DKind == OMPD_flush) {
2898 CKind = OMPC_flush;
2899 } else {
2900 assert(DKind == OMPD_depobj &&(static_cast <bool> (DKind == OMPD_depobj && "Expected flush or depobj directives."
) ? void (0) : __assert_fail ("DKind == OMPD_depobj && \"Expected flush or depobj directives.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2901, __extension__ __PRETTY_FUNCTION__
))
2901 "Expected flush or depobj directives.")(static_cast <bool> (DKind == OMPD_depobj && "Expected flush or depobj directives."
) ? void (0) : __assert_fail ("DKind == OMPD_depobj && \"Expected flush or depobj directives.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 2901, __extension__ __PRETTY_FUNCTION__
))
;
2902 CKind = OMPC_depobj;
2903 }
2904 }
2905 // No more implicit clauses allowed.
2906 ImplicitClauseAllowed = false;
2907 Actions.StartOpenMPClause(CKind);
2908 HasImplicitClause = false;
Value stored to 'HasImplicitClause' is never read
2909 OMPClause *Clause = ParseOpenMPClause(
2910 DKind, CKind, !FirstClauses[unsigned(CKind)].getInt());
2911 FirstClauses[unsigned(CKind)].setInt(true);
2912 if (Clause) {
2913 FirstClauses[unsigned(CKind)].setPointer(Clause);
2914 Clauses.push_back(Clause);
2915 }
2916
2917 // Skip ',' if any.
2918 if (Tok.is(tok::comma))
2919 ConsumeToken();
2920 Actions.EndOpenMPClause();
2921 }
2922 // End location of the directive.
2923 EndLoc = Tok.getLocation();
2924 // Consume final annot_pragma_openmp_end.
2925 ConsumeAnnotationToken();
2926
2927 // OpenMP [2.13.8, ordered Construct, Syntax]
2928 // If the depend clause is specified, the ordered construct is a stand-alone
2929 // directive.
2930 if (DKind == OMPD_ordered && FirstClauses[unsigned(OMPC_depend)].getInt()) {
2931 if ((StmtCtx & ParsedStmtContext::AllowStandaloneOpenMPDirectives) ==
2932 ParsedStmtContext()) {
2933 Diag(Loc, diag::err_omp_immediate_directive)
2934 << getOpenMPDirectiveName(DKind) << 1
2935 << getOpenMPClauseName(OMPC_depend);
2936 }
2937 HasAssociatedStatement = false;
2938 }
2939
2940 if (DKind == OMPD_tile && !FirstClauses[unsigned(OMPC_sizes)].getInt()) {
2941 Diag(Loc, diag::err_omp_required_clause)
2942 << getOpenMPDirectiveName(OMPD_tile) << "sizes";
2943 }
2944
2945 StmtResult AssociatedStmt;
2946 if (HasAssociatedStatement) {
2947 // The body is a block scope like in Lambdas and Blocks.
2948 Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2949 // FIXME: We create a bogus CompoundStmt scope to hold the contents of
2950 // the captured region. Code elsewhere assumes that any FunctionScopeInfo
2951 // should have at least one compound statement scope within it.
2952 ParsingOpenMPDirectiveRAII NormalScope(*this, /*Value=*/false);
2953 {
2954 Sema::CompoundScopeRAII Scope(Actions);
2955 AssociatedStmt = ParseStatement();
2956
2957 if (AssociatedStmt.isUsable() && isOpenMPLoopDirective(DKind) &&
2958 getLangOpts().OpenMPIRBuilder)
2959 AssociatedStmt = Actions.ActOnOpenMPLoopnest(AssociatedStmt.get());
2960 }
2961 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2962 } else if (DKind == OMPD_target_update || DKind == OMPD_target_enter_data ||
2963 DKind == OMPD_target_exit_data) {
2964 Actions.ActOnOpenMPRegionStart(DKind, getCurScope());
2965 AssociatedStmt = (Sema::CompoundScopeRAII(Actions),
2966 Actions.ActOnCompoundStmt(Loc, Loc, std::nullopt,
2967 /*isStmtExpr=*/false));
2968 AssociatedStmt = Actions.ActOnOpenMPRegionEnd(AssociatedStmt, Clauses);
2969 }
2970 Directive = Actions.ActOnOpenMPExecutableDirective(
2971 DKind, DirName, CancelRegion, Clauses, AssociatedStmt.get(), Loc,
2972 EndLoc);
2973
2974 // Exit scope.
2975 Actions.EndOpenMPDSABlock(Directive.get());
2976 OMPDirectiveScope.Exit();
2977 break;
2978 }
2979 case OMPD_declare_simd:
2980 case OMPD_declare_target:
2981 case OMPD_begin_declare_target:
2982 case OMPD_end_declare_target:
2983 case OMPD_requires:
2984 case OMPD_begin_declare_variant:
2985 case OMPD_end_declare_variant:
2986 case OMPD_declare_variant:
2987 Diag(Tok, diag::err_omp_unexpected_directive)
2988 << 1 << getOpenMPDirectiveName(DKind);
2989 SkipUntil(tok::annot_pragma_openmp_end);
2990 break;
2991 case OMPD_unknown:
2992 default:
2993 Diag(Tok, diag::err_omp_unknown_directive);
2994 SkipUntil(tok::annot_pragma_openmp_end);
2995 break;
2996 }
2997 return Directive;
2998}
2999
3000// Parses simple list:
3001// simple-variable-list:
3002// '(' id-expression {, id-expression} ')'
3003//
3004bool Parser::ParseOpenMPSimpleVarList(
3005 OpenMPDirectiveKind Kind,
3006 const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)>
3007 &Callback,
3008 bool AllowScopeSpecifier) {
3009 // Parse '('.
3010 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3011 if (T.expectAndConsume(diag::err_expected_lparen_after,
3012 getOpenMPDirectiveName(Kind).data()))
3013 return true;
3014 bool IsCorrect = true;
3015 bool NoIdentIsFound = true;
3016
3017 // Read tokens while ')' or annot_pragma_openmp_end is not found.
3018 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
3019 CXXScopeSpec SS;
3020 UnqualifiedId Name;
3021 // Read var name.
3022 Token PrevTok = Tok;
3023 NoIdentIsFound = false;
3024
3025 if (AllowScopeSpecifier && getLangOpts().CPlusPlus &&
3026 ParseOptionalCXXScopeSpecifier(SS, /*ObjectType=*/nullptr,
3027 /*ObjectHasErrors=*/false, false)) {
3028 IsCorrect = false;
3029 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3030 StopBeforeMatch);
3031 } else if (ParseUnqualifiedId(SS, /*ObjectType=*/nullptr,
3032 /*ObjectHadErrors=*/false, false, false,
3033 false, false, nullptr, Name)) {
3034 IsCorrect = false;
3035 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3036 StopBeforeMatch);
3037 } else if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren) &&
3038 Tok.isNot(tok::annot_pragma_openmp_end)) {
3039 IsCorrect = false;
3040 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3041 StopBeforeMatch);
3042 Diag(PrevTok.getLocation(), diag::err_expected)
3043 << tok::identifier
3044 << SourceRange(PrevTok.getLocation(), PrevTokLocation);
3045 } else {
3046 Callback(SS, Actions.GetNameFromUnqualifiedId(Name));
3047 }
3048 // Consume ','.
3049 if (Tok.is(tok::comma)) {
3050 ConsumeToken();
3051 }
3052 }
3053
3054 if (NoIdentIsFound) {
3055 Diag(Tok, diag::err_expected) << tok::identifier;
3056 IsCorrect = false;
3057 }
3058
3059 // Parse ')'.
3060 IsCorrect = !T.consumeClose() && IsCorrect;
3061
3062 return !IsCorrect;
3063}
3064
3065OMPClause *Parser::ParseOpenMPSizesClause() {
3066 SourceLocation ClauseNameLoc = ConsumeToken();
3067 SmallVector<Expr *, 4> ValExprs;
3068
3069 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3070 if (T.consumeOpen()) {
3071 Diag(Tok, diag::err_expected) << tok::l_paren;
3072 return nullptr;
3073 }
3074
3075 while (true) {
3076 ExprResult Val = ParseConstantExpression();
3077 if (!Val.isUsable()) {
3078 T.skipToEnd();
3079 return nullptr;
3080 }
3081
3082 ValExprs.push_back(Val.get());
3083
3084 if (Tok.is(tok::r_paren) || Tok.is(tok::annot_pragma_openmp_end))
3085 break;
3086
3087 ExpectAndConsume(tok::comma);
3088 }
3089
3090 T.consumeClose();
3091
3092 return Actions.ActOnOpenMPSizesClause(
3093 ValExprs, ClauseNameLoc, T.getOpenLocation(), T.getCloseLocation());
3094}
3095
3096OMPClause *Parser::ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind) {
3097 SourceLocation Loc = Tok.getLocation();
3098 ConsumeAnyToken();
3099
3100 // Parse '('.
3101 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3102 if (T.expectAndConsume(diag::err_expected_lparen_after, "uses_allocator"))
3103 return nullptr;
3104 SmallVector<Sema::UsesAllocatorsData, 4> Data;
3105 do {
3106 ExprResult Allocator =
3107 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3108 if (Allocator.isInvalid()) {
3109 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3110 StopBeforeMatch);
3111 break;
3112 }
3113 Sema::UsesAllocatorsData &D = Data.emplace_back();
3114 D.Allocator = Allocator.get();
3115 if (Tok.is(tok::l_paren)) {
3116 BalancedDelimiterTracker T(*this, tok::l_paren,
3117 tok::annot_pragma_openmp_end);
3118 T.consumeOpen();
3119 ExprResult AllocatorTraits =
3120 getLangOpts().CPlusPlus ? ParseCXXIdExpression() : ParseExpression();
3121 T.consumeClose();
3122 if (AllocatorTraits.isInvalid()) {
3123 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3124 StopBeforeMatch);
3125 break;
3126 }
3127 D.AllocatorTraits = AllocatorTraits.get();
3128 D.LParenLoc = T.getOpenLocation();
3129 D.RParenLoc = T.getCloseLocation();
3130 }
3131 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
3132 Diag(Tok, diag::err_omp_expected_punc) << "uses_allocators" << 0;
3133 // Parse ','
3134 if (Tok.is(tok::comma))
3135 ConsumeAnyToken();
3136 } while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end));
3137 T.consumeClose();
3138 return Actions.ActOnOpenMPUsesAllocatorClause(Loc, T.getOpenLocation(),
3139 T.getCloseLocation(), Data);
3140}
3141
3142/// Parsing of OpenMP clauses.
3143///
3144/// clause:
3145/// if-clause | final-clause | num_threads-clause | safelen-clause |
3146/// default-clause | private-clause | firstprivate-clause | shared-clause
3147/// | linear-clause | aligned-clause | collapse-clause | bind-clause |
3148/// lastprivate-clause | reduction-clause | proc_bind-clause |
3149/// schedule-clause | copyin-clause | copyprivate-clause | untied-clause |
3150/// mergeable-clause | flush-clause | read-clause | write-clause |
3151/// update-clause | capture-clause | seq_cst-clause | device-clause |
3152/// simdlen-clause | threads-clause | simd-clause | num_teams-clause |
3153/// thread_limit-clause | priority-clause | grainsize-clause |
3154/// nogroup-clause | num_tasks-clause | hint-clause | to-clause |
3155/// from-clause | is_device_ptr-clause | task_reduction-clause |
3156/// in_reduction-clause | allocator-clause | allocate-clause |
3157/// acq_rel-clause | acquire-clause | release-clause | relaxed-clause |
3158/// depobj-clause | destroy-clause | detach-clause | inclusive-clause |
3159/// exclusive-clause | uses_allocators-clause | use_device_addr-clause |
3160/// has_device_addr
3161///
3162OMPClause *Parser::ParseOpenMPClause(OpenMPDirectiveKind DKind,
3163 OpenMPClauseKind CKind, bool FirstClause) {
3164 OMPClauseKind = CKind;
3165 OMPClause *Clause = nullptr;
3166 bool ErrorFound = false;
3167 bool WrongDirective = false;
3168 // Check if clause is allowed for the given directive.
3169 if (CKind != OMPC_unknown &&
3170 !isAllowedClauseForDirective(DKind, CKind, getLangOpts().OpenMP)) {
3171 Diag(Tok, diag::err_omp_unexpected_clause)
3172 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
3173 ErrorFound = true;
3174 WrongDirective = true;
3175 }
3176
3177 switch (CKind) {
3178 case OMPC_final:
3179 case OMPC_num_threads:
3180 case OMPC_safelen:
3181 case OMPC_simdlen:
3182 case OMPC_collapse:
3183 case OMPC_ordered:
3184 case OMPC_num_teams:
3185 case OMPC_thread_limit:
3186 case OMPC_priority:
3187 case OMPC_grainsize:
3188 case OMPC_num_tasks:
3189 case OMPC_hint:
3190 case OMPC_allocator:
3191 case OMPC_depobj:
3192 case OMPC_detach:
3193 case OMPC_novariants:
3194 case OMPC_nocontext:
3195 case OMPC_filter:
3196 case OMPC_partial:
3197 case OMPC_align:
3198 case OMPC_message:
3199 case OMPC_ompx_dyn_cgroup_mem:
3200 // OpenMP [2.5, Restrictions]
3201 // At most one num_threads clause can appear on the directive.
3202 // OpenMP [2.8.1, simd construct, Restrictions]
3203 // Only one safelen clause can appear on a simd directive.
3204 // Only one simdlen clause can appear on a simd directive.
3205 // Only one collapse clause can appear on a simd directive.
3206 // OpenMP [2.11.1, task Construct, Restrictions]
3207 // At most one if clause can appear on the directive.
3208 // At most one final clause can appear on the directive.
3209 // OpenMP [teams Construct, Restrictions]
3210 // At most one num_teams clause can appear on the directive.
3211 // At most one thread_limit clause can appear on the directive.
3212 // OpenMP [2.9.1, task Construct, Restrictions]
3213 // At most one priority clause can appear on the directive.
3214 // OpenMP [2.9.2, taskloop Construct, Restrictions]
3215 // At most one grainsize clause can appear on the directive.
3216 // OpenMP [2.9.2, taskloop Construct, Restrictions]
3217 // At most one num_tasks clause can appear on the directive.
3218 // OpenMP [2.11.3, allocate Directive, Restrictions]
3219 // At most one allocator clause can appear on the directive.
3220 // OpenMP 5.0, 2.10.1 task Construct, Restrictions.
3221 // At most one detach clause can appear on the directive.
3222 // OpenMP 5.1, 2.3.6 dispatch Construct, Restrictions.
3223 // At most one novariants clause can appear on a dispatch directive.
3224 // At most one nocontext clause can appear on a dispatch directive.
3225 // OpenMP [5.1, error directive, Restrictions]
3226 // At most one message clause can appear on the directive
3227 if (!FirstClause) {
3228 Diag(Tok, diag::err_omp_more_one_clause)
3229 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3230 ErrorFound = true;
3231 }
3232
3233 if ((CKind == OMPC_ordered || CKind == OMPC_partial) &&
3234 PP.LookAhead(/*N=*/0).isNot(tok::l_paren))
3235 Clause = ParseOpenMPClause(CKind, WrongDirective);
3236 else if (CKind == OMPC_grainsize || CKind == OMPC_num_tasks)
3237 Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
3238 else
3239 Clause = ParseOpenMPSingleExprClause(CKind, WrongDirective);
3240 break;
3241 case OMPC_default:
3242 case OMPC_proc_bind:
3243 case OMPC_atomic_default_mem_order:
3244 case OMPC_at:
3245 case OMPC_severity:
3246 case OMPC_bind:
3247 // OpenMP [2.14.3.1, Restrictions]
3248 // Only a single default clause may be specified on a parallel, task or
3249 // teams directive.
3250 // OpenMP [2.5, parallel Construct, Restrictions]
3251 // At most one proc_bind clause can appear on the directive.
3252 // OpenMP [5.0, Requires directive, Restrictions]
3253 // At most one atomic_default_mem_order clause can appear
3254 // on the directive
3255 // OpenMP [5.1, error directive, Restrictions]
3256 // At most one at clause can appear on the directive
3257 // At most one severity clause can appear on the directive
3258 // OpenMP 5.1, 2.11.7 loop Construct, Restrictions.
3259 // At most one bind clause can appear on a loop directive.
3260 if (!FirstClause) {
3261 Diag(Tok, diag::err_omp_more_one_clause)
3262 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3263 ErrorFound = true;
3264 }
3265
3266 Clause = ParseOpenMPSimpleClause(CKind, WrongDirective);
3267 break;
3268 case OMPC_device:
3269 case OMPC_schedule:
3270 case OMPC_dist_schedule:
3271 case OMPC_defaultmap:
3272 case OMPC_order:
3273 // OpenMP [2.7.1, Restrictions, p. 3]
3274 // Only one schedule clause can appear on a loop directive.
3275 // OpenMP 4.5 [2.10.4, Restrictions, p. 106]
3276 // At most one defaultmap clause can appear on the directive.
3277 // OpenMP 5.0 [2.12.5, target construct, Restrictions]
3278 // At most one device clause can appear on the directive.
3279 // OpenMP 5.1 [2.11.3, order clause, Restrictions]
3280 // At most one order clause may appear on a construct.
3281 if ((getLangOpts().OpenMP < 50 || CKind != OMPC_defaultmap) &&
3282 (CKind != OMPC_order || getLangOpts().OpenMP >= 51) && !FirstClause) {
3283 Diag(Tok, diag::err_omp_more_one_clause)
3284 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3285 ErrorFound = true;
3286 }
3287 [[fallthrough]];
3288 case OMPC_if:
3289 Clause = ParseOpenMPSingleExprWithArgClause(DKind, CKind, WrongDirective);
3290 break;
3291 case OMPC_nowait:
3292 case OMPC_untied:
3293 case OMPC_mergeable:
3294 case OMPC_read:
3295 case OMPC_write:
3296 case OMPC_capture:
3297 case OMPC_compare:
3298 case OMPC_seq_cst:
3299 case OMPC_acq_rel:
3300 case OMPC_acquire:
3301 case OMPC_release:
3302 case OMPC_relaxed:
3303 case OMPC_threads:
3304 case OMPC_simd:
3305 case OMPC_nogroup:
3306 case OMPC_unified_address:
3307 case OMPC_unified_shared_memory:
3308 case OMPC_reverse_offload:
3309 case OMPC_dynamic_allocators:
3310 case OMPC_full:
3311 // OpenMP [2.7.1, Restrictions, p. 9]
3312 // Only one ordered clause can appear on a loop directive.
3313 // OpenMP [2.7.1, Restrictions, C/C++, p. 4]
3314 // Only one nowait clause can appear on a for directive.
3315 // OpenMP [5.0, Requires directive, Restrictions]
3316 // Each of the requires clauses can appear at most once on the directive.
3317 if (!FirstClause) {
3318 Diag(Tok, diag::err_omp_more_one_clause)
3319 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3320 ErrorFound = true;
3321 }
3322
3323 Clause = ParseOpenMPClause(CKind, WrongDirective);
3324 break;
3325 case OMPC_update:
3326 if (!FirstClause) {
3327 Diag(Tok, diag::err_omp_more_one_clause)
3328 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3329 ErrorFound = true;
3330 }
3331
3332 Clause = (DKind == OMPD_depobj)
3333 ? ParseOpenMPSimpleClause(CKind, WrongDirective)
3334 : ParseOpenMPClause(CKind, WrongDirective);
3335 break;
3336 case OMPC_private:
3337 case OMPC_firstprivate:
3338 case OMPC_lastprivate:
3339 case OMPC_shared:
3340 case OMPC_reduction:
3341 case OMPC_task_reduction:
3342 case OMPC_in_reduction:
3343 case OMPC_linear:
3344 case OMPC_aligned:
3345 case OMPC_copyin:
3346 case OMPC_copyprivate:
3347 case OMPC_flush:
3348 case OMPC_depend:
3349 case OMPC_map:
3350 case OMPC_to:
3351 case OMPC_from:
3352 case OMPC_use_device_ptr:
3353 case OMPC_use_device_addr:
3354 case OMPC_is_device_ptr:
3355 case OMPC_has_device_addr:
3356 case OMPC_allocate:
3357 case OMPC_nontemporal:
3358 case OMPC_inclusive:
3359 case OMPC_exclusive:
3360 case OMPC_affinity:
3361 Clause = ParseOpenMPVarListClause(DKind, CKind, WrongDirective);
3362 break;
3363 case OMPC_sizes:
3364 if (!FirstClause) {
3365 Diag(Tok, diag::err_omp_more_one_clause)
3366 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3367 ErrorFound = true;
3368 }
3369
3370 Clause = ParseOpenMPSizesClause();
3371 break;
3372 case OMPC_uses_allocators:
3373 Clause = ParseOpenMPUsesAllocatorClause(DKind);
3374 break;
3375 case OMPC_destroy:
3376 if (DKind != OMPD_interop) {
3377 if (!FirstClause) {
3378 Diag(Tok, diag::err_omp_more_one_clause)
3379 << getOpenMPDirectiveName(DKind) << getOpenMPClauseName(CKind) << 0;
3380 ErrorFound = true;
3381 }
3382 Clause = ParseOpenMPClause(CKind, WrongDirective);
3383 break;
3384 }
3385 [[fallthrough]];
3386 case OMPC_init:
3387 case OMPC_use:
3388 Clause = ParseOpenMPInteropClause(CKind, WrongDirective);
3389 break;
3390 case OMPC_device_type:
3391 case OMPC_unknown:
3392 skipUntilPragmaOpenMPEnd(DKind);
3393 break;
3394 case OMPC_threadprivate:
3395 case OMPC_uniform:
3396 case OMPC_match:
3397 if (!WrongDirective)
3398 Diag(Tok, diag::err_omp_unexpected_clause)
3399 << getOpenMPClauseName(CKind) << getOpenMPDirectiveName(DKind);
3400 SkipUntil(tok::comma, tok::annot_pragma_openmp_end, StopBeforeMatch);
3401 break;
3402 default:
3403 break;
3404 }
3405 return ErrorFound ? nullptr : Clause;
3406}
3407
3408/// Parses simple expression in parens for single-expression clauses of OpenMP
3409/// constructs.
3410/// \param RLoc Returned location of right paren.
3411ExprResult Parser::ParseOpenMPParensExpr(StringRef ClauseName,
3412 SourceLocation &RLoc,
3413 bool IsAddressOfOperand) {
3414 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3415 if (T.expectAndConsume(diag::err_expected_lparen_after, ClauseName.data()))
3416 return ExprError();
3417
3418 SourceLocation ELoc = Tok.getLocation();
3419 ExprResult LHS(
3420 ParseCastExpression(AnyCastExpr, IsAddressOfOperand, NotTypeCast));
3421 ExprResult Val(ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3422 Val = Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3423
3424 // Parse ')'.
3425 RLoc = Tok.getLocation();
3426 if (!T.consumeClose())
3427 RLoc = T.getCloseLocation();
3428
3429 return Val;
3430}
3431
3432/// Parsing of OpenMP clauses with single expressions like 'final',
3433/// 'collapse', 'safelen', 'num_threads', 'simdlen', 'num_teams',
3434/// 'thread_limit', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'hint' or
3435/// 'detach'.
3436///
3437/// final-clause:
3438/// 'final' '(' expression ')'
3439///
3440/// num_threads-clause:
3441/// 'num_threads' '(' expression ')'
3442///
3443/// safelen-clause:
3444/// 'safelen' '(' expression ')'
3445///
3446/// simdlen-clause:
3447/// 'simdlen' '(' expression ')'
3448///
3449/// collapse-clause:
3450/// 'collapse' '(' expression ')'
3451///
3452/// priority-clause:
3453/// 'priority' '(' expression ')'
3454///
3455/// grainsize-clause:
3456/// 'grainsize' '(' expression ')'
3457///
3458/// num_tasks-clause:
3459/// 'num_tasks' '(' expression ')'
3460///
3461/// hint-clause:
3462/// 'hint' '(' expression ')'
3463///
3464/// allocator-clause:
3465/// 'allocator' '(' expression ')'
3466///
3467/// detach-clause:
3468/// 'detach' '(' event-handler-expression ')'
3469///
3470/// align-clause
3471/// 'align' '(' positive-integer-constant ')'
3472///
3473OMPClause *Parser::ParseOpenMPSingleExprClause(OpenMPClauseKind Kind,
3474 bool ParseOnly) {
3475 SourceLocation Loc = ConsumeToken();
3476 SourceLocation LLoc = Tok.getLocation();
3477 SourceLocation RLoc;
3478
3479 ExprResult Val = ParseOpenMPParensExpr(getOpenMPClauseName(Kind), RLoc);
3480
3481 if (Val.isInvalid())
3482 return nullptr;
3483
3484 if (ParseOnly)
3485 return nullptr;
3486 return Actions.ActOnOpenMPSingleExprClause(Kind, Val.get(), Loc, LLoc, RLoc);
3487}
3488
3489/// Parse indirect clause for '#pragma omp declare target' directive.
3490/// 'indirect' '[' '(' invoked-by-fptr ')' ']'
3491/// where invoked-by-fptr is a constant boolean expression that evaluates to
3492/// true or false at compile time.
3493bool Parser::ParseOpenMPIndirectClause(Sema::DeclareTargetContextInfo &DTCI,
3494 bool ParseOnly) {
3495 SourceLocation Loc = ConsumeToken();
3496 SourceLocation RLoc;
3497
3498 if (Tok.isNot(tok::l_paren)) {
3499 if (ParseOnly)
3500 return false;
3501 DTCI.Indirect = nullptr;
3502 return true;
3503 }
3504
3505 ExprResult Val =
3506 ParseOpenMPParensExpr(getOpenMPClauseName(OMPC_indirect), RLoc);
3507 if (Val.isInvalid())
3508 return false;
3509
3510 if (ParseOnly)
3511 return false;
3512
3513 if (!Val.get()->isValueDependent() && !Val.get()->isTypeDependent() &&
3514 !Val.get()->isInstantiationDependent() &&
3515 !Val.get()->containsUnexpandedParameterPack()) {
3516 ExprResult Ret = Actions.CheckBooleanCondition(Loc, Val.get());
3517 if (Ret.isInvalid())
3518 return false;
3519 llvm::APSInt Result;
3520 Ret = Actions.VerifyIntegerConstantExpression(Val.get(), &Result,
3521 Sema::AllowFold);
3522 if (Ret.isInvalid())
3523 return false;
3524 DTCI.Indirect = Val.get();
3525 return true;
3526 }
3527 return false;
3528}
3529
3530/// Parses a comma-separated list of interop-types and a prefer_type list.
3531///
3532bool Parser::ParseOMPInteropInfo(OMPInteropInfo &InteropInfo,
3533 OpenMPClauseKind Kind) {
3534 const Token &Tok = getCurToken();
3535 bool HasError = false;
3536 bool IsTarget = false;
3537 bool IsTargetSync = false;
3538
3539 while (Tok.is(tok::identifier)) {
3540 // Currently prefer_type is only allowed with 'init' and it must be first.
3541 bool PreferTypeAllowed = Kind == OMPC_init &&
3542 InteropInfo.PreferTypes.empty() && !IsTarget &&
3543 !IsTargetSync;
3544 if (Tok.getIdentifierInfo()->isStr("target")) {
3545 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions]
3546 // Each interop-type may be specified on an action-clause at most
3547 // once.
3548 if (IsTarget)
3549 Diag(Tok, diag::warn_omp_more_one_interop_type) << "target";
3550 IsTarget = true;
3551 ConsumeToken();
3552 } else if (Tok.getIdentifierInfo()->isStr("targetsync")) {
3553 if (IsTargetSync)
3554 Diag(Tok, diag::warn_omp_more_one_interop_type) << "targetsync";
3555 IsTargetSync = true;
3556 ConsumeToken();
3557 } else if (Tok.getIdentifierInfo()->isStr("prefer_type") &&
3558 PreferTypeAllowed) {
3559 ConsumeToken();
3560 BalancedDelimiterTracker PT(*this, tok::l_paren,
3561 tok::annot_pragma_openmp_end);
3562 if (PT.expectAndConsume(diag::err_expected_lparen_after, "prefer_type"))
3563 HasError = true;
3564
3565 while (Tok.isNot(tok::r_paren)) {
3566 SourceLocation Loc = Tok.getLocation();
3567 ExprResult LHS = ParseCastExpression(AnyCastExpr);
3568 ExprResult PTExpr = Actions.CorrectDelayedTyposInExpr(
3569 ParseRHSOfBinaryExpression(LHS, prec::Conditional));
3570 PTExpr = Actions.ActOnFinishFullExpr(PTExpr.get(), Loc,
3571 /*DiscardedValue=*/false);
3572 if (PTExpr.isUsable()) {
3573 InteropInfo.PreferTypes.push_back(PTExpr.get());
3574 } else {
3575 HasError = true;
3576 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3577 StopBeforeMatch);
3578 }
3579
3580 if (Tok.is(tok::comma))
3581 ConsumeToken();
3582 }
3583 PT.consumeClose();
3584 } else {
3585 HasError = true;
3586 Diag(Tok, diag::err_omp_expected_interop_type);
3587 ConsumeToken();
3588 }
3589 if (!Tok.is(tok::comma))
3590 break;
3591 ConsumeToken();
3592 }
3593
3594 if (!HasError && !IsTarget && !IsTargetSync) {
3595 Diag(Tok, diag::err_omp_expected_interop_type);
3596 HasError = true;
3597 }
3598
3599 if (Kind == OMPC_init) {
3600 if (Tok.isNot(tok::colon) && (IsTarget || IsTargetSync))
3601 Diag(Tok, diag::warn_pragma_expected_colon) << "interop types";
3602 if (Tok.is(tok::colon))
3603 ConsumeToken();
3604 }
3605
3606 // As of OpenMP 5.1,there are two interop-types, "target" and
3607 // "targetsync". Either or both are allowed for a single interop.
3608 InteropInfo.IsTarget = IsTarget;
3609 InteropInfo.IsTargetSync = IsTargetSync;
3610
3611 return HasError;
3612}
3613
3614/// Parsing of OpenMP clauses that use an interop-var.
3615///
3616/// init-clause:
3617/// init([interop-modifier, ]interop-type[[, interop-type] ... ]:interop-var)
3618///
3619/// destroy-clause:
3620/// destroy(interop-var)
3621///
3622/// use-clause:
3623/// use(interop-var)
3624///
3625/// interop-modifier:
3626/// prefer_type(preference-list)
3627///
3628/// preference-list:
3629/// foreign-runtime-id [, foreign-runtime-id]...
3630///
3631/// foreign-runtime-id:
3632/// <string-literal> | <constant-integral-expression>
3633///
3634/// interop-type:
3635/// target | targetsync
3636///
3637OMPClause *Parser::ParseOpenMPInteropClause(OpenMPClauseKind Kind,
3638 bool ParseOnly) {
3639 SourceLocation Loc = ConsumeToken();
3640 // Parse '('.
3641 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3642 if (T.expectAndConsume(diag::err_expected_lparen_after,
3643 getOpenMPClauseName(Kind).data()))
3644 return nullptr;
3645
3646 bool InteropError = false;
3647 OMPInteropInfo InteropInfo;
3648 if (Kind == OMPC_init)
3649 InteropError = ParseOMPInteropInfo(InteropInfo, OMPC_init);
3650
3651 // Parse the variable.
3652 SourceLocation VarLoc = Tok.getLocation();
3653 ExprResult InteropVarExpr =
3654 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
3655 if (!InteropVarExpr.isUsable()) {
3656 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
3657 StopBeforeMatch);
3658 }
3659
3660 // Parse ')'.
3661 SourceLocation RLoc = Tok.getLocation();
3662 if (!T.consumeClose())
3663 RLoc = T.getCloseLocation();
3664
3665 if (ParseOnly || !InteropVarExpr.isUsable() || InteropError)
3666 return nullptr;
3667
3668 if (Kind == OMPC_init)
3669 return Actions.ActOnOpenMPInitClause(InteropVarExpr.get(), InteropInfo, Loc,
3670 T.getOpenLocation(), VarLoc, RLoc);
3671 if (Kind == OMPC_use)
3672 return Actions.ActOnOpenMPUseClause(InteropVarExpr.get(), Loc,
3673 T.getOpenLocation(), VarLoc, RLoc);
3674
3675 if (Kind == OMPC_destroy)
3676 return Actions.ActOnOpenMPDestroyClause(InteropVarExpr.get(), Loc,
3677 T.getOpenLocation(), VarLoc, RLoc);
3678
3679 llvm_unreachable("Unexpected interop variable clause.")::llvm::llvm_unreachable_internal("Unexpected interop variable clause."
, "clang/lib/Parse/ParseOpenMP.cpp", 3679)
;
3680}
3681
3682/// Parsing of simple OpenMP clauses like 'default' or 'proc_bind'.
3683///
3684/// default-clause:
3685/// 'default' '(' 'none' | 'shared' | 'private' | 'firstprivate' ')'
3686///
3687/// proc_bind-clause:
3688/// 'proc_bind' '(' 'master' | 'close' | 'spread' ')'
3689///
3690/// bind-clause:
3691/// 'bind' '(' 'teams' | 'parallel' | 'thread' ')'
3692///
3693/// update-clause:
3694/// 'update' '(' 'in' | 'out' | 'inout' | 'mutexinoutset' |
3695/// 'inoutset' ')'
3696///
3697OMPClause *Parser::ParseOpenMPSimpleClause(OpenMPClauseKind Kind,
3698 bool ParseOnly) {
3699 std::optional<SimpleClauseData> Val = parseOpenMPSimpleClause(*this, Kind);
3700 if (!Val || ParseOnly)
3701 return nullptr;
3702 if (getLangOpts().OpenMP < 51 && Kind == OMPC_default &&
3703 (static_cast<DefaultKind>(Val->Type) == OMP_DEFAULT_private ||
3704 static_cast<DefaultKind>(Val->Type) ==
3705 OMP_DEFAULT_firstprivate)) {
3706 Diag(Val->LOpen, diag::err_omp_invalid_dsa)
3707 << getOpenMPClauseName(static_cast<DefaultKind>(Val->Type) ==
3708 OMP_DEFAULT_private
3709 ? OMPC_private
3710 : OMPC_firstprivate)
3711 << getOpenMPClauseName(OMPC_default) << "5.1";
3712 return nullptr;
3713 }
3714 return Actions.ActOnOpenMPSimpleClause(Kind, Val->Type,
3715 Val->TypeLoc, Val->LOpen,
3716 Val->Loc, Val->RLoc);
3717}
3718
3719/// Parsing of OpenMP clauses like 'ordered'.
3720///
3721/// ordered-clause:
3722/// 'ordered'
3723///
3724/// nowait-clause:
3725/// 'nowait'
3726///
3727/// untied-clause:
3728/// 'untied'
3729///
3730/// mergeable-clause:
3731/// 'mergeable'
3732///
3733/// read-clause:
3734/// 'read'
3735///
3736/// threads-clause:
3737/// 'threads'
3738///
3739/// simd-clause:
3740/// 'simd'
3741///
3742/// nogroup-clause:
3743/// 'nogroup'
3744///
3745OMPClause *Parser::ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly) {
3746 SourceLocation Loc = Tok.getLocation();
3747 ConsumeAnyToken();
3748
3749 if (ParseOnly)
3750 return nullptr;
3751 return Actions.ActOnOpenMPClause(Kind, Loc, Tok.getLocation());
3752}
3753
3754/// Parsing of OpenMP clauses with single expressions and some additional
3755/// argument like 'schedule' or 'dist_schedule'.
3756///
3757/// schedule-clause:
3758/// 'schedule' '(' [ modifier [ ',' modifier ] ':' ] kind [',' expression ]
3759/// ')'
3760///
3761/// if-clause:
3762/// 'if' '(' [ directive-name-modifier ':' ] expression ')'
3763///
3764/// defaultmap:
3765/// 'defaultmap' '(' modifier [ ':' kind ] ')'
3766///
3767/// device-clause:
3768/// 'device' '(' [ device-modifier ':' ] expression ')'
3769///
3770OMPClause *Parser::ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind,
3771 OpenMPClauseKind Kind,
3772 bool ParseOnly) {
3773 SourceLocation Loc = ConsumeToken();
3774 SourceLocation DelimLoc;
3775 // Parse '('.
3776 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
3777 if (T.expectAndConsume(diag::err_expected_lparen_after,
3778 getOpenMPClauseName(Kind).data()))
3779 return nullptr;
3780
3781 ExprResult Val;
3782 SmallVector<unsigned, 4> Arg;
3783 SmallVector<SourceLocation, 4> KLoc;
3784 if (Kind == OMPC_schedule) {
3785 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
3786 Arg.resize(NumberOfElements);
3787 KLoc.resize(NumberOfElements);
3788 Arg[Modifier1] = OMPC_SCHEDULE_MODIFIER_unknown;
3789 Arg[Modifier2] = OMPC_SCHEDULE_MODIFIER_unknown;
3790 Arg[ScheduleKind] = OMPC_SCHEDULE_unknown;
3791 unsigned KindModifier = getOpenMPSimpleClauseType(
3792 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3793 if (KindModifier > OMPC_SCHEDULE_unknown) {
3794 // Parse 'modifier'
3795 Arg[Modifier1] = KindModifier;
3796 KLoc[Modifier1] = Tok.getLocation();
3797 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3798 Tok.isNot(tok::annot_pragma_openmp_end))
3799 ConsumeAnyToken();
3800 if (Tok.is(tok::comma)) {
3801 // Parse ',' 'modifier'
3802 ConsumeAnyToken();
3803 KindModifier = getOpenMPSimpleClauseType(
3804 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3805 Arg[Modifier2] = KindModifier > OMPC_SCHEDULE_unknown
3806 ? KindModifier
3807 : (unsigned)OMPC_SCHEDULE_unknown;
3808 KLoc[Modifier2] = Tok.getLocation();
3809 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3810 Tok.isNot(tok::annot_pragma_openmp_end))
3811 ConsumeAnyToken();
3812 }
3813 // Parse ':'
3814 if (Tok.is(tok::colon))
3815 ConsumeAnyToken();
3816 else
3817 Diag(Tok, diag::warn_pragma_expected_colon) << "schedule modifier";
3818 KindModifier = getOpenMPSimpleClauseType(
3819 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3820 }
3821 Arg[ScheduleKind] = KindModifier;
3822 KLoc[ScheduleKind] = Tok.getLocation();
3823 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3824 Tok.isNot(tok::annot_pragma_openmp_end))
3825 ConsumeAnyToken();
3826 if ((Arg[ScheduleKind] == OMPC_SCHEDULE_static ||
3827 Arg[ScheduleKind] == OMPC_SCHEDULE_dynamic ||
3828 Arg[ScheduleKind] == OMPC_SCHEDULE_guided) &&
3829 Tok.is(tok::comma))
3830 DelimLoc = ConsumeAnyToken();
3831 } else if (Kind == OMPC_dist_schedule) {
3832 Arg.push_back(getOpenMPSimpleClauseType(
3833 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3834 KLoc.push_back(Tok.getLocation());
3835 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3836 Tok.isNot(tok::annot_pragma_openmp_end))
3837 ConsumeAnyToken();
3838 if (Arg.back() == OMPC_DIST_SCHEDULE_static && Tok.is(tok::comma))
3839 DelimLoc = ConsumeAnyToken();
3840 } else if (Kind == OMPC_defaultmap) {
3841 // Get a defaultmap modifier
3842 unsigned Modifier = getOpenMPSimpleClauseType(
3843 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3844 // Set defaultmap modifier to unknown if it is either scalar, aggregate, or
3845 // pointer
3846 if (Modifier < OMPC_DEFAULTMAP_MODIFIER_unknown)
3847 Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown;
3848 Arg.push_back(Modifier);
3849 KLoc.push_back(Tok.getLocation());
3850 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3851 Tok.isNot(tok::annot_pragma_openmp_end))
3852 ConsumeAnyToken();
3853 // Parse ':'
3854 if (Tok.is(tok::colon) || getLangOpts().OpenMP < 50) {
3855 if (Tok.is(tok::colon))
3856 ConsumeAnyToken();
3857 else if (Arg.back() != OMPC_DEFAULTMAP_MODIFIER_unknown)
3858 Diag(Tok, diag::warn_pragma_expected_colon) << "defaultmap modifier";
3859 // Get a defaultmap kind
3860 Arg.push_back(getOpenMPSimpleClauseType(
3861 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3862 KLoc.push_back(Tok.getLocation());
3863 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3864 Tok.isNot(tok::annot_pragma_openmp_end))
3865 ConsumeAnyToken();
3866 } else {
3867 Arg.push_back(OMPC_DEFAULTMAP_unknown);
3868 KLoc.push_back(SourceLocation());
3869 }
3870 } else if (Kind == OMPC_order) {
3871 enum { Modifier, OrderKind, NumberOfElements };
3872 Arg.resize(NumberOfElements);
3873 KLoc.resize(NumberOfElements);
3874 Arg[Modifier] = OMPC_ORDER_MODIFIER_unknown;
3875 Arg[OrderKind] = OMPC_ORDER_unknown;
3876 unsigned KindModifier = getOpenMPSimpleClauseType(
3877 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3878 if (KindModifier > OMPC_ORDER_unknown) {
3879 // Parse 'modifier'
3880 Arg[Modifier] = KindModifier;
3881 KLoc[Modifier] = Tok.getLocation();
3882 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3883 Tok.isNot(tok::annot_pragma_openmp_end))
3884 ConsumeAnyToken();
3885 // Parse ':'
3886 if (Tok.is(tok::colon))
3887 ConsumeAnyToken();
3888 else
3889 Diag(Tok, diag::warn_pragma_expected_colon) << "order modifier";
3890 KindModifier = getOpenMPSimpleClauseType(
3891 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts());
3892 }
3893 Arg[OrderKind] = KindModifier;
3894 KLoc[OrderKind] = Tok.getLocation();
3895 if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::comma) &&
3896 Tok.isNot(tok::annot_pragma_openmp_end))
3897 ConsumeAnyToken();
3898 } else if (Kind == OMPC_device) {
3899 // Only target executable directives support extended device construct.
3900 if (isOpenMPTargetExecutionDirective(DKind) && getLangOpts().OpenMP >= 50 &&
3901 NextToken().is(tok::colon)) {
3902 // Parse optional <device modifier> ':'
3903 Arg.push_back(getOpenMPSimpleClauseType(
3904 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok), getLangOpts()));
3905 KLoc.push_back(Tok.getLocation());
3906 ConsumeAnyToken();
3907 // Parse ':'
3908 ConsumeAnyToken();
3909 } else {
3910 Arg.push_back(OMPC_DEVICE_unknown);
3911 KLoc.emplace_back();
3912 }
3913 } else if (Kind == OMPC_grainsize) {
3914 // Parse optional <grainsize modifier> ':'
3915 OpenMPGrainsizeClauseModifier Modifier =
3916 static_cast<OpenMPGrainsizeClauseModifier>(getOpenMPSimpleClauseType(
3917 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
3918 getLangOpts()));
3919 if (getLangOpts().OpenMP >= 51) {
3920 if (NextToken().is(tok::colon)) {
3921 Arg.push_back(Modifier);
3922 KLoc.push_back(Tok.getLocation());
3923 // Parse modifier
3924 ConsumeAnyToken();
3925 // Parse ':'
3926 ConsumeAnyToken();
3927 } else {
3928 if (Modifier == OMPC_GRAINSIZE_strict) {
3929 Diag(Tok, diag::err_modifier_expected_colon) << "strict";
3930 // Parse modifier
3931 ConsumeAnyToken();
3932 }
3933 Arg.push_back(OMPC_GRAINSIZE_unknown);
3934 KLoc.emplace_back();
3935 }
3936 } else {
3937 Arg.push_back(OMPC_GRAINSIZE_unknown);
3938 KLoc.emplace_back();
3939 }
3940 } else if (Kind == OMPC_num_tasks) {
3941 // Parse optional <num_tasks modifier> ':'
3942 OpenMPNumTasksClauseModifier Modifier =
3943 static_cast<OpenMPNumTasksClauseModifier>(getOpenMPSimpleClauseType(
3944 Kind, Tok.isAnnotation() ? "" : PP.getSpelling(Tok),
3945 getLangOpts()));
3946 if (getLangOpts().OpenMP >= 51) {
3947 if (NextToken().is(tok::colon)) {
3948 Arg.push_back(Modifier);
3949 KLoc.push_back(Tok.getLocation());
3950 // Parse modifier
3951 ConsumeAnyToken();
3952 // Parse ':'
3953 ConsumeAnyToken();
3954 } else {
3955 if (Modifier == OMPC_NUMTASKS_strict) {
3956 Diag(Tok, diag::err_modifier_expected_colon) << "strict";
3957 // Parse modifier
3958 ConsumeAnyToken();
3959 }
3960 Arg.push_back(OMPC_NUMTASKS_unknown);
3961 KLoc.emplace_back();
3962 }
3963 } else {
3964 Arg.push_back(OMPC_NUMTASKS_unknown);
3965 KLoc.emplace_back();
3966 }
3967 } else {
3968 assert(Kind == OMPC_if)(static_cast <bool> (Kind == OMPC_if) ? void (0) : __assert_fail
("Kind == OMPC_if", "clang/lib/Parse/ParseOpenMP.cpp", 3968,
__extension__ __PRETTY_FUNCTION__))
;
3969 KLoc.push_back(Tok.getLocation());
3970 TentativeParsingAction TPA(*this);
3971 auto DK = parseOpenMPDirectiveKind(*this);
3972 Arg.push_back(DK);
3973 if (DK != OMPD_unknown) {
3974 ConsumeToken();
3975 if (Tok.is(tok::colon) && getLangOpts().OpenMP > 40) {
3976 TPA.Commit();
3977 DelimLoc = ConsumeToken();
3978 } else {
3979 TPA.Revert();
3980 Arg.back() = unsigned(OMPD_unknown);
3981 }
3982 } else {
3983 TPA.Revert();
3984 }
3985 }
3986
3987 bool NeedAnExpression = (Kind == OMPC_schedule && DelimLoc.isValid()) ||
3988 (Kind == OMPC_dist_schedule && DelimLoc.isValid()) ||
3989 Kind == OMPC_if || Kind == OMPC_device ||
3990 Kind == OMPC_grainsize || Kind == OMPC_num_tasks;
3991 if (NeedAnExpression) {
3992 SourceLocation ELoc = Tok.getLocation();
3993 ExprResult LHS(ParseCastExpression(AnyCastExpr, false, NotTypeCast));
3994 Val = ParseRHSOfBinaryExpression(LHS, prec::Conditional);
3995 Val =
3996 Actions.ActOnFinishFullExpr(Val.get(), ELoc, /*DiscardedValue*/ false);
3997 }
3998
3999 // Parse ')'.
4000 SourceLocation RLoc = Tok.getLocation();
4001 if (!T.consumeClose())
4002 RLoc = T.getCloseLocation();
4003
4004 if (NeedAnExpression && Val.isInvalid())
4005 return nullptr;
4006
4007 if (ParseOnly)
4008 return nullptr;
4009 return Actions.ActOnOpenMPSingleExprWithArgClause(
4010 Kind, Arg, Val.get(), Loc, T.getOpenLocation(), KLoc, DelimLoc, RLoc);
4011}
4012
4013static bool ParseReductionId(Parser &P, CXXScopeSpec &ReductionIdScopeSpec,
4014 UnqualifiedId &ReductionId) {
4015 if (ReductionIdScopeSpec.isEmpty()) {
4016 auto OOK = OO_None;
4017 switch (P.getCurToken().getKind()) {
4018 case tok::plus:
4019 OOK = OO_Plus;
4020 break;
4021 case tok::minus:
4022 OOK = OO_Minus;
4023 break;
4024 case tok::star:
4025 OOK = OO_Star;
4026 break;
4027 case tok::amp:
4028 OOK = OO_Amp;
4029 break;
4030 case tok::pipe:
4031 OOK = OO_Pipe;
4032 break;
4033 case tok::caret:
4034 OOK = OO_Caret;
4035 break;
4036 case tok::ampamp:
4037 OOK = OO_AmpAmp;
4038 break;
4039 case tok::pipepipe:
4040 OOK = OO_PipePipe;
4041 break;
4042 default:
4043 break;
4044 }
4045 if (OOK != OO_None) {
4046 SourceLocation OpLoc = P.ConsumeToken();
4047 SourceLocation SymbolLocations[] = {OpLoc, OpLoc, SourceLocation()};
4048 ReductionId.setOperatorFunctionId(OpLoc, OOK, SymbolLocations);
4049 return false;
4050 }
4051 }
4052 return P.ParseUnqualifiedId(
4053 ReductionIdScopeSpec, /*ObjectType=*/nullptr,
4054 /*ObjectHadErrors=*/false, /*EnteringContext*/ false,
4055 /*AllowDestructorName*/ false,
4056 /*AllowConstructorName*/ false,
4057 /*AllowDeductionGuide*/ false, nullptr, ReductionId);
4058}
4059
4060/// Checks if the token is a valid map-type-modifier.
4061/// FIXME: It will return an OpenMPMapClauseKind if that's what it parses.
4062static OpenMPMapModifierKind isMapModifier(Parser &P) {
4063 Token Tok = P.getCurToken();
4064 if (!Tok.is(tok::identifier))
4065 return OMPC_MAP_MODIFIER_unknown;
4066
4067 Preprocessor &PP = P.getPreprocessor();
4068 OpenMPMapModifierKind TypeModifier =
4069 static_cast<OpenMPMapModifierKind>(getOpenMPSimpleClauseType(
4070 OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
4071 return TypeModifier;
4072}
4073
4074/// Parse the mapper modifier in map, to, and from clauses.
4075bool Parser::parseMapperModifier(Sema::OpenMPVarListDataTy &Data) {
4076 // Parse '('.
4077 BalancedDelimiterTracker T(*this, tok::l_paren, tok::colon);
4078 if (T.expectAndConsume(diag::err_expected_lparen_after, "mapper")) {
4079 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4080 StopBeforeMatch);
4081 return true;
4082 }
4083 // Parse mapper-identifier
4084 if (getLangOpts().CPlusPlus)
4085 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
4086 /*ObjectType=*/nullptr,
4087 /*ObjectHasErrors=*/false,
4088 /*EnteringContext=*/false);
4089 if (Tok.isNot(tok::identifier) && Tok.isNot(tok::kw_default)) {
4090 Diag(Tok.getLocation(), diag::err_omp_mapper_illegal_identifier);
4091 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4092 StopBeforeMatch);
4093 return true;
4094 }
4095 auto &DeclNames = Actions.getASTContext().DeclarationNames;
4096 Data.ReductionOrMapperId = DeclarationNameInfo(
4097 DeclNames.getIdentifier(Tok.getIdentifierInfo()), Tok.getLocation());
4098 ConsumeToken();
4099 // Parse ')'.
4100 return T.consumeClose();
4101}
4102
4103/// Parse map-type-modifiers in map clause.
4104/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
4105/// where, map-type-modifier ::= always | close | mapper(mapper-identifier) |
4106/// present
4107bool Parser::parseMapTypeModifiers(Sema::OpenMPVarListDataTy &Data) {
4108 while (getCurToken().isNot(tok::colon)) {
4109 OpenMPMapModifierKind TypeModifier = isMapModifier(*this);
4110 if (TypeModifier == OMPC_MAP_MODIFIER_always ||
4111 TypeModifier == OMPC_MAP_MODIFIER_close ||
4112 TypeModifier == OMPC_MAP_MODIFIER_present ||
4113 TypeModifier == OMPC_MAP_MODIFIER_ompx_hold) {
4114 Data.MapTypeModifiers.push_back(TypeModifier);
4115 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
4116 ConsumeToken();
4117 } else if (TypeModifier == OMPC_MAP_MODIFIER_mapper) {
4118 Data.MapTypeModifiers.push_back(TypeModifier);
4119 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
4120 ConsumeToken();
4121 if (parseMapperModifier(Data))
4122 return true;
4123 } else {
4124 // For the case of unknown map-type-modifier or a map-type.
4125 // Map-type is followed by a colon; the function returns when it
4126 // encounters a token followed by a colon.
4127 if (Tok.is(tok::comma)) {
4128 Diag(Tok, diag::err_omp_map_type_modifier_missing);
4129 ConsumeToken();
4130 continue;
4131 }
4132 // Potential map-type token as it is followed by a colon.
4133 if (PP.LookAhead(0).is(tok::colon))
4134 return false;
4135 Diag(Tok, diag::err_omp_unknown_map_type_modifier)
4136 << (getLangOpts().OpenMP >= 51 ? (getLangOpts().OpenMP >= 52 ? 2 : 1)
4137 : 0)
4138 << getLangOpts().OpenMPExtensions;
4139 ConsumeToken();
4140 }
4141 if (getCurToken().is(tok::comma))
4142 ConsumeToken();
4143 }
4144 return false;
4145}
4146
4147/// Checks if the token is a valid map-type.
4148/// FIXME: It will return an OpenMPMapModifierKind if that's what it parses.
4149static OpenMPMapClauseKind isMapType(Parser &P) {
4150 Token Tok = P.getCurToken();
4151 // The map-type token can be either an identifier or the C++ delete keyword.
4152 if (!Tok.isOneOf(tok::identifier, tok::kw_delete))
4153 return OMPC_MAP_unknown;
4154 Preprocessor &PP = P.getPreprocessor();
4155 OpenMPMapClauseKind MapType =
4156 static_cast<OpenMPMapClauseKind>(getOpenMPSimpleClauseType(
4157 OMPC_map, PP.getSpelling(Tok), P.getLangOpts()));
4158 return MapType;
4159}
4160
4161/// Parse map-type in map clause.
4162/// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list)
4163/// where, map-type ::= to | from | tofrom | alloc | release | delete
4164static void parseMapType(Parser &P, Sema::OpenMPVarListDataTy &Data) {
4165 Token Tok = P.getCurToken();
4166 if (Tok.is(tok::colon)) {
4167 P.Diag(Tok, diag::err_omp_map_type_missing);
4168 return;
4169 }
4170 Data.ExtraModifier = isMapType(P);
4171 if (Data.ExtraModifier == OMPC_MAP_unknown)
4172 P.Diag(Tok, diag::err_omp_unknown_map_type);
4173 P.ConsumeToken();
4174}
4175
4176/// Parses simple expression in parens for single-expression clauses of OpenMP
4177/// constructs.
4178ExprResult Parser::ParseOpenMPIteratorsExpr() {
4179 assert(Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator" &&(static_cast <bool> (Tok.is(tok::identifier) &&
PP.getSpelling(Tok) == "iterator" && "Expected 'iterator' token."
) ? void (0) : __assert_fail ("Tok.is(tok::identifier) && PP.getSpelling(Tok) == \"iterator\" && \"Expected 'iterator' token.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 4180, __extension__ __PRETTY_FUNCTION__
))
4180 "Expected 'iterator' token.")(static_cast <bool> (Tok.is(tok::identifier) &&
PP.getSpelling(Tok) == "iterator" && "Expected 'iterator' token."
) ? void (0) : __assert_fail ("Tok.is(tok::identifier) && PP.getSpelling(Tok) == \"iterator\" && \"Expected 'iterator' token.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 4180, __extension__ __PRETTY_FUNCTION__
))
;
4181 SourceLocation IteratorKwLoc = ConsumeToken();
4182
4183 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4184 if (T.expectAndConsume(diag::err_expected_lparen_after, "iterator"))
4185 return ExprError();
4186
4187 SourceLocation LLoc = T.getOpenLocation();
4188 SmallVector<Sema::OMPIteratorData, 4> Data;
4189 while (Tok.isNot(tok::r_paren) && Tok.isNot(tok::annot_pragma_openmp_end)) {
4190 // Check if the type parsing is required.
4191 ParsedType IteratorType;
4192 if (Tok.isNot(tok::identifier) || NextToken().isNot(tok::equal)) {
4193 // identifier '=' is not found - parse type.
4194 TypeResult TR = ParseTypeName();
4195 if (TR.isInvalid()) {
4196 T.skipToEnd();
4197 return ExprError();
4198 }
4199 IteratorType = TR.get();
4200 }
4201
4202 // Parse identifier.
4203 IdentifierInfo *II = nullptr;
4204 SourceLocation IdLoc;
4205 if (Tok.is(tok::identifier)) {
4206 II = Tok.getIdentifierInfo();
4207 IdLoc = ConsumeToken();
4208 } else {
4209 Diag(Tok, diag::err_expected_unqualified_id) << 0;
4210 }
4211
4212 // Parse '='.
4213 SourceLocation AssignLoc;
4214 if (Tok.is(tok::equal))
4215 AssignLoc = ConsumeToken();
4216 else
4217 Diag(Tok, diag::err_omp_expected_equal_in_iterator);
4218
4219 // Parse range-specification - <begin> ':' <end> [ ':' <step> ]
4220 ColonProtectionRAIIObject ColonRAII(*this);
4221 // Parse <begin>
4222 SourceLocation Loc = Tok.getLocation();
4223 ExprResult LHS = ParseCastExpression(AnyCastExpr);
4224 ExprResult Begin = Actions.CorrectDelayedTyposInExpr(
4225 ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4226 Begin = Actions.ActOnFinishFullExpr(Begin.get(), Loc,
4227 /*DiscardedValue=*/false);
4228 // Parse ':'.
4229 SourceLocation ColonLoc;
4230 if (Tok.is(tok::colon))
4231 ColonLoc = ConsumeToken();
4232
4233 // Parse <end>
4234 Loc = Tok.getLocation();
4235 LHS = ParseCastExpression(AnyCastExpr);
4236 ExprResult End = Actions.CorrectDelayedTyposInExpr(
4237 ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4238 End = Actions.ActOnFinishFullExpr(End.get(), Loc,
4239 /*DiscardedValue=*/false);
4240
4241 SourceLocation SecColonLoc;
4242 ExprResult Step;
4243 // Parse optional step.
4244 if (Tok.is(tok::colon)) {
4245 // Parse ':'
4246 SecColonLoc = ConsumeToken();
4247 // Parse <step>
4248 Loc = Tok.getLocation();
4249 LHS = ParseCastExpression(AnyCastExpr);
4250 Step = Actions.CorrectDelayedTyposInExpr(
4251 ParseRHSOfBinaryExpression(LHS, prec::Conditional));
4252 Step = Actions.ActOnFinishFullExpr(Step.get(), Loc,
4253 /*DiscardedValue=*/false);
4254 }
4255
4256 // Parse ',' or ')'
4257 if (Tok.isNot(tok::comma) && Tok.isNot(tok::r_paren))
4258 Diag(Tok, diag::err_omp_expected_punc_after_iterator);
4259 if (Tok.is(tok::comma))
4260 ConsumeToken();
4261
4262 Sema::OMPIteratorData &D = Data.emplace_back();
4263 D.DeclIdent = II;
4264 D.DeclIdentLoc = IdLoc;
4265 D.Type = IteratorType;
4266 D.AssignLoc = AssignLoc;
4267 D.ColonLoc = ColonLoc;
4268 D.SecColonLoc = SecColonLoc;
4269 D.Range.Begin = Begin.get();
4270 D.Range.End = End.get();
4271 D.Range.Step = Step.get();
4272 }
4273
4274 // Parse ')'.
4275 SourceLocation RLoc = Tok.getLocation();
4276 if (!T.consumeClose())
4277 RLoc = T.getCloseLocation();
4278
4279 return Actions.ActOnOMPIteratorExpr(getCurScope(), IteratorKwLoc, LLoc, RLoc,
4280 Data);
4281}
4282
4283bool Parser::ParseOpenMPReservedLocator(OpenMPClauseKind Kind,
4284 Sema::OpenMPVarListDataTy &Data,
4285 const LangOptions &LangOpts) {
4286 // Currently the only reserved locator is 'omp_all_memory' which is only
4287 // allowed on a depend clause.
4288 if (Kind != OMPC_depend || LangOpts.OpenMP < 51)
4289 return false;
4290
4291 if (Tok.is(tok::identifier) &&
4292 Tok.getIdentifierInfo()->isStr("omp_all_memory")) {
4293
4294 if (Data.ExtraModifier == OMPC_DEPEND_outallmemory ||
4295 Data.ExtraModifier == OMPC_DEPEND_inoutallmemory)
4296 Diag(Tok, diag::warn_omp_more_one_omp_all_memory);
4297 else if (Data.ExtraModifier != OMPC_DEPEND_out &&
4298 Data.ExtraModifier != OMPC_DEPEND_inout)
4299 Diag(Tok, diag::err_omp_requires_out_inout_depend_type);
4300 else
4301 Data.ExtraModifier = Data.ExtraModifier == OMPC_DEPEND_out
4302 ? OMPC_DEPEND_outallmemory
4303 : OMPC_DEPEND_inoutallmemory;
4304 ConsumeToken();
4305 return true;
4306 }
4307 return false;
4308}
4309
4310/// Parses clauses with list.
4311bool Parser::ParseOpenMPVarList(OpenMPDirectiveKind DKind,
4312 OpenMPClauseKind Kind,
4313 SmallVectorImpl<Expr *> &Vars,
4314 Sema::OpenMPVarListDataTy &Data) {
4315 UnqualifiedId UnqualifiedReductionId;
4316 bool InvalidReductionId = false;
4317 bool IsInvalidMapperModifier = false;
4318
4319 // Parse '('.
4320 BalancedDelimiterTracker T(*this, tok::l_paren, tok::annot_pragma_openmp_end);
4321 if (T.expectAndConsume(diag::err_expected_lparen_after,
4322 getOpenMPClauseName(Kind).data()))
4323 return true;
4324
4325 bool HasIterator = false;
4326 bool InvalidIterator = false;
4327 bool NeedRParenForLinear = false;
4328 BalancedDelimiterTracker LinearT(*this, tok::l_paren,
4329 tok::annot_pragma_openmp_end);
4330 // Handle reduction-identifier for reduction clause.
4331 if (Kind == OMPC_reduction || Kind == OMPC_task_reduction ||
4332 Kind == OMPC_in_reduction) {
4333 Data.ExtraModifier = OMPC_REDUCTION_unknown;
4334 if (Kind == OMPC_reduction && getLangOpts().OpenMP >= 50 &&
4335 (Tok.is(tok::identifier) || Tok.is(tok::kw_default)) &&
4336 NextToken().is(tok::comma)) {
4337 // Parse optional reduction modifier.
4338 Data.ExtraModifier =
4339 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4340 Data.ExtraModifierLoc = Tok.getLocation();
4341 ConsumeToken();
4342 assert(Tok.is(tok::comma) && "Expected comma.")(static_cast <bool> (Tok.is(tok::comma) && "Expected comma."
) ? void (0) : __assert_fail ("Tok.is(tok::comma) && \"Expected comma.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 4342, __extension__ __PRETTY_FUNCTION__
))
;
4343 (void)ConsumeToken();
4344 }
4345 ColonProtectionRAIIObject ColonRAII(*this);
4346 if (getLangOpts().CPlusPlus)
4347 ParseOptionalCXXScopeSpecifier(Data.ReductionOrMapperIdScopeSpec,
4348 /*ObjectType=*/nullptr,
4349 /*ObjectHasErrors=*/false,
4350 /*EnteringContext=*/false);
4351 InvalidReductionId = ParseReductionId(
4352 *this, Data.ReductionOrMapperIdScopeSpec, UnqualifiedReductionId);
4353 if (InvalidReductionId) {
4354 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4355 StopBeforeMatch);
4356 }
4357 if (Tok.is(tok::colon))
4358 Data.ColonLoc = ConsumeToken();
4359 else
4360 Diag(Tok, diag::warn_pragma_expected_colon) << "reduction identifier";
4361 if (!InvalidReductionId)
4362 Data.ReductionOrMapperId =
4363 Actions.GetNameFromUnqualifiedId(UnqualifiedReductionId);
4364 } else if (Kind == OMPC_depend) {
4365 if (getLangOpts().OpenMP >= 50) {
4366 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
4367 // Handle optional dependence modifier.
4368 // iterator(iterators-definition)
4369 // where iterators-definition is iterator-specifier [,
4370 // iterators-definition ]
4371 // where iterator-specifier is [ iterator-type ] identifier =
4372 // range-specification
4373 HasIterator = true;
4374 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4375 ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
4376 Data.DepModOrTailExpr = IteratorRes.get();
4377 // Parse ','
4378 ExpectAndConsume(tok::comma);
4379 }
4380 }
4381 // Handle dependency type for depend clause.
4382 ColonProtectionRAIIObject ColonRAII(*this);
4383 Data.ExtraModifier = getOpenMPSimpleClauseType(
4384 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
4385 getLangOpts());
4386 Data.ExtraModifierLoc = Tok.getLocation();
4387 if (Data.ExtraModifier == OMPC_DEPEND_unknown) {
4388 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4389 StopBeforeMatch);
4390 } else {
4391 ConsumeToken();
4392 // Special processing for depend(source) clause.
4393 if (DKind == OMPD_ordered && Data.ExtraModifier == OMPC_DEPEND_source) {
4394 // Parse ')'.
4395 T.consumeClose();
4396 return false;
4397 }
4398 }
4399 if (Tok.is(tok::colon)) {
4400 Data.ColonLoc = ConsumeToken();
4401 } else {
4402 Diag(Tok, DKind == OMPD_ordered ? diag::warn_pragma_expected_colon_r_paren
4403 : diag::warn_pragma_expected_colon)
4404 << "dependency type";
4405 }
4406 } else if (Kind == OMPC_linear) {
4407 // Try to parse modifier if any.
4408 Data.ExtraModifier = OMPC_LINEAR_val;
4409 if (Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::l_paren)) {
4410 Data.ExtraModifier =
4411 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4412 Data.ExtraModifierLoc = ConsumeToken();
4413 LinearT.consumeOpen();
4414 NeedRParenForLinear = true;
4415 }
4416 } else if (Kind == OMPC_lastprivate) {
4417 // Try to parse modifier if any.
4418 Data.ExtraModifier = OMPC_LASTPRIVATE_unknown;
4419 // Conditional modifier allowed only in OpenMP 5.0 and not supported in
4420 // distribute and taskloop based directives.
4421 if ((getLangOpts().OpenMP >= 50 && !isOpenMPDistributeDirective(DKind) &&
4422 !isOpenMPTaskLoopDirective(DKind)) &&
4423 Tok.is(tok::identifier) && PP.LookAhead(0).is(tok::colon)) {
4424 Data.ExtraModifier =
4425 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts());
4426 Data.ExtraModifierLoc = Tok.getLocation();
4427 ConsumeToken();
4428 assert(Tok.is(tok::colon) && "Expected colon.")(static_cast <bool> (Tok.is(tok::colon) && "Expected colon."
) ? void (0) : __assert_fail ("Tok.is(tok::colon) && \"Expected colon.\""
, "clang/lib/Parse/ParseOpenMP.cpp", 4428, __extension__ __PRETTY_FUNCTION__
))
;
4429 Data.ColonLoc = ConsumeToken();
4430 }
4431 } else if (Kind == OMPC_map) {
4432 // Handle optional iterator map modifier.
4433 if (Tok.is(tok::identifier) && PP.getSpelling(Tok) == "iterator") {
4434 HasIterator = true;
4435 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4436 Data.MapTypeModifiers.push_back(OMPC_MAP_MODIFIER_iterator);
4437 Data.MapTypeModifiersLoc.push_back(Tok.getLocation());
4438 ExprResult IteratorRes = ParseOpenMPIteratorsExpr();
4439 Data.IteratorExpr = IteratorRes.get();
4440 // Parse ','
4441 ExpectAndConsume(tok::comma);
4442 if (getLangOpts().OpenMP < 52) {
4443 Diag(Tok, diag::err_omp_unknown_map_type_modifier)
4444 << (getLangOpts().OpenMP >= 51 ? 1 : 0)
4445 << getLangOpts().OpenMPExtensions;
4446 InvalidIterator = true;
4447 }
4448 }
4449 // Handle map type for map clause.
4450 ColonProtectionRAIIObject ColonRAII(*this);
4451
4452 // The first identifier may be a list item, a map-type or a
4453 // map-type-modifier. The map-type can also be delete which has the same
4454 // spelling of the C++ delete keyword.
4455 Data.ExtraModifier = OMPC_MAP_unknown;
4456 Data.ExtraModifierLoc = Tok.getLocation();
4457
4458 // Check for presence of a colon in the map clause.
4459 TentativeParsingAction TPA(*this);
4460 bool ColonPresent = false;
4461 if (SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4462 StopBeforeMatch)) {
4463 if (Tok.is(tok::colon))
4464 ColonPresent = true;
4465 }
4466 TPA.Revert();
4467 // Only parse map-type-modifier[s] and map-type if a colon is present in
4468 // the map clause.
4469 if (ColonPresent) {
4470 IsInvalidMapperModifier = parseMapTypeModifiers(Data);
4471 if (!IsInvalidMapperModifier)
4472 parseMapType(*this, Data);
4473 else
4474 SkipUntil(tok::colon, tok::annot_pragma_openmp_end, StopBeforeMatch);
4475 }
4476 if (Data.ExtraModifier == OMPC_MAP_unknown) {
4477 Data.ExtraModifier = OMPC_MAP_tofrom;
4478 if (getLangOpts().OpenMP >= 52) {
4479 if (DKind == OMPD_target_enter_data)
4480 Data.ExtraModifier = OMPC_MAP_to;
4481 else if (DKind == OMPD_target_exit_data)
4482 Data.ExtraModifier = OMPC_MAP_from;
4483 }
4484 Data.IsMapTypeImplicit = true;
4485 }
4486
4487 if (Tok.is(tok::colon))
4488 Data.ColonLoc = ConsumeToken();
4489 } else if (Kind == OMPC_to || Kind == OMPC_from) {
4490 while (Tok.is(tok::identifier)) {
4491 auto Modifier = static_cast<OpenMPMotionModifierKind>(
4492 getOpenMPSimpleClauseType(Kind, PP.getSpelling(Tok), getLangOpts()));
4493 if (Modifier == OMPC_MOTION_MODIFIER_unknown)
4494 break;
4495 Data.MotionModifiers.push_back(Modifier);
4496 Data.MotionModifiersLoc.push_back(Tok.getLocation());
4497 ConsumeToken();
4498 if (Modifier == OMPC_MOTION_MODIFIER_mapper) {
4499 IsInvalidMapperModifier = parseMapperModifier(Data);
4500 if (IsInvalidMapperModifier)
4501 break;
4502 }
4503 // OpenMP < 5.1 doesn't permit a ',' or additional modifiers.
4504 if (getLangOpts().OpenMP < 51)
4505 break;
4506 // OpenMP 5.1 accepts an optional ',' even if the next character is ':'.
4507 // TODO: Is that intentional?
4508 if (Tok.is(tok::comma))
4509 ConsumeToken();
4510 }
4511 if (!Data.MotionModifiers.empty() && Tok.isNot(tok::colon)) {
4512 if (!IsInvalidMapperModifier) {
4513 if (getLangOpts().OpenMP < 51)
4514 Diag(Tok, diag::warn_pragma_expected_colon) << ")";
4515 else
4516 Diag(Tok, diag::warn_pragma_expected_colon) << "motion modifier";
4517 }
4518 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4519 StopBeforeMatch);
4520 }
4521 // OpenMP 5.1 permits a ':' even without a preceding modifier. TODO: Is
4522 // that intentional?
4523 if ((!Data.MotionModifiers.empty() || getLangOpts().OpenMP >= 51) &&
4524 Tok.is(tok::colon))
4525 Data.ColonLoc = ConsumeToken();
4526 } else if (Kind == OMPC_allocate ||
4527 (Kind == OMPC_affinity && Tok.is(tok::identifier) &&
4528 PP.getSpelling(Tok) == "iterator")) {
4529 // Handle optional allocator expression followed by colon delimiter.
4530 ColonProtectionRAIIObject ColonRAII(*this);
4531 TentativeParsingAction TPA(*this);
4532 // OpenMP 5.0, 2.10.1, task Construct.
4533 // where aff-modifier is one of the following:
4534 // iterator(iterators-definition)
4535 ExprResult Tail;
4536 if (Kind == OMPC_allocate) {
4537 Tail = ParseAssignmentExpression();
4538 } else {
4539 HasIterator = true;
4540 EnterScope(Scope::OpenMPDirectiveScope | Scope::DeclScope);
4541 Tail = ParseOpenMPIteratorsExpr();
4542 }
4543 Tail = Actions.CorrectDelayedTyposInExpr(Tail);
4544 Tail = Actions.ActOnFinishFullExpr(Tail.get(), T.getOpenLocation(),
4545 /*DiscardedValue=*/false);
4546 if (Tail.isUsable()) {
4547 if (Tok.is(tok::colon)) {
4548 Data.DepModOrTailExpr = Tail.get();
4549 Data.ColonLoc = ConsumeToken();
4550 TPA.Commit();
4551 } else {
4552 // Colon not found, parse only list of variables.
4553 TPA.Revert();
4554 }
4555 } else {
4556 // Parsing was unsuccessfull, revert and skip to the end of clause or
4557 // directive.
4558 TPA.Revert();
4559 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4560 StopBeforeMatch);
4561 }
4562 } else if (Kind == OMPC_adjust_args) {
4563 // Handle adjust-op for adjust_args clause.
4564 ColonProtectionRAIIObject ColonRAII(*this);
4565 Data.ExtraModifier = getOpenMPSimpleClauseType(
4566 Kind, Tok.is(tok::identifier) ? PP.getSpelling(Tok) : "",
4567 getLangOpts());
4568 Data.ExtraModifierLoc = Tok.getLocation();
4569 if (Data.ExtraModifier == OMPC_ADJUST_ARGS_unknown) {
4570 SkipUntil(tok::colon, tok::r_paren, tok::annot_pragma_openmp_end,
4571 StopBeforeMatch);
4572 } else {
4573 ConsumeToken();
4574 if (Tok.is(tok::colon))
4575 Data.ColonLoc = Tok.getLocation();
4576 ExpectAndConsume(tok::colon, diag::warn_pragma_expected_colon,
4577 "adjust-op");
4578 }
4579 }
4580
4581 bool IsComma =
4582 (Kind != OMPC_reduction && Kind != OMPC_task_reduction &&
4583 Kind != OMPC_in_reduction && Kind != OMPC_depend && Kind != OMPC_map) ||
4584 (Kind == OMPC_reduction && !InvalidReductionId) ||
4585 (Kind == OMPC_map && Data.ExtraModifier != OMPC_MAP_unknown) ||
4586 (Kind == OMPC_depend && Data.ExtraModifier != OMPC_DEPEND_unknown) ||
4587 (Kind == OMPC_adjust_args &&
4588 Data.ExtraModifier != OMPC_ADJUST_ARGS_unknown);
4589 const bool MayHaveTail = (Kind == OMPC_linear || Kind == OMPC_aligned);
4590 while (IsComma || (Tok.isNot(tok::r_paren) && Tok.isNot(tok::colon) &&
4591 Tok.isNot(tok::annot_pragma_openmp_end))) {
4592 ParseScope OMPListScope(this, Scope::OpenMPDirectiveScope);
4593 ColonProtectionRAIIObject ColonRAII(*this, MayHaveTail);
4594 if (!ParseOpenMPReservedLocator(Kind, Data, getLangOpts())) {
4595 // Parse variable
4596 ExprResult VarExpr =
4597 Actions.CorrectDelayedTyposInExpr(ParseAssignmentExpression());
4598 if (VarExpr.isUsable()) {
4599 Vars.push_back(VarExpr.get());
4600 } else {
4601 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4602 StopBeforeMatch);
4603 }
4604 }
4605 // Skip ',' if any
4606 IsComma = Tok.is(tok::comma);
4607 if (IsComma)
4608 ConsumeToken();
4609 else if (Tok.isNot(tok::r_paren) &&
4610 Tok.isNot(tok::annot_pragma_openmp_end) &&
4611 (!MayHaveTail || Tok.isNot(tok::colon)))
4612 Diag(Tok, diag::err_omp_expected_punc)
4613 << ((Kind == OMPC_flush) ? getOpenMPDirectiveName(OMPD_flush)
4614 : getOpenMPClauseName(Kind))
4615 << (Kind == OMPC_flush);
4616 }
4617
4618 // Parse ')' for linear clause with modifier.
4619 if (NeedRParenForLinear)
4620 LinearT.consumeClose();
4621
4622 // Parse ':' linear-step (or ':' alignment).
4623 const bool MustHaveTail = MayHaveTail && Tok.is(tok::colon);
4624 if (MustHaveTail) {
4625 Data.ColonLoc = Tok.getLocation();
4626 SourceLocation ELoc = ConsumeToken();
4627 ExprResult Tail = ParseAssignmentExpression();
4628 Tail =
4629 Actions.ActOnFinishFullExpr(Tail.get(), ELoc, /*DiscardedValue*/ false);
4630 if (Tail.isUsable())
4631 Data.DepModOrTailExpr = Tail.get();
4632 else
4633 SkipUntil(tok::comma, tok::r_paren, tok::annot_pragma_openmp_end,
4634 StopBeforeMatch);
4635 }
4636
4637 // Parse ')'.
4638 Data.RLoc = Tok.getLocation();
4639 if (!T.consumeClose())
4640 Data.RLoc = T.getCloseLocation();
4641 // Exit from scope when the iterator is used in depend clause.
4642 if (HasIterator)
4643 ExitScope();
4644 return (Kind != OMPC_depend && Kind != OMPC_map && Vars.empty()) ||
4645 (MustHaveTail && !Data.DepModOrTailExpr) || InvalidReductionId ||
4646 IsInvalidMapperModifier || InvalidIterator;
4647}
4648
4649/// Parsing of OpenMP clause 'private', 'firstprivate', 'lastprivate',
4650/// 'shared', 'copyin', 'copyprivate', 'flush', 'reduction', 'task_reduction',
4651/// 'in_reduction', 'nontemporal', 'exclusive' or 'inclusive'.
4652///
4653/// private-clause:
4654/// 'private' '(' list ')'
4655/// firstprivate-clause:
4656/// 'firstprivate' '(' list ')'
4657/// lastprivate-clause:
4658/// 'lastprivate' '(' list ')'
4659/// shared-clause:
4660/// 'shared' '(' list ')'
4661/// linear-clause:
4662/// 'linear' '(' linear-list [ ':' linear-step ] ')'
4663/// aligned-clause:
4664/// 'aligned' '(' list [ ':' alignment ] ')'
4665/// reduction-clause:
4666/// 'reduction' '(' [ modifier ',' ] reduction-identifier ':' list ')'
4667/// task_reduction-clause:
4668/// 'task_reduction' '(' reduction-identifier ':' list ')'
4669/// in_reduction-clause:
4670/// 'in_reduction' '(' reduction-identifier ':' list ')'
4671/// copyprivate-clause:
4672/// 'copyprivate' '(' list ')'
4673/// flush-clause:
4674/// 'flush' '(' list ')'
4675/// depend-clause:
4676/// 'depend' '(' in | out | inout : list | source ')'
4677/// map-clause:
4678/// 'map' '(' [ [ always [,] ] [ close [,] ]
4679/// [ mapper '(' mapper-identifier ')' [,] ]
4680/// to | from | tofrom | alloc | release | delete ':' ] list ')';
4681/// to-clause:
4682/// 'to' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
4683/// from-clause:
4684/// 'from' '(' [ mapper '(' mapper-identifier ')' ':' ] list ')'
4685/// use_device_ptr-clause:
4686/// 'use_device_ptr' '(' list ')'
4687/// use_device_addr-clause:
4688/// 'use_device_addr' '(' list ')'
4689/// is_device_ptr-clause:
4690/// 'is_device_ptr' '(' list ')'
4691/// has_device_addr-clause:
4692/// 'has_device_addr' '(' list ')'
4693/// allocate-clause:
4694/// 'allocate' '(' [ allocator ':' ] list ')'
4695/// nontemporal-clause:
4696/// 'nontemporal' '(' list ')'
4697/// inclusive-clause:
4698/// 'inclusive' '(' list ')'
4699/// exclusive-clause:
4700/// 'exclusive' '(' list ')'
4701///
4702/// For 'linear' clause linear-list may have the following forms:
4703/// list
4704/// modifier(list)
4705/// where modifier is 'val' (C) or 'ref', 'val' or 'uval'(C++).
4706OMPClause *Parser::ParseOpenMPVarListClause(OpenMPDirectiveKind DKind,
4707 OpenMPClauseKind Kind,
4708 bool ParseOnly) {
4709 SourceLocation Loc = Tok.getLocation();
4710 SourceLocation LOpen = ConsumeToken();
4711 SmallVector<Expr *, 4> Vars;
4712 Sema::OpenMPVarListDataTy Data;
4713
4714 if (ParseOpenMPVarList(DKind, Kind, Vars, Data))
4715 return nullptr;
4716
4717 if (ParseOnly)
4718 return nullptr;
4719 OMPVarListLocTy Locs(Loc, LOpen, Data.RLoc);
4720 return Actions.ActOnOpenMPVarListClause(Kind, Vars, Locs, Data);
4721}