Bug Summary

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