clang 24.0.0git
SemaOpenACC.cpp
Go to the documentation of this file.
1//===--- SemaOpenACC.cpp - Semantic Analysis for OpenACC constructs -------===//
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 semantic analysis for OpenACC constructs, and things
10/// that are not clause specific.
11///
12//===----------------------------------------------------------------------===//
13
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/Sema.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/Casting.h"
26
27using namespace clang;
28
29namespace {
30bool diagnoseConstructAppertainment(SemaOpenACC &S, OpenACCDirectiveKind K,
31 SourceLocation StartLoc, bool IsStmt) {
32 switch (K) {
33 default:
35 // Nothing to do here, both invalid and unimplemented don't really need to
36 // do anything.
37 break;
55 if (!IsStmt)
56 return S.Diag(StartLoc, diag::err_acc_construct_appertainment) << K;
57 break;
58 }
59 return false;
60}
61
62void CollectActiveReductionClauses(
64 ArrayRef<OpenACCClause *> CurClauses) {
65 for (auto *CurClause : CurClauses) {
66 if (auto *RedClause = dyn_cast<OpenACCReductionClause>(CurClause);
67 RedClause && !RedClause->getVarList().empty())
68 ActiveClauses.push_back(RedClause);
69 }
70}
71
72// Depth needs to be preserved for all associated statements that aren't
73// supposed to modify the compute/combined/loop construct information.
74bool PreserveLoopRAIIDepthInAssociatedStmtRAII(OpenACCDirectiveKind DK) {
75 switch (DK) {
83 return false;
87 return true;
98 llvm_unreachable("Doesn't have an associated stmt");
100 llvm_unreachable("Unhandled directive kind?");
101 }
102 llvm_unreachable("Unhandled directive kind?");
103}
104
105} // namespace
106
108
113 : SemaRef(S), OldActiveComputeConstructInfo(S.ActiveComputeConstructInfo),
114 DirKind(DK), OldLoopGangClauseOnKernel(S.LoopGangClauseOnKernel),
115 OldLoopWorkerClauseLoc(S.LoopWorkerClauseLoc),
116 OldLoopVectorClauseLoc(S.LoopVectorClauseLoc),
117 OldLoopWithoutSeqInfo(S.LoopWithoutSeqInfo),
118 ActiveReductionClauses(S.ActiveReductionClauses),
119 LoopRAII(SemaRef, PreserveLoopRAIIDepthInAssociatedStmtRAII(DirKind)) {
120
121 // Compute constructs end up taking their 'loop'.
122 if (DirKind == OpenACCDirectiveKind::Parallel ||
123 DirKind == OpenACCDirectiveKind::Serial ||
125 CollectActiveReductionClauses(S.ActiveReductionClauses, Clauses);
126 SemaRef.ActiveComputeConstructInfo.Kind = DirKind;
127 SemaRef.ActiveComputeConstructInfo.Clauses = Clauses;
128
129 // OpenACC 3.3 2.9.2: When the parent compute construct is a kernels
130 // construct, the gang clause behaves as follows. ... The region of a loop
131 // with a gang clause may not contain another loop with a gang clause unless
132 // within a nested compute region.
133 //
134 // Implement the 'unless within a nested compute region' part.
135 SemaRef.LoopGangClauseOnKernel = {};
136 SemaRef.LoopWorkerClauseLoc = {};
137 SemaRef.LoopVectorClauseLoc = {};
138 SemaRef.LoopWithoutSeqInfo = {};
139 } else if (DirKind == OpenACCDirectiveKind::ParallelLoop ||
142 SemaRef.ActiveComputeConstructInfo.Kind = DirKind;
143 SemaRef.ActiveComputeConstructInfo.Clauses = Clauses;
144
145 CollectActiveReductionClauses(S.ActiveReductionClauses, Clauses);
146 SetCollapseInfoBeforeAssociatedStmt(UnInstClauses, Clauses);
147 SetTileInfoBeforeAssociatedStmt(UnInstClauses, Clauses);
148
149 SemaRef.LoopGangClauseOnKernel = {};
150 SemaRef.LoopWorkerClauseLoc = {};
151 SemaRef.LoopVectorClauseLoc = {};
152
153 // Set the active 'loop' location if there isn't a 'seq' on it, so we can
154 // diagnose the for loops.
155 SemaRef.LoopWithoutSeqInfo = {};
156 if (Clauses.end() ==
157 llvm::find_if(Clauses, llvm::IsaPred<OpenACCSeqClause>))
158 SemaRef.LoopWithoutSeqInfo = {DirKind, DirLoc};
159
160 // OpenACC 3.3 2.9.2: When the parent compute construct is a kernels
161 // construct, the gang clause behaves as follows. ... The region of a loop
162 // with a gang clause may not contain another loop with a gang clause unless
163 // within a nested compute region.
164 //
165 // We don't bother doing this when this is a template instantiation, as
166 // there is no reason to do these checks: the existance of a
167 // gang/kernels/etc cannot be dependent.
168 if (DirKind == OpenACCDirectiveKind::KernelsLoop && UnInstClauses.empty()) {
169 // This handles the 'outer loop' part of this.
170 auto *Itr = llvm::find_if(Clauses, llvm::IsaPred<OpenACCGangClause>);
171 if (Itr != Clauses.end())
172 SemaRef.LoopGangClauseOnKernel = {(*Itr)->getBeginLoc(), DirKind};
173 }
174
175 if (UnInstClauses.empty()) {
176 auto *Itr = llvm::find_if(Clauses, llvm::IsaPred<OpenACCWorkerClause>);
177 if (Itr != Clauses.end())
178 SemaRef.LoopWorkerClauseLoc = (*Itr)->getBeginLoc();
179
180 auto *Itr2 = llvm::find_if(Clauses, llvm::IsaPred<OpenACCVectorClause>);
181 if (Itr2 != Clauses.end())
182 SemaRef.LoopVectorClauseLoc = (*Itr2)->getBeginLoc();
183 }
184 } else if (DirKind == OpenACCDirectiveKind::Loop) {
185 CollectActiveReductionClauses(S.ActiveReductionClauses, Clauses);
186 SetCollapseInfoBeforeAssociatedStmt(UnInstClauses, Clauses);
187 SetTileInfoBeforeAssociatedStmt(UnInstClauses, Clauses);
188
189 // Set the active 'loop' location if there isn't a 'seq' on it, so we can
190 // diagnose the for loops.
191 SemaRef.LoopWithoutSeqInfo = {};
192 if (Clauses.end() ==
193 llvm::find_if(Clauses, llvm::IsaPred<OpenACCSeqClause>))
194 SemaRef.LoopWithoutSeqInfo = {DirKind, DirLoc};
195
196 // OpenACC 3.3 2.9.2: When the parent compute construct is a kernels
197 // construct, the gang clause behaves as follows. ... The region of a loop
198 // with a gang clause may not contain another loop with a gang clause unless
199 // within a nested compute region.
200 //
201 // We don't bother doing this when this is a template instantiation, as
202 // there is no reason to do these checks: the existance of a
203 // gang/kernels/etc cannot be dependent.
204 if (SemaRef.getActiveComputeConstructInfo().Kind ==
206 UnInstClauses.empty()) {
207 // This handles the 'outer loop' part of this.
208 auto *Itr = llvm::find_if(Clauses, llvm::IsaPred<OpenACCGangClause>);
209 if (Itr != Clauses.end())
210 SemaRef.LoopGangClauseOnKernel = {(*Itr)->getBeginLoc(),
212 }
213
214 if (UnInstClauses.empty()) {
215 auto *Itr = llvm::find_if(Clauses, llvm::IsaPred<OpenACCWorkerClause>);
216 if (Itr != Clauses.end())
217 SemaRef.LoopWorkerClauseLoc = (*Itr)->getBeginLoc();
218
219 auto *Itr2 = llvm::find_if(Clauses, llvm::IsaPred<OpenACCVectorClause>);
220 if (Itr2 != Clauses.end())
221 SemaRef.LoopVectorClauseLoc = (*Itr2)->getBeginLoc();
222 }
223 }
224}
225
226namespace {
227// Given two collapse clauses, and the uninstanted version of the new one,
228// return the 'best' one for the purposes of setting the collapse checking
229// values.
231getBestCollapseCandidate(const OpenACCCollapseClause *Old,
233 const OpenACCCollapseClause *UnInstNew) {
234 // If the loop count is nullptr, it is because instantiation failed, so this
235 // can't be the best one.
236 if (!New->getLoopCount())
237 return Old;
238
239 // If the loop-count had an error, than 'new' isn't a candidate.
240 if (!New->getLoopCount())
241 return Old;
242
243 // Don't consider uninstantiated ones, since we can't really check these.
244 if (New->getLoopCount()->isInstantiationDependent())
245 return Old;
246
247 // If this is an instantiation, and the old version wasn't instantation
248 // dependent, than nothing has changed and we've already done a diagnostic
249 // based on this one, so don't consider it.
250 if (UnInstNew && !UnInstNew->getLoopCount()->isInstantiationDependent())
251 return Old;
252
253 // New is now a valid candidate, so if there isn't an old one at this point,
254 // New is the only valid one.
255 if (!Old)
256 return New;
257
258 // If the 'New' expression has a larger value than 'Old', then it is the new
259 // best candidate.
260 if (cast<ConstantExpr>(Old->getLoopCount())->getResultAsAPSInt() <
261 cast<ConstantExpr>(New->getLoopCount())->getResultAsAPSInt())
262 return New;
263
264 return Old;
265}
266} // namespace
267
271
272 // Reset this checking for loops that aren't covered in a RAII object.
273 SemaRef.LoopInfo.CurLevelHasLoopAlready = false;
274 SemaRef.CollapseInfo.CollapseDepthSatisfied = true;
275 SemaRef.CollapseInfo.CurCollapseCount = 0;
276 SemaRef.TileInfo.TileDepthSatisfied = true;
277
278 // We make sure to take an optional list of uninstantiated clauses, so that
279 // we can check to make sure we don't 'double diagnose' in the event that
280 // the value of 'N' was not dependent in a template. Since we cannot count on
281 // there only being a single collapse clause, we count on the order to make
282 // sure get the matching ones, and we count on TreeTransform not removing
283 // these, even if loop-count instantiation failed. We can check the
284 // non-dependent ones right away, and realize that subsequent instantiation
285 // can only make it more specific.
286
287 auto *UnInstClauseItr =
288 llvm::find_if(UnInstClauses, llvm::IsaPred<OpenACCCollapseClause>);
289 auto *ClauseItr =
290 llvm::find_if(Clauses, llvm::IsaPred<OpenACCCollapseClause>);
291 const OpenACCCollapseClause *FoundClause = nullptr;
292
293 // Loop through the list of Collapse clauses and find the one that:
294 // 1- Has a non-dependent, non-null loop count (null means error, likely
295 // during instantiation).
296 // 2- If UnInstClauses isn't empty, its corresponding
297 // loop count was dependent.
298 // 3- Has the largest 'loop count' of all.
299 while (ClauseItr != Clauses.end()) {
300 const OpenACCCollapseClause *CurClause =
301 cast<OpenACCCollapseClause>(*ClauseItr);
302 const OpenACCCollapseClause *UnInstCurClause =
303 UnInstClauseItr == UnInstClauses.end()
304 ? nullptr
305 : cast<OpenACCCollapseClause>(*UnInstClauseItr);
306
307 FoundClause =
308 getBestCollapseCandidate(FoundClause, CurClause, UnInstCurClause);
309
310 UnInstClauseItr =
311 UnInstClauseItr == UnInstClauses.end()
312 ? UnInstClauseItr
313 : std::find_if(std::next(UnInstClauseItr), UnInstClauses.end(),
314 llvm::IsaPred<OpenACCCollapseClause>);
315 ClauseItr = std::find_if(std::next(ClauseItr), Clauses.end(),
316 llvm::IsaPred<OpenACCCollapseClause>);
317 }
318
319 if (!FoundClause)
320 return;
321
322 SemaRef.CollapseInfo.ActiveCollapse = FoundClause;
323 SemaRef.CollapseInfo.CollapseDepthSatisfied = false;
324 SemaRef.CollapseInfo.CurCollapseCount =
325 cast<ConstantExpr>(FoundClause->getLoopCount())->getResultAsAPSInt();
326 SemaRef.CollapseInfo.DirectiveKind = DirKind;
327}
328
332 // We don't diagnose if this is during instantiation, since the only thing we
333 // care about is the number of arguments, which we can figure out without
334 // instantiation, so we don't want to double-diagnose.
335 if (UnInstClauses.size() > 0)
336 return;
337 auto *TileClauseItr =
338 llvm::find_if(Clauses, llvm::IsaPred<OpenACCTileClause>);
339
340 if (Clauses.end() == TileClauseItr)
341 return;
342
343 OpenACCTileClause *TileClause = cast<OpenACCTileClause>(*TileClauseItr);
344
345 // Multiple tile clauses are allowed, so ensure that we use the one with the
346 // largest 'tile count'.
347 while (Clauses.end() !=
348 (TileClauseItr = std::find_if(std::next(TileClauseItr), Clauses.end(),
349 llvm::IsaPred<OpenACCTileClause>))) {
350 OpenACCTileClause *NewClause = cast<OpenACCTileClause>(*TileClauseItr);
351 if (NewClause->getSizeExprs().size() > TileClause->getSizeExprs().size())
352 TileClause = NewClause;
353 }
354
355 SemaRef.TileInfo.ActiveTile = TileClause;
356 SemaRef.TileInfo.TileDepthSatisfied = false;
357 SemaRef.TileInfo.CurTileCount =
358 static_cast<unsigned>(TileClause->getSizeExprs().size());
359 SemaRef.TileInfo.DirectiveKind = DirKind;
360}
361
363 if (DirKind == OpenACCDirectiveKind::Parallel ||
364 DirKind == OpenACCDirectiveKind::Serial ||
366 DirKind == OpenACCDirectiveKind::Loop ||
370 SemaRef.ActiveComputeConstructInfo = OldActiveComputeConstructInfo;
371 SemaRef.LoopGangClauseOnKernel = OldLoopGangClauseOnKernel;
372 SemaRef.LoopWorkerClauseLoc = OldLoopWorkerClauseLoc;
373 SemaRef.LoopVectorClauseLoc = OldLoopVectorClauseLoc;
374 SemaRef.LoopWithoutSeqInfo = OldLoopWithoutSeqInfo;
375 SemaRef.ActiveReductionClauses.swap(ActiveReductionClauses);
376 } else if (DirKind == OpenACCDirectiveKind::Data ||
378 // Intentionally doesn't reset the Loop, Compute Construct, or reduction
379 // effects.
380 }
381}
382
384 SourceLocation DirLoc) {
385 // Start an evaluation context to parse the clause arguments on.
386 SemaRef.PushExpressionEvaluationContext(
388
389 // There is nothing do do here as all we have at this point is the name of the
390 // construct itself.
391}
392
395 Expr *IntExpr) {
396
397 assert(((DK != OpenACCDirectiveKind::Invalid &&
403 "Only one of directive or clause kind should be provided");
404
405 class IntExprConverter : public Sema::ICEConvertDiagnoser {
406 OpenACCDirectiveKind DirectiveKind;
407 OpenACCClauseKind ClauseKind;
408 Expr *IntExpr;
409
410 // gets the index into the diagnostics so we can use this for clauses,
411 // directives, and sub array.s
412 unsigned getDiagKind() const {
413 if (ClauseKind != OpenACCClauseKind::Invalid)
414 return 0;
415 if (DirectiveKind != OpenACCDirectiveKind::Invalid)
416 return 1;
417 return 2;
418 }
419
420 public:
421 IntExprConverter(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
422 Expr *IntExpr)
423 : ICEConvertDiagnoser(/*AllowScopedEnumerations=*/false,
424 /*Suppress=*/false,
425 /*SuppressConversion=*/true),
426 DirectiveKind(DK), ClauseKind(CK), IntExpr(IntExpr) {}
427
428 bool match(QualType T) override {
429 // OpenACC spec just calls this 'integer expression' as having an
430 // 'integer type', so fall back on C99's 'integer type'.
431 return T->isIntegerType();
432 }
434 QualType T) override {
435 return S.Diag(Loc, diag::err_acc_int_expr_requires_integer)
436 << getDiagKind() << ClauseKind << DirectiveKind << T;
437 }
438
440 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override {
441 return S.Diag(Loc, diag::err_acc_int_expr_incomplete_class_type)
442 << T << IntExpr->getSourceRange();
443 }
444
446 diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T,
447 QualType ConvTy) override {
448 return S.Diag(Loc, diag::err_acc_int_expr_explicit_conversion)
449 << T << ConvTy;
450 }
451
452 SemaBase::SemaDiagnosticBuilder noteExplicitConv(Sema &S,
453 CXXConversionDecl *Conv,
454 QualType ConvTy) override {
455 return S.Diag(Conv->getLocation(), diag::note_acc_int_expr_conversion)
456 << ConvTy->isEnumeralType() << ConvTy;
457 }
458
460 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override {
461 return S.Diag(Loc, diag::err_acc_int_expr_multiple_conversions) << T;
462 }
463
465 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
466 return S.Diag(Conv->getLocation(), diag::note_acc_int_expr_conversion)
467 << ConvTy->isEnumeralType() << ConvTy;
468 }
469
471 diagnoseConversion(Sema &S, SourceLocation Loc, QualType T,
472 QualType ConvTy) override {
473 llvm_unreachable("conversion functions are permitted");
474 }
475 } IntExprDiagnoser(DK, CK, IntExpr);
476
477 if (!IntExpr)
478 return ExprError();
479
480 ExprResult IntExprResult = SemaRef.PerformContextualImplicitConversion(
481 Loc, IntExpr, IntExprDiagnoser);
482 if (IntExprResult.isInvalid())
483 return ExprError();
484
485 IntExpr = IntExprResult.get();
486 if (!IntExpr->isTypeDependent() && !IntExpr->getType()->isIntegerType())
487 return ExprError();
488
489 // TODO OpenACC: Do we want to perform usual unary conversions here? When
490 // doing codegen we might find that is necessary, but skip it for now.
491 return IntExpr;
492}
493
495 Expr *VarExpr) {
496 // We already know that VarExpr is a proper reference to a variable, so we
497 // should be able to just take the type of the expression to get the type of
498 // the referenced variable.
499
500 // We've already seen an error, don't diagnose anything else.
501 if (!VarExpr || VarExpr->containsErrors())
502 return false;
503
505 VarExpr->hasPlaceholderType(BuiltinType::ArraySection)) {
506 Diag(VarExpr->getExprLoc(), diag::err_array_section_use) << /*OpenACC=*/0;
507 Diag(VarExpr->getExprLoc(), diag::note_acc_expected_pointer_var);
508 return true;
509 }
510
511 QualType Ty = VarExpr->getType();
513
514 // Nothing we can do if this is a dependent type.
515 if (Ty->isDependentType())
516 return false;
517
518 if (!Ty->isPointerType())
519 return Diag(VarExpr->getExprLoc(), diag::err_acc_var_not_pointer_type)
520 << ClauseKind << Ty;
521 return false;
522}
523
526 if (DK == OpenACCDirectiveKind::Cache) {
527 CacheInfo.ParsingCacheVarList = true;
528 CacheInfo.IsInvalidCacheRef = false;
529 }
530}
531
533 CacheInfo.ParsingCacheVarList = false;
534 CacheInfo.IsInvalidCacheRef = false;
535 // This makes sure that we properly mark variables 'used' that are referenced.
536 SemaRef.CleanupVarDeclMarking();
537}
538
540 Expr *CurVarExpr = VarExpr->IgnoreParenImpCasts();
541 // Clear this here, so we can do the returns based on the invalid cache ref
542 // here. Note all return statements in this function must return ExprError if
543 // IsInvalidCacheRef. However, instead of doing an 'early return' in that
544 // case, we can let the rest of the diagnostics happen, as the invalid decl
545 // ref is a warning.
546 bool WasParsingInvalidCacheRef =
547 CacheInfo.ParsingCacheVarList && CacheInfo.IsInvalidCacheRef;
548 CacheInfo.ParsingCacheVarList = false;
549 CacheInfo.IsInvalidCacheRef = false;
550
552 Diag(VarExpr->getExprLoc(), diag::err_acc_not_a_var_ref_cache);
553 return ExprError();
554 }
555
556 // It isn't clear what 'simple array element or simple subarray' means, so we
557 // will just allow arbitrary depth.
559 if (auto *SubScrpt = dyn_cast<ArraySubscriptExpr>(CurVarExpr))
560 CurVarExpr = SubScrpt->getBase()->IgnoreParenImpCasts();
561 else
562 CurVarExpr =
563 cast<ArraySectionExpr>(CurVarExpr)->getBase()->IgnoreParenImpCasts();
564 }
565
566 // References to a VarDecl are fine.
567 if (const auto *DRE = dyn_cast<DeclRefExpr>(CurVarExpr)) {
569 DRE->getFoundDecl()->getCanonicalDecl()))
570 return WasParsingInvalidCacheRef ? ExprEmpty() : VarExpr;
571 }
572
573 if (const auto *ME = dyn_cast<MemberExpr>(CurVarExpr)) {
574 if (isa<FieldDecl>(ME->getMemberDecl()->getCanonicalDecl())) {
575 return WasParsingInvalidCacheRef ? ExprEmpty() : VarExpr;
576 }
577 }
578
579 // Nothing really we can do here, as these are dependent. So just return they
580 // are valid.
582 return WasParsingInvalidCacheRef ? ExprEmpty() : VarExpr;
583
584 // There isn't really anything we can do in the case of a recovery expr, so
585 // skip the diagnostic rather than produce a confusing diagnostic.
586 if (isa<RecoveryExpr>(CurVarExpr))
587 return ExprError();
588
589 Diag(VarExpr->getExprLoc(), diag::err_acc_not_a_var_ref_cache);
590 return ExprError();
591}
592
594 if (!getLangOpts().OpenACC || !CacheInfo.ParsingCacheVarList || !D ||
595 D->isInvalidDecl())
596 return;
597 // A 'cache' variable reference MUST be declared before the 'acc.loop' we
598 // generate in codegen, so we have to mark it invalid here in some way. We do
599 // so in a bit of a convoluted way as there is no good way to put this into
600 // the AST, so we store it in SemaOpenACC State. We can check the Scope
601 // during parsing to make sure there is a 'loop' before the decl is
602 // declared(and skip during instantiation).
603 // We only diagnose this as a warning, as this isn't required by the standard
604 // (unless you take a VERY awkward reading of some awkward prose).
605
606 Scope *CurScope = SemaRef.getCurScope();
607
608 // if we are at TU level, we are either doing some EXTRA wacky, or are in a
609 // template instantiation, so just give up.
610 if (CurScope->getDepth() == 0)
611 return;
612
613 while (CurScope) {
614 // If we run into a loop construct scope, than this is 'correct' in that the
615 // declaration is outside of the loop.
616 if (CurScope->isOpenACCLoopConstructScope())
617 return;
618
619 if (CurScope->isDeclScope(D)) {
620 Diag(Loc, diag::warn_acc_cache_var_not_outside_loop);
621
622 CacheInfo.IsInvalidCacheRef = true;
623 }
624
625 CurScope = CurScope->getParent();
626 }
627 // If we don't find the decl at all, we assume that it must be outside of the
628 // loop (or we aren't in a loop!) so skip the diagnostic.
629}
630
631namespace {
632// Check whether the type of the thing we are referencing is OK for things like
633// private, firstprivate, and reduction, which require certain operators to be
634// available.
635ExprResult CheckVarType(SemaOpenACC &S, OpenACCClauseKind CK, Expr *VarExpr,
636 SourceLocation InnerLoc, QualType InnerTy) {
637 // There is nothing to do here, only these three have these sorts of
638 // restrictions.
639 if (CK != OpenACCClauseKind::Private &&
642 return VarExpr;
643
644 // We can't test this if it isn't here, or if the type isn't clear yet.
645 if (InnerTy.isNull() || InnerTy->isDependentType())
646 return VarExpr;
647
648 InnerTy = InnerTy.getUnqualifiedType();
649 if (auto *RefTy = InnerTy->getAs<ReferenceType>())
650 InnerTy = RefTy->getPointeeType();
651
652 if (auto *ArrTy = InnerTy->getAsArrayTypeUnsafe()) {
653 // Non constant arrays decay to 'pointer', so warn and return that we're
654 // successful.
655 if (!ArrTy->isConstantArrayType()) {
656 S.Diag(InnerLoc, clang::diag::warn_acc_var_referenced_non_const_array)
657 << InnerTy << CK;
658 return VarExpr;
659 }
660
661 return CheckVarType(S, CK, VarExpr, InnerLoc, ArrTy->getElementType());
662 }
663
664 if (S.SemaRef.RequireCompleteType(InnerLoc, InnerTy,
666 diag::err_incomplete_type))
667 return ExprError();
668
669 auto *RD = InnerTy->getAsCXXRecordDecl();
670
671 // if this isn't a C++ record decl, we can create/copy/destroy this thing at
672 // will without problem, so this is a success.
673 if (!RD)
674 return VarExpr;
675
676 if (CK == OpenACCClauseKind::Private) {
677 bool HasNonDeletedDefaultCtor =
678 llvm::find_if(RD->ctors(), [](const CXXConstructorDecl *CD) {
679 return CD->isDefaultConstructor() && !CD->isDeleted();
680 }) != RD->ctors().end();
681 if (!HasNonDeletedDefaultCtor && !RD->needsImplicitDefaultConstructor()) {
682 S.Diag(InnerLoc, clang::diag::warn_acc_var_referenced_lacks_op)
683 << InnerTy << CK << clang::diag::AccVarReferencedReason::DefCtor;
684 return ExprError();
685 }
686 } else if (CK == OpenACCClauseKind::FirstPrivate) {
687 if (!RD->hasSimpleCopyConstructor()) {
688 Sema::SpecialMemberOverloadResult SMOR = S.SemaRef.LookupSpecialMember(
689 RD, CXXSpecialMemberKind::CopyConstructor, /*ConstArg=*/true,
690 /*VolatileArg=*/false, /*RValueThis=*/false, /*ConstThis=*/false,
691 /*VolatileThis=*/false);
692
694 SMOR.getMethod()->isDeleted()) {
695 S.Diag(InnerLoc, clang::diag::warn_acc_var_referenced_lacks_op)
696 << InnerTy << CK << clang::diag::AccVarReferencedReason::CopyCtor;
697 return ExprError();
698 }
699 }
700 } else if (CK == OpenACCClauseKind::Reduction) {
701 // TODO: Reduction needs to be an aggregate, which gets checked later, so
702 // construction here isn't a problem. However, we need to make sure that we
703 // can compare it correctly still.
704 }
705
706 // All 3 things need to make sure they have a dtor.
707 bool DestructorDeleted =
708 RD->getDestructor() && RD->getDestructor()->isDeleted();
709 if (DestructorDeleted && !RD->needsImplicitDestructor()) {
710 S.Diag(InnerLoc, clang::diag::warn_acc_var_referenced_lacks_op)
711 << InnerTy << CK << clang::diag::AccVarReferencedReason::Dtor;
712 return ExprError();
713 }
714 return VarExpr;
715}
716
717ExprResult CheckVarType(SemaOpenACC &S, OpenACCClauseKind CK, Expr *VarExpr,
718 Expr *InnerExpr) {
719 if (!InnerExpr)
720 return VarExpr;
721 return CheckVarType(S, CK, VarExpr, InnerExpr->getBeginLoc(),
722 InnerExpr->getType());
723}
724} // namespace
725
727 Expr *VarExpr) {
728 // This makes sure that we properly mark variables 'used' that are referenced.
729 SemaRef.CleanupVarDeclMarking();
730
731 // This has unique enough restrictions that we should split it to a separate
732 // function.
734 return ActOnCacheVar(VarExpr);
735
736 Expr *CurVarExpr = VarExpr->IgnoreParenImpCasts();
737
738 // 'use_device' doesn't allow array subscript or array sections.
739 // OpenACC3.3 2.8:
740 // A 'var' in a 'use_device' clause must be the name of a variable or array.
741 // OpenACC3.3 2.13:
742 // A 'var' in a 'declare' directive must be a variable or array name.
743 if ((CK == OpenACCClauseKind::UseDevice ||
745 if (isa<ArraySubscriptExpr>(CurVarExpr)) {
746 Diag(VarExpr->getExprLoc(),
747 diag::err_acc_not_a_var_ref_use_device_declare)
749 return ExprError();
750 }
751 // As an extension, we allow 'array sections'/'sub-arrays' here, as that is
752 // effectively defining an array, and are in common use.
753 if (isa<ArraySectionExpr>(CurVarExpr))
754 Diag(VarExpr->getExprLoc(),
755 diag::ext_acc_array_section_use_device_declare)
757 }
758
759 // Sub-arrays/subscript-exprs are fine as long as the base is a
760 // VarExpr/MemberExpr. So strip all of those off.
762 if (auto *SubScrpt = dyn_cast<ArraySubscriptExpr>(CurVarExpr))
763 CurVarExpr = SubScrpt->getBase()->IgnoreParenImpCasts();
764 else
765 CurVarExpr =
766 cast<ArraySectionExpr>(CurVarExpr)->getBase()->IgnoreParenImpCasts();
767 }
768
769 // References to a VarDecl are fine.
770 if (const auto *DRE = dyn_cast<DeclRefExpr>(CurVarExpr)) {
772 DRE->getFoundDecl()->getCanonicalDecl()))
773 return CheckVarType(*this, CK, VarExpr, CurVarExpr);
774 }
775
776 // If CK is a Reduction, this special cases for OpenACC3.3 2.5.15: "A var in a
777 // reduction clause must be a scalar variable name, an aggregate variable
778 // name, an array element, or a subarray.
779 // If CK is a 'use_device', this also isn't valid, as it isn't the name of a
780 // variable or array, if not done as a member expr.
781 // A MemberExpr that references a Field is valid for other clauses.
782 if (const auto *ME = dyn_cast<MemberExpr>(CurVarExpr)) {
783 if (isa<FieldDecl>(ME->getMemberDecl()->getCanonicalDecl())) {
787
788 // We can allow 'member expr' if the 'this' is implicit in the case of
789 // declare, reduction, and use_device.
790 const auto *This = dyn_cast<CXXThisExpr>(ME->getBase());
791 if (This && This->isImplicit())
792 return CheckVarType(*this, CK, VarExpr, CurVarExpr);
793 } else {
794 return CheckVarType(*this, CK, VarExpr, CurVarExpr);
795 }
796 }
797 }
798
799 // Referring to 'this' is ok for the most part, but for 'use_device'/'declare'
800 // doesn't fall into 'variable or array name'
803 return CheckVarType(*this, CK, VarExpr, CurVarExpr);
804
805 // Nothing really we can do here, as these are dependent. So just return they
806 // are valid.
807 if (isa<DependentScopeDeclRefExpr>(CurVarExpr) ||
810 return CheckVarType(*this, CK, VarExpr, CurVarExpr);
811
812 // There isn't really anything we can do in the case of a recovery expr, so
813 // skip the diagnostic rather than produce a confusing diagnostic.
814 if (isa<RecoveryExpr>(CurVarExpr))
815 return ExprError();
816
818 Diag(VarExpr->getExprLoc(), diag::err_acc_not_a_var_ref_use_device_declare)
819 << /*declare*/ 1;
820 else if (CK == OpenACCClauseKind::UseDevice)
821 Diag(VarExpr->getExprLoc(), diag::err_acc_not_a_var_ref_use_device_declare)
822 << /*use_device*/ 0;
823 else
824 Diag(VarExpr->getExprLoc(), diag::err_acc_not_a_var_ref)
826 return ExprError();
827}
828
830 Expr *LowerBound,
831 SourceLocation ColonLoc,
832 Expr *Length,
833 SourceLocation RBLoc) {
834 ASTContext &Context = getASTContext();
835
836 // Handle placeholders.
837 if (Base->hasPlaceholderType() &&
838 !Base->hasPlaceholderType(BuiltinType::ArraySection)) {
839 ExprResult Result = SemaRef.CheckPlaceholderExpr(Base);
840 if (Result.isInvalid())
841 return ExprError();
842 Base = Result.get();
843 }
844 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
845 ExprResult Result = SemaRef.CheckPlaceholderExpr(LowerBound);
846 if (Result.isInvalid())
847 return ExprError();
848 Result = SemaRef.DefaultLvalueConversion(Result.get());
849 if (Result.isInvalid())
850 return ExprError();
851 LowerBound = Result.get();
852 }
853 if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
854 ExprResult Result = SemaRef.CheckPlaceholderExpr(Length);
855 if (Result.isInvalid())
856 return ExprError();
857 Result = SemaRef.DefaultLvalueConversion(Result.get());
858 if (Result.isInvalid())
859 return ExprError();
860 Length = Result.get();
861 }
862
863 // Check the 'base' value, it must be an array or pointer type, and not to/of
864 // a function type.
866 QualType ResultTy;
867 if (!Base->isTypeDependent()) {
868 // 'AnyPointerType' would be wrong here, because it includes ObjC types.
869 if (OriginalBaseTy->isPointerType()) {
870 ResultTy = OriginalBaseTy->getPointeeType();
871 } else if (OriginalBaseTy->isArrayType()) {
872 ResultTy = OriginalBaseTy->getAsArrayTypeUnsafe()->getElementType();
873 } else {
874 return ExprError(
875 Diag(Base->getExprLoc(), diag::err_acc_typecheck_subarray_value)
876 << Base->getSourceRange());
877 }
878
879 if (ResultTy->isFunctionType()) {
880 Diag(Base->getExprLoc(), diag::err_acc_subarray_function_type)
881 << ResultTy << Base->getSourceRange();
882 return ExprError();
883 }
884
885 if (SemaRef.RequireCompleteType(Base->getExprLoc(), ResultTy,
886 diag::err_acc_subarray_incomplete_type,
887 Base))
888 return ExprError();
889
890 if (!Base->hasPlaceholderType(BuiltinType::ArraySection)) {
891 ExprResult Result = SemaRef.DefaultFunctionArrayLvalueConversion(Base);
892 if (Result.isInvalid())
893 return ExprError();
894 Base = Result.get();
895 }
896 }
897
898 auto GetRecovery = [&](Expr *E, QualType Ty) {
899 ExprResult Recovery =
900 SemaRef.CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), E, Ty);
901 return Recovery.isUsable() ? Recovery.get() : nullptr;
902 };
903
904 // Ensure both of the expressions are int-exprs.
905 if (LowerBound && !LowerBound->isTypeDependent()) {
906 ExprResult LBRes =
908 LowerBound->getExprLoc(), LowerBound);
909
910 if (LBRes.isUsable())
911 LBRes = SemaRef.DefaultLvalueConversion(LBRes.get());
912 LowerBound =
913 LBRes.isUsable() ? LBRes.get() : GetRecovery(LowerBound, Context.IntTy);
914 }
915
916 if (Length && !Length->isTypeDependent()) {
917 ExprResult LenRes =
919 Length->getExprLoc(), Length);
920
921 if (LenRes.isUsable())
922 LenRes = SemaRef.DefaultLvalueConversion(LenRes.get());
923 Length =
924 LenRes.isUsable() ? LenRes.get() : GetRecovery(Length, Context.IntTy);
925 }
926
927 // Length is required if the base type is not an array of known bounds.
928 if (!Length && (OriginalBaseTy.isNull() ||
929 (!OriginalBaseTy->isDependentType() &&
930 !OriginalBaseTy->isConstantArrayType() &&
931 !OriginalBaseTy->isDependentSizedArrayType()))) {
932 bool IsArray = !OriginalBaseTy.isNull() && OriginalBaseTy->isArrayType();
933 SourceLocation DiagLoc = ColonLoc.isInvalid() ? LBLoc : ColonLoc;
934 Diag(DiagLoc, diag::err_acc_subarray_no_length) << IsArray;
935 // Fill in a dummy 'length' so that when we instantiate this we don't
936 // double-diagnose here.
937 ExprResult Recovery = SemaRef.CreateRecoveryExpr(
938 DiagLoc, SourceLocation(), ArrayRef<Expr *>(), Context.IntTy);
939 Length = Recovery.isUsable() ? Recovery.get() : nullptr;
940 }
941
942 // Check the values of each of the arguments, they cannot be negative(we
943 // assume), and if the array bound is known, must be within range. As we do
944 // so, do our best to continue with evaluation, we can set the
945 // value/expression to nullptr/nullopt if they are invalid, and treat them as
946 // not present for the rest of evaluation.
947
948 // We don't have to check for dependence, because the dependent size is
949 // represented as a different AST node.
950 std::optional<llvm::APSInt> BaseSize;
951 if (!OriginalBaseTy.isNull() && OriginalBaseTy->isConstantArrayType()) {
952 const auto *ArrayTy = Context.getAsConstantArrayType(OriginalBaseTy);
953 BaseSize = ArrayTy->getSize();
954 }
955
956 auto GetBoundValue = [&](Expr *E) -> std::optional<llvm::APSInt> {
957 if (!E || E->isInstantiationDependent())
958 return std::nullopt;
959
961 if (!E->EvaluateAsInt(Res, Context))
962 return std::nullopt;
963 return Res.Val.getInt();
964 };
965
966 std::optional<llvm::APSInt> LowerBoundValue = GetBoundValue(LowerBound);
967 std::optional<llvm::APSInt> LengthValue = GetBoundValue(Length);
968
969 // Check lower bound for negative or out of range.
970 if (LowerBoundValue.has_value()) {
971 if (LowerBoundValue->isNegative()) {
972 Diag(LowerBound->getExprLoc(), diag::err_acc_subarray_negative)
973 << /*LowerBound=*/0 << toString(*LowerBoundValue, /*Radix=*/10);
974 LowerBoundValue.reset();
975 LowerBound = GetRecovery(LowerBound, LowerBound->getType());
976 } else if (BaseSize.has_value() &&
977 llvm::APSInt::compareValues(*LowerBoundValue, *BaseSize) >= 0) {
978 // Lower bound (start index) must be less than the size of the array.
979 Diag(LowerBound->getExprLoc(), diag::err_acc_subarray_out_of_range)
980 << /*LowerBound=*/0 << toString(*LowerBoundValue, /*Radix=*/10)
981 << toString(*BaseSize, /*Radix=*/10);
982 LowerBoundValue.reset();
983 LowerBound = GetRecovery(LowerBound, LowerBound->getType());
984 }
985 }
986
987 // Check length for negative or out of range.
988 if (LengthValue.has_value()) {
989 if (LengthValue->isNegative()) {
990 Diag(Length->getExprLoc(), diag::err_acc_subarray_negative)
991 << /*Length=*/1 << toString(*LengthValue, /*Radix=*/10);
992 LengthValue.reset();
993 Length = GetRecovery(Length, Length->getType());
994 } else if (BaseSize.has_value() &&
995 llvm::APSInt::compareValues(*LengthValue, *BaseSize) > 0) {
996 // Length must be lessthan or EQUAL to the size of the array.
997 Diag(Length->getExprLoc(), diag::err_acc_subarray_out_of_range)
998 << /*Length=*/1 << toString(*LengthValue, /*Radix=*/10)
999 << toString(*BaseSize, /*Radix=*/10);
1000 LengthValue.reset();
1001 Length = GetRecovery(Length, Length->getType());
1002 }
1003 }
1004
1005 // Adding two APSInts requires matching sign and width, so extract those here.
1006 auto AddAPSInt = [](llvm::APSInt LHS, llvm::APSInt RHS) -> llvm::APSInt {
1007 if (LHS.isSigned() == RHS.isSigned() &&
1008 LHS.getBitWidth() == RHS.getBitWidth())
1009 return LHS + RHS;
1010
1011 // Width is + 1 so that unsigned->signed conversion just works.
1012 unsigned Width = std::max(LHS.getBitWidth(), RHS.getBitWidth()) + 1;
1013 return llvm::APSInt(LHS.sext(Width) + RHS.sext(Width), /*Signed=*/true);
1014 };
1015
1016 // If we know all 3 values, we can diagnose that the total value would be out
1017 // of range.
1018 if (BaseSize.has_value() && LowerBoundValue.has_value() &&
1019 LengthValue.has_value() &&
1020 llvm::APSInt::compareValues(AddAPSInt(*LowerBoundValue, *LengthValue),
1021 *BaseSize) > 0) {
1022 Diag(Base->getExprLoc(),
1023 diag::err_acc_subarray_base_plus_length_out_of_range)
1024 << toString(*LowerBoundValue, /*Radix=*/10)
1025 << toString(*LengthValue, /*Radix=*/10)
1026 << toString(*BaseSize, /*Radix=*/10);
1027
1028 LowerBoundValue.reset();
1029 LowerBound = GetRecovery(LowerBound, LowerBound->getType());
1030 LengthValue.reset();
1031 Length = GetRecovery(Length, Length->getType());
1032 }
1033
1034 // If any part of the expression is dependent, return a dependent sub-array.
1035 QualType ArrayExprTy = Context.ArraySectionTy;
1036 if (Base->isTypeDependent() ||
1037 (LowerBound && LowerBound->isTypeDependent()) ||
1038 (Length && Length->isTypeDependent()))
1039 ArrayExprTy = Context.DependentTy;
1040
1041 return new (Context)
1042 ArraySectionExpr(Base, LowerBound, Length, ArrayExprTy, VK_LValue,
1043 OK_Ordinary, ColonLoc, RBLoc);
1044}
1045
1047 if (!getLangOpts().OpenACC)
1048 return;
1049
1050 if (!LoopInfo.TopLevelLoopSeen)
1051 return;
1052
1053 if (CollapseInfo.CurCollapseCount && *CollapseInfo.CurCollapseCount > 0) {
1054 Diag(WhileLoc, diag::err_acc_invalid_in_loop)
1055 << /*while loop*/ 1 << CollapseInfo.DirectiveKind
1057 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
1058 Diag(CollapseInfo.ActiveCollapse->getBeginLoc(),
1059 diag::note_acc_active_clause_here)
1061
1062 // Remove the value so that we don't get cascading errors in the body. The
1063 // caller RAII object will restore this.
1064 CollapseInfo.CurCollapseCount = std::nullopt;
1065 }
1066
1067 if (TileInfo.CurTileCount && *TileInfo.CurTileCount > 0) {
1068 Diag(WhileLoc, diag::err_acc_invalid_in_loop)
1069 << /*while loop*/ 1 << TileInfo.DirectiveKind
1071 assert(TileInfo.ActiveTile && "tile count without object?");
1072 Diag(TileInfo.ActiveTile->getBeginLoc(), diag::note_acc_active_clause_here)
1074
1075 // Remove the value so that we don't get cascading errors in the body. The
1076 // caller RAII object will restore this.
1077 TileInfo.CurTileCount = std::nullopt;
1078 }
1079}
1080
1082 if (!getLangOpts().OpenACC)
1083 return;
1084
1085 if (!LoopInfo.TopLevelLoopSeen)
1086 return;
1087
1088 if (CollapseInfo.CurCollapseCount && *CollapseInfo.CurCollapseCount > 0) {
1089 Diag(DoLoc, diag::err_acc_invalid_in_loop)
1090 << /*do loop*/ 2 << CollapseInfo.DirectiveKind
1092 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
1093 Diag(CollapseInfo.ActiveCollapse->getBeginLoc(),
1094 diag::note_acc_active_clause_here)
1096
1097 // Remove the value so that we don't get cascading errors in the body. The
1098 // caller RAII object will restore this.
1099 CollapseInfo.CurCollapseCount = std::nullopt;
1100 }
1101
1102 if (TileInfo.CurTileCount && *TileInfo.CurTileCount > 0) {
1103 Diag(DoLoc, diag::err_acc_invalid_in_loop)
1104 << /*do loop*/ 2 << TileInfo.DirectiveKind << OpenACCClauseKind::Tile;
1105 assert(TileInfo.ActiveTile && "tile count without object?");
1106 Diag(TileInfo.ActiveTile->getBeginLoc(), diag::note_acc_active_clause_here)
1108
1109 // Remove the value so that we don't get cascading errors in the body. The
1110 // caller RAII object will restore this.
1111 TileInfo.CurTileCount = std::nullopt;
1112 }
1113}
1114
1115void SemaOpenACC::ForStmtBeginHelper(SourceLocation ForLoc,
1116 ForStmtBeginChecker &C) {
1117 assert(getLangOpts().OpenACC && "Check enabled when not OpenACC?");
1118
1119 // Enable the while/do-while checking.
1120 LoopInfo.TopLevelLoopSeen = true;
1121
1122 if (CollapseInfo.CurCollapseCount && *CollapseInfo.CurCollapseCount > 0) {
1123 // Check the format of this loop if it is affected by the collapse.
1124 C.check();
1125
1126 // OpenACC 3.3 2.9.1:
1127 // Each associated loop, except the innermost, must contain exactly one loop
1128 // or loop nest.
1129 // This checks for more than 1 loop at the current level, the
1130 // 'depth'-satisifed checking manages the 'not zero' case.
1131 if (LoopInfo.CurLevelHasLoopAlready) {
1132 Diag(ForLoc, diag::err_acc_clause_multiple_loops)
1133 << CollapseInfo.DirectiveKind << OpenACCClauseKind::Collapse;
1134 assert(CollapseInfo.ActiveCollapse && "No collapse object?");
1135 Diag(CollapseInfo.ActiveCollapse->getBeginLoc(),
1136 diag::note_acc_active_clause_here)
1138 } else {
1139 --(*CollapseInfo.CurCollapseCount);
1140
1141 // Once we've hit zero here, we know we have deep enough 'for' loops to
1142 // get to the bottom.
1143 if (*CollapseInfo.CurCollapseCount == 0)
1144 CollapseInfo.CollapseDepthSatisfied = true;
1145 }
1146 }
1147
1148 if (TileInfo.CurTileCount && *TileInfo.CurTileCount > 0) {
1149 // Check the format of this loop if it is affected by the tile.
1150 C.check();
1151
1152 if (LoopInfo.CurLevelHasLoopAlready) {
1153 Diag(ForLoc, diag::err_acc_clause_multiple_loops)
1154 << TileInfo.DirectiveKind << OpenACCClauseKind::Tile;
1155 assert(TileInfo.ActiveTile && "No tile object?");
1156 Diag(TileInfo.ActiveTile->getBeginLoc(),
1157 diag::note_acc_active_clause_here)
1159 } else {
1160 TileInfo.CurTileCount = *TileInfo.CurTileCount - 1;
1161 // Once we've hit zero here, we know we have deep enough 'for' loops to
1162 // get to the bottom.
1163 if (*TileInfo.CurTileCount == 0)
1164 TileInfo.TileDepthSatisfied = true;
1165 }
1166 }
1167
1168 // Set this to 'false' for the body of this loop, so that the next level
1169 // checks independently.
1170 LoopInfo.CurLevelHasLoopAlready = false;
1171}
1172
1173namespace {
1174bool isValidLoopVariableType(QualType LoopVarTy) {
1175 // Just skip if it is dependent, it could be any of the below.
1176 if (LoopVarTy->isDependentType())
1177 return true;
1178
1179 // The loop variable must be of integer,
1180 if (LoopVarTy->isIntegerType())
1181 return true;
1182
1183 // C/C++ pointer,
1184 if (LoopVarTy->isPointerType())
1185 return true;
1186
1187 // or C++ random-access iterator type.
1188 if (const auto *RD = LoopVarTy->getAsCXXRecordDecl()) {
1189 // Note: Only do CXXRecordDecl because RecordDecl can't be a random access
1190 // iterator type!
1191
1192 // We could either do a lot of work to see if this matches
1193 // random-access-iterator, but it seems that just checking that the
1194 // 'iterator_category' typedef is more than sufficient. If programmers are
1195 // willing to lie about this, we can let them.
1196
1197 for (const auto *TD :
1198 llvm::make_filter_range(RD->decls(), llvm::IsaPred<TypedefNameDecl>)) {
1199 const auto *TDND = cast<TypedefNameDecl>(TD)->getCanonicalDecl();
1200
1201 if (TDND->getName() != "iterator_category")
1202 continue;
1203
1204 // If there is no type for this decl, return false.
1205 if (TDND->getUnderlyingType().isNull())
1206 return false;
1207
1208 const CXXRecordDecl *ItrCategoryDecl =
1209 TDND->getUnderlyingType()->getAsCXXRecordDecl();
1210
1211 // If the category isn't a record decl, it isn't the tag type.
1212 if (!ItrCategoryDecl)
1213 return false;
1214
1215 auto IsRandomAccessIteratorTag = [](const CXXRecordDecl *RD) {
1216 if (RD->getName() != "random_access_iterator_tag")
1217 return false;
1218 // Checks just for std::random_access_iterator_tag.
1219 return RD->getEnclosingNamespaceContext()->isStdNamespace();
1220 };
1221
1222 if (IsRandomAccessIteratorTag(ItrCategoryDecl))
1223 return true;
1224
1225 // We can also support tag-types inherited from the
1226 // random_access_iterator_tag.
1227 if (ItrCategoryDecl->isCompleteDefinition())
1228 for (CXXBaseSpecifier BS : ItrCategoryDecl->bases())
1229 if (IsRandomAccessIteratorTag(BS.getType()->getAsCXXRecordDecl()))
1230 return true;
1231
1232 return false;
1233 }
1234 }
1235
1236 return false;
1237}
1238const ValueDecl *getDeclFromExpr(const Expr *E) {
1239 E = E->IgnoreParenImpCasts();
1240 if (const auto *FE = dyn_cast<FullExpr>(E))
1241 E = FE->getSubExpr();
1242
1243 E = E->IgnoreParenImpCasts();
1244
1245 if (!E)
1246 return nullptr;
1247 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
1248 return DRE->getDecl();
1249
1250 if (const auto *ME = dyn_cast<MemberExpr>(E))
1251 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
1252 return ME->getMemberDecl();
1253
1254 return nullptr;
1255}
1256} // namespace
1257
1258void SemaOpenACC::ForStmtBeginChecker::checkRangeFor() {
1259 const RangeForInfo &RFI = std::get<RangeForInfo>(Info);
1260 // If this hasn't changed since last instantiated we're done.
1261 if (RFI.Uninstantiated == RFI.CurrentVersion)
1262 return;
1263
1264 const DeclStmt *UninstRangeStmt =
1265 IsInstantiation ? RFI.Uninstantiated->getBeginStmt() : nullptr;
1266 const DeclStmt *RangeStmt = RFI.CurrentVersion->getBeginStmt();
1267
1268 // If this isn't the first time we've checked this loop, suppress any cases
1269 // where we previously diagnosed.
1270 if (UninstRangeStmt) {
1271 const ValueDecl *InitVar =
1272 cast<ValueDecl>(UninstRangeStmt->getSingleDecl());
1273 QualType VarType = InitVar->getType().getNonReferenceType();
1274
1275 if (!isValidLoopVariableType(VarType))
1276 return;
1277 }
1278
1279 // In some dependent contexts, the autogenerated range statement doesn't get
1280 // included until instantiation, so skip for now.
1281 if (RangeStmt) {
1282 const ValueDecl *InitVar = cast<ValueDecl>(RangeStmt->getSingleDecl());
1283 QualType VarType = InitVar->getType().getNonReferenceType();
1284
1285 if (!isValidLoopVariableType(VarType)) {
1286 SemaRef.Diag(InitVar->getBeginLoc(), diag::err_acc_loop_variable_type)
1287 << SemaRef.LoopWithoutSeqInfo.Kind << VarType;
1288 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1289 diag::note_acc_construct_here)
1290 << SemaRef.LoopWithoutSeqInfo.Kind;
1291 return;
1292 }
1293 }
1294}
1295bool SemaOpenACC::ForStmtBeginChecker::checkForInit(const Stmt *InitStmt,
1296 const ValueDecl *&InitVar,
1297 bool Diag) {
1298 // Init statement is required.
1299 if (!InitStmt) {
1300 if (Diag) {
1301 SemaRef.Diag(ForLoc, diag::err_acc_loop_variable)
1302 << SemaRef.LoopWithoutSeqInfo.Kind;
1303 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1304 diag::note_acc_construct_here)
1305 << SemaRef.LoopWithoutSeqInfo.Kind;
1306 }
1307 return true;
1308 }
1309 auto DiagLoopVar = [this, Diag, InitStmt]() {
1310 if (Diag) {
1311 SemaRef.Diag(InitStmt->getBeginLoc(), diag::err_acc_loop_variable)
1312 << SemaRef.LoopWithoutSeqInfo.Kind;
1313 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1314 diag::note_acc_construct_here)
1315 << SemaRef.LoopWithoutSeqInfo.Kind;
1316 }
1317 return true;
1318 };
1319
1320 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(InitStmt))
1321 InitStmt = ExprTemp->getSubExpr();
1322 if (const auto *E = dyn_cast<Expr>(InitStmt))
1323 InitStmt = E->IgnoreParenImpCasts();
1324
1325 InitVar = nullptr;
1326 if (const auto *BO = dyn_cast<BinaryOperator>(InitStmt)) {
1327 // Allow assignment operator here.
1328
1329 if (!BO->isAssignmentOp())
1330 return DiagLoopVar();
1331
1332 const Expr *LHS = BO->getLHS()->IgnoreParenImpCasts();
1333 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHS))
1334 InitVar = DRE->getDecl();
1335 } else if (const auto *DS = dyn_cast<DeclStmt>(InitStmt)) {
1336 // Allow T t = <whatever>
1337 if (!DS->isSingleDecl())
1338 return DiagLoopVar();
1339 InitVar = dyn_cast<ValueDecl>(DS->getSingleDecl());
1340
1341 // Ensure we have an initializer, unless this is a record/dependent type.
1342 if (InitVar) {
1343 if (!isa<VarDecl>(InitVar))
1344 return DiagLoopVar();
1345
1346 if (!InitVar->getType()->isRecordType() &&
1347 !InitVar->getType()->isDependentType() &&
1348 !cast<VarDecl>(InitVar)->hasInit())
1349 return DiagLoopVar();
1350 }
1351 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(InitStmt)) {
1352 // Allow assignment operator call.
1353 if (CE->getOperator() != OO_Equal)
1354 return DiagLoopVar();
1355 if (CE->getNumArgs() < 1)
1356 return DiagLoopVar();
1357
1358 const Expr *LHS = CE->getArg(0)->IgnoreParenImpCasts();
1359 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
1360 InitVar = DRE->getDecl();
1361 } else if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
1362 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
1363 InitVar = ME->getMemberDecl();
1364 }
1365 }
1366
1367 // If after all of that, we haven't found a variable, give up.
1368 if (!InitVar)
1369 return DiagLoopVar();
1370
1371 InitVar = cast<ValueDecl>(InitVar->getCanonicalDecl());
1372 QualType VarType = InitVar->getType().getNonReferenceType();
1373
1374 // Since we have one, all we need to do is ensure it is the right type.
1375 if (!isValidLoopVariableType(VarType)) {
1376 if (Diag) {
1377 SemaRef.Diag(InitVar->getBeginLoc(), diag::err_acc_loop_variable_type)
1378 << SemaRef.LoopWithoutSeqInfo.Kind << VarType;
1379 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1380 diag::note_acc_construct_here)
1381 << SemaRef.LoopWithoutSeqInfo.Kind;
1382 }
1383 return true;
1384 }
1385
1386 return false;
1387}
1388
1389bool SemaOpenACC::ForStmtBeginChecker::checkForCond(const Stmt *CondStmt,
1390 const ValueDecl *InitVar,
1391 bool Diag) {
1392 // A condition statement is required.
1393 if (!CondStmt) {
1394 if (Diag) {
1395 SemaRef.Diag(ForLoc, diag::err_acc_loop_terminating_condition)
1396 << SemaRef.LoopWithoutSeqInfo.Kind;
1397 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1398 diag::note_acc_construct_here)
1399 << SemaRef.LoopWithoutSeqInfo.Kind;
1400 }
1401
1402 return true;
1403 }
1404 auto DiagCondVar = [this, Diag, CondStmt] {
1405 if (Diag) {
1406 SemaRef.Diag(CondStmt->getBeginLoc(),
1407 diag::err_acc_loop_terminating_condition)
1408 << SemaRef.LoopWithoutSeqInfo.Kind;
1409 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1410 diag::note_acc_construct_here)
1411 << SemaRef.LoopWithoutSeqInfo.Kind;
1412 }
1413 return true;
1414 };
1415
1416 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(CondStmt))
1417 CondStmt = ExprTemp->getSubExpr();
1418 if (const auto *E = dyn_cast<Expr>(CondStmt))
1419 CondStmt = E->IgnoreParenImpCasts();
1420
1421 const ValueDecl *CondVar = nullptr;
1422 if (const auto *BO = dyn_cast<BinaryOperator>(CondStmt)) {
1423 switch (BO->getOpcode()) {
1424 default:
1425 return DiagCondVar();
1426 case BO_EQ:
1427 case BO_LT:
1428 case BO_GT:
1429 case BO_NE:
1430 case BO_LE:
1431 case BO_GE:
1432 break;
1433 }
1434
1435 // Assign the condition-var to the LHS. If it either comes back null, or
1436 // the LHS doesn't match the InitVar, assign it to the RHS so that 5 < N is
1437 // allowed.
1438 CondVar = getDeclFromExpr(BO->getLHS());
1439 if (!CondVar ||
1440 (InitVar && CondVar->getCanonicalDecl() != InitVar->getCanonicalDecl()))
1441 CondVar = getDeclFromExpr(BO->getRHS());
1442
1443 } else if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(CondStmt)) {
1444 // Any of the comparison ops should be ok here, but we don't know how to
1445 // handle spaceship, so disallow for now.
1446 if (!CE->isComparisonOp() || CE->getOperator() == OO_Spaceship)
1447 return DiagCondVar();
1448
1449 if (CE->getNumArgs() < 1)
1450 DiagCondVar();
1451
1452 // Same logic here: Assign it to the LHS, unless the LHS comes back null or
1453 // not equal to the init var.
1454 CondVar = getDeclFromExpr(CE->getArg(0));
1455 if (!CondVar ||
1456 (InitVar &&
1457 CondVar->getCanonicalDecl() != InitVar->getCanonicalDecl() &&
1458 CE->getNumArgs() > 1))
1459 CondVar = getDeclFromExpr(CE->getArg(1));
1460 } else {
1461 return DiagCondVar();
1462 }
1463
1464 if (!CondVar)
1465 return DiagCondVar();
1466
1467 // Don't consider this an error unless the init variable was properly set,
1468 // else check to make sure they are the same variable.
1469 if (InitVar && CondVar->getCanonicalDecl() != InitVar->getCanonicalDecl())
1470 return DiagCondVar();
1471
1472 return false;
1473}
1474
1475namespace {
1476// Helper to check the RHS of an assignment during for's step. We can allow
1477// InitVar = InitVar + N, InitVar = N + InitVar, and Initvar = Initvar - N,
1478// where N is an integer.
1479bool isValidForIncRHSAssign(const ValueDecl *InitVar, const Expr *RHS) {
1480
1481 auto isValid = [](const ValueDecl *InitVar, const Expr *InnerLHS,
1482 const Expr *InnerRHS, bool IsAddition) {
1483 // ONE of the sides has to be an integer type.
1484 if (!InnerLHS->getType()->isIntegerType() &&
1485 !InnerRHS->getType()->isIntegerType())
1486 return false;
1487
1488 // If the init var is already an error, don't bother trying to check for
1489 // it.
1490 if (!InitVar)
1491 return true;
1492
1493 const ValueDecl *LHSDecl = getDeclFromExpr(InnerLHS);
1494 const ValueDecl *RHSDecl = getDeclFromExpr(InnerRHS);
1495 // If we can't get a declaration, this is probably an error, so give up.
1496 if (!LHSDecl || !RHSDecl)
1497 return true;
1498
1499 // If the LHS is the InitVar, the other must be int, so this is valid.
1500 if (LHSDecl->getCanonicalDecl() ==
1501 InitVar->getCanonicalDecl())
1502 return true;
1503
1504 // Subtraction doesn't allow the RHS to be init var, so this is invalid.
1505 if (!IsAddition)
1506 return false;
1507
1508 return RHSDecl->getCanonicalDecl() ==
1509 InitVar->getCanonicalDecl();
1510 };
1511
1512 if (const auto *BO = dyn_cast<BinaryOperator>(RHS)) {
1513 BinaryOperatorKind OpC = BO->getOpcode();
1514 if (OpC != BO_Add && OpC != BO_Sub)
1515 return false;
1516 return isValid(InitVar, BO->getLHS(), BO->getRHS(), OpC == BO_Add);
1517 } else if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
1518 OverloadedOperatorKind Op = CE->getOperator();
1519 if (Op != OO_Plus && Op != OO_Minus)
1520 return false;
1521 // Despite Plus/Minus otherwise only being possible with 2 arguments, error
1522 // recovery will sometimes leave us with only 1 here, so fail out if we
1523 // don't have the correct number of args.
1524 if (CE->getNumArgs() != 2)
1525 return false;
1526 return isValid(InitVar, CE->getArg(0), CE->getArg(1), Op == OO_Plus);
1527 }
1528
1529 return false;
1530}
1531} // namespace
1532
1533bool SemaOpenACC::ForStmtBeginChecker::checkForInc(const Stmt *IncStmt,
1534 const ValueDecl *InitVar,
1535 bool Diag) {
1536 if (!IncStmt) {
1537 if (Diag) {
1538 SemaRef.Diag(ForLoc, diag::err_acc_loop_not_monotonic)
1539 << SemaRef.LoopWithoutSeqInfo.Kind;
1540 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1541 diag::note_acc_construct_here)
1542 << SemaRef.LoopWithoutSeqInfo.Kind;
1543 }
1544 return true;
1545 }
1546 auto DiagIncVar = [this, Diag, IncStmt] {
1547 if (Diag) {
1548 SemaRef.Diag(IncStmt->getBeginLoc(), diag::err_acc_loop_not_monotonic)
1549 << SemaRef.LoopWithoutSeqInfo.Kind;
1550 SemaRef.Diag(SemaRef.LoopWithoutSeqInfo.Loc,
1551 diag::note_acc_construct_here)
1552 << SemaRef.LoopWithoutSeqInfo.Kind;
1553 }
1554 return true;
1555 };
1556
1557 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(IncStmt))
1558 IncStmt = ExprTemp->getSubExpr();
1559 if (const auto *E = dyn_cast<Expr>(IncStmt))
1560 IncStmt = E->IgnoreParenImpCasts();
1561
1562 const ValueDecl *IncVar = nullptr;
1563 // Here we enforce the monotonically increase/decrease:
1564 if (const auto *UO = dyn_cast<UnaryOperator>(IncStmt)) {
1565 // Allow increment/decrement ops.
1566 if (!UO->isIncrementDecrementOp())
1567 return DiagIncVar();
1568 IncVar = getDeclFromExpr(UO->getSubExpr());
1569 } else if (const auto *BO = dyn_cast<BinaryOperator>(IncStmt)) {
1570 switch (BO->getOpcode()) {
1571 default:
1572 return DiagIncVar();
1573 case BO_AddAssign:
1574 case BO_SubAssign:
1575 break;
1576 case BO_Assign:
1577 // For assignment we also allow InitVar = InitVar + N, InitVar = N +
1578 // InitVar, and InitVar = InitVar - N; BUT only if 'N' is integral.
1579 if (!isValidForIncRHSAssign(InitVar, BO->getRHS()))
1580 return DiagIncVar();
1581 break;
1582 }
1583 IncVar = getDeclFromExpr(BO->getLHS());
1584 } else if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(IncStmt)) {
1585 if (CE->getNumArgs() < 1)
1586 return DiagIncVar();
1587
1588 switch (CE->getOperator()) {
1589 default:
1590 return DiagIncVar();
1591 case OO_PlusPlus:
1592 case OO_MinusMinus:
1593 case OO_PlusEqual:
1594 case OO_MinusEqual:
1595 break;
1596 case OO_Equal:
1597 // For assignment we also allow InitVar = InitVar + N, InitVar = N +
1598 // InitVar, and InitVar = InitVar - N; BUT only if 'N' is integral.
1599 if (CE->getNumArgs() != 2 ||
1600 !isValidForIncRHSAssign(InitVar, CE->getArg(1)))
1601 return DiagIncVar();
1602 break;
1603 }
1604
1605 IncVar = getDeclFromExpr(CE->getArg(0));
1606 } else {
1607 return DiagIncVar();
1608 }
1609
1610 if (!IncVar)
1611 return DiagIncVar();
1612
1613 // InitVar shouldn't be null unless there was an error, so don't diagnose if
1614 // that is the case. Else we should ensure that it refers to the loop
1615 // value.
1616 if (InitVar && IncVar->getCanonicalDecl() != InitVar->getCanonicalDecl())
1617 return DiagIncVar();
1618
1619 return false;
1620}
1621
1622void SemaOpenACC::ForStmtBeginChecker::checkFor() {
1623 const CheckForInfo &CFI = std::get<CheckForInfo>(Info);
1624
1625 if (!IsInstantiation) {
1626 // If this isn't an instantiation, we can just check all of these and
1627 // diagnose.
1628 const ValueDecl *CurInitVar = nullptr;
1629 checkForInit(CFI.Current.Init, CurInitVar, /*Diag=*/true);
1630 checkForCond(CFI.Current.Condition, CurInitVar, /*Diag=*/true);
1631 checkForInc(CFI.Current.Increment, CurInitVar, /*DIag=*/true);
1632 } else {
1633 const ValueDecl *UninstInitVar = nullptr;
1634 // Checking the 'init' section first. We have to always run both versions,
1635 // at minimum with the 'diag' off, so that we can ensure we get the correct
1636 // instantiation var for checking by later ones.
1637 bool UninstInitFailed =
1638 checkForInit(CFI.Uninst.Init, UninstInitVar, /*Diag=*/false);
1639
1640 // VarDecls are always rebuild because they are dependent, so we can do a
1641 // little work to suppress some of the double checking based on whether the
1642 // type is instantiation dependent. This is imperfect, but will get us most
1643 // cases suppressed. Currently this only handles the 'T t =' case.
1644 auto InitChanged = [=]() {
1645 if (CFI.Uninst.Init == CFI.Current.Init)
1646 return false;
1647
1648 QualType OldVDTy;
1649 QualType NewVDTy;
1650
1651 if (const auto *DS = dyn_cast<DeclStmt>(CFI.Uninst.Init))
1652 if (const VarDecl *VD = dyn_cast_if_present<VarDecl>(
1653 DS->isSingleDecl() ? DS->getSingleDecl() : nullptr))
1654 OldVDTy = VD->getType();
1655 if (const auto *DS = dyn_cast<DeclStmt>(CFI.Current.Init))
1656 if (const VarDecl *VD = dyn_cast_if_present<VarDecl>(
1657 DS->isSingleDecl() ? DS->getSingleDecl() : nullptr))
1658 NewVDTy = VD->getType();
1659
1660 if (OldVDTy.isNull() || NewVDTy.isNull())
1661 return true;
1662
1663 return OldVDTy->isInstantiationDependentType() !=
1665 };
1666
1667 // Only diagnose the new 'init' if the previous version didn't fail, AND the
1668 // current init changed meaningfully.
1669 bool ShouldDiagNewInit = !UninstInitFailed && InitChanged();
1670 const ValueDecl *CurInitVar = nullptr;
1671 checkForInit(CFI.Current.Init, CurInitVar, /*Diag=*/ShouldDiagNewInit);
1672
1673 // Check the condition and increment only if the previous version passed,
1674 // and this changed.
1675 if (CFI.Uninst.Condition != CFI.Current.Condition &&
1676 !checkForCond(CFI.Uninst.Condition, UninstInitVar, /*Diag=*/false))
1677 checkForCond(CFI.Current.Condition, CurInitVar, /*Diag=*/true);
1678 if (CFI.Uninst.Increment != CFI.Current.Increment &&
1679 !checkForInc(CFI.Uninst.Increment, UninstInitVar, /*Diag=*/false))
1680 checkForInc(CFI.Current.Increment, CurInitVar, /*Diag=*/true);
1681 }
1682}
1683
1684void SemaOpenACC::ForStmtBeginChecker::check() {
1685 // If this isn't an active loop without a seq, immediately return, nothing to
1686 // check.
1687 if (SemaRef.LoopWithoutSeqInfo.Kind == OpenACCDirectiveKind::Invalid)
1688 return;
1689
1690 // If we've already checked, because this is a 'top level' one (and asking
1691 // again because 'tile' and 'collapse' might apply), just return, nothing to
1692 // do here.
1693 if (AlreadyChecked)
1694 return;
1695 AlreadyChecked = true;
1696
1697 // OpenACC3.3 2.1:
1698 // A loop associated with a loop construct that does not have a seq clause
1699 // must be written to meet all the following conditions:
1700 // - The loop variable must be of integer, C/C++ pointer, or C++ random-access
1701 // iterator type.
1702 // - The loop variable must monotonically increase or decrease in the
1703 // direction of its termination condition.
1704 // - The loop trip count must be computable in constant time when entering the
1705 // loop construct.
1706 //
1707 // For a C++ range-based for loop, the loop variable
1708 // identified by the above conditions is the internal iterator, such as a
1709 // pointer, that the compiler generates to iterate the range. it is not the
1710 // variable declared by the for loop.
1711
1712 if (std::holds_alternative<RangeForInfo>(Info))
1713 return checkRangeFor();
1714
1715 return checkFor();
1716}
1717
1719 const Stmt *First, const Stmt *OldSecond,
1720 const Stmt *Second, const Stmt *OldThird,
1721 const Stmt *Third) {
1722 if (!getLangOpts().OpenACC)
1723 return;
1724
1725 ForStmtBeginChecker FSBC{*this, ForLoc, OldFirst, OldSecond,
1726 OldThird, First, Second, Third};
1727 // Check if this is the top-level 'for' for a 'loop'. Else it will be checked
1728 // as a part of the helper if a tile/collapse applies.
1729 if (!LoopInfo.TopLevelLoopSeen) {
1730 FSBC.check();
1731 }
1732
1733 ForStmtBeginHelper(ForLoc, FSBC);
1734}
1735
1737 const Stmt *Second, const Stmt *Third) {
1738 if (!getLangOpts().OpenACC)
1739 return;
1740
1741 ForStmtBeginChecker FSBC{*this, ForLoc, First, Second, Third};
1742
1743 // Check if this is the top-level 'for' for a 'loop'. Else it will be checked
1744 // as a part of the helper if a tile/collapse applies.
1745 if (!LoopInfo.TopLevelLoopSeen)
1746 FSBC.check();
1747
1748 ForStmtBeginHelper(ForLoc, FSBC);
1749}
1750
1752 const Stmt *OldRangeFor,
1753 const Stmt *RangeFor) {
1754 if (!getLangOpts().OpenACC || OldRangeFor == nullptr || RangeFor == nullptr)
1755 return;
1756
1757 ForStmtBeginChecker FSBC{*this, ForLoc,
1758 cast_if_present<CXXForRangeStmt>(OldRangeFor),
1759 cast_if_present<CXXForRangeStmt>(RangeFor)};
1760 // Check if this is the top-level 'for' for a 'loop'. Else it will be checked
1761 // as a part of the helper if a tile/collapse applies.
1762 if (!LoopInfo.TopLevelLoopSeen) {
1763 FSBC.check();
1764 }
1765 ForStmtBeginHelper(ForLoc, FSBC);
1766}
1767
1769 const Stmt *RangeFor) {
1770 if (!getLangOpts().OpenACC || RangeFor == nullptr)
1771 return;
1772
1773 ForStmtBeginChecker FSBC = {*this, ForLoc,
1774 cast_if_present<CXXForRangeStmt>(RangeFor)};
1775
1776 // Check if this is the top-level 'for' for a 'loop'. Else it will be checked
1777 // as a part of the helper if a tile/collapse applies.
1778 if (!LoopInfo.TopLevelLoopSeen)
1779 FSBC.check();
1780
1781 ForStmtBeginHelper(ForLoc, FSBC);
1782}
1783
1784namespace {
1785SourceLocation FindInterveningCodeInLoop(const Stmt *CurStmt) {
1786 // We should diagnose on anything except `CompoundStmt`, `NullStmt`,
1787 // `ForStmt`, `CXXForRangeStmt`, since those are legal, and `WhileStmt` and
1788 // `DoStmt`, as those are caught as a violation elsewhere.
1789 // For `CompoundStmt` we need to search inside of it.
1790 if (!CurStmt ||
1792 CurStmt))
1793 return SourceLocation{};
1794
1795 // Any other construct is an error anyway, so it has already been diagnosed.
1796 if (isa<OpenACCConstructStmt>(CurStmt))
1797 return SourceLocation{};
1798
1799 // Search inside the compound statement, this allows for arbitrary nesting
1800 // of compound statements, as long as there isn't any code inside.
1801 if (const auto *CS = dyn_cast<CompoundStmt>(CurStmt)) {
1802 for (const auto *ChildStmt : CS->children()) {
1803 SourceLocation ChildStmtLoc = FindInterveningCodeInLoop(ChildStmt);
1804 if (ChildStmtLoc.isValid())
1805 return ChildStmtLoc;
1806 }
1807 // Empty/not invalid compound statements are legal.
1808 return SourceLocation{};
1809 }
1810 return CurStmt->getBeginLoc();
1811}
1812} // namespace
1813
1815 if (!getLangOpts().OpenACC)
1816 return;
1817
1818 // Set this to 'true' so if we find another one at this level we can diagnose.
1819 LoopInfo.CurLevelHasLoopAlready = true;
1820
1821 if (!Body.isUsable())
1822 return;
1823
1824 bool IsActiveCollapse = CollapseInfo.CurCollapseCount &&
1825 *CollapseInfo.CurCollapseCount > 0 &&
1826 !CollapseInfo.ActiveCollapse->hasForce();
1827 bool IsActiveTile = TileInfo.CurTileCount && *TileInfo.CurTileCount > 0;
1828
1829 if (IsActiveCollapse || IsActiveTile) {
1830 SourceLocation OtherStmtLoc = FindInterveningCodeInLoop(Body.get());
1831
1832 if (OtherStmtLoc.isValid() && IsActiveCollapse) {
1833 Diag(OtherStmtLoc, diag::err_acc_intervening_code)
1834 << OpenACCClauseKind::Collapse << CollapseInfo.DirectiveKind;
1835 Diag(CollapseInfo.ActiveCollapse->getBeginLoc(),
1836 diag::note_acc_active_clause_here)
1838 }
1839
1840 if (OtherStmtLoc.isValid() && IsActiveTile) {
1841 Diag(OtherStmtLoc, diag::err_acc_intervening_code)
1842 << OpenACCClauseKind::Tile << TileInfo.DirectiveKind;
1843 Diag(TileInfo.ActiveTile->getBeginLoc(),
1844 diag::note_acc_active_clause_here)
1846 }
1847 }
1848}
1849
1850namespace {
1851// Helper that should mirror ActOnRoutineName to get the FunctionDecl out for
1852// magic-static checking.
1853FunctionDecl *getFunctionFromRoutineName(Expr *RoutineName) {
1854 if (!RoutineName)
1855 return nullptr;
1856 RoutineName = RoutineName->IgnoreParenImpCasts();
1857 if (isa<RecoveryExpr>(RoutineName)) {
1858 // There is nothing we can do here, this isn't a function we can count on.
1859 return nullptr;
1861 RoutineName)) {
1862 // The lookup is dependent, so we'll have to figure this out later.
1863 return nullptr;
1864 } else if (auto *DRE = dyn_cast<DeclRefExpr>(RoutineName)) {
1865 ValueDecl *VD = DRE->getDecl();
1866
1867 if (auto *FD = dyn_cast<FunctionDecl>(VD))
1868 return FD;
1869
1870 // Allow lambdas.
1871 if (auto *VarD = dyn_cast<VarDecl>(VD)) {
1872 QualType VarDTy = VarD->getType();
1873 if (!VarDTy.isNull()) {
1874 if (auto *RD = VarDTy->getAsCXXRecordDecl()) {
1875 if (RD->isGenericLambda())
1876 return nullptr;
1877 if (RD->isLambda())
1878 return RD->getLambdaCallOperator();
1879 } else if (VarDTy->isDependentType()) {
1880 // We don't really know what this is going to be.
1881 return nullptr;
1882 }
1883 }
1884 return nullptr;
1885 } else if (isa<OverloadExpr>(RoutineName)) {
1886 return nullptr;
1887 }
1888 }
1889 return nullptr;
1890}
1891} // namespace
1892
1894 assert(RoutineName && "Routine name cannot be null here");
1895 RoutineName = RoutineName->IgnoreParenImpCasts();
1896
1897 if (isa<RecoveryExpr>(RoutineName)) {
1898 // This has already been diagnosed, so we can skip it.
1899 return ExprError();
1901 RoutineName)) {
1902 // These are dependent and we can't really check them, so delay until
1903 // instantiation.
1904 return RoutineName;
1905 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(RoutineName)) {
1906 const ValueDecl *VD = DRE->getDecl();
1907
1908 if (isa<FunctionDecl>(VD))
1909 return RoutineName;
1910
1911 // Allow lambdas.
1912 if (const auto *VarD = dyn_cast<VarDecl>(VD)) {
1913 QualType VarDTy = VarD->getType();
1914 if (!VarDTy.isNull()) {
1915 if (const auto *RD = VarDTy->getAsCXXRecordDecl()) {
1916 if (RD->isGenericLambda()) {
1917 Diag(RoutineName->getBeginLoc(), diag::err_acc_routine_overload_set)
1918 << RoutineName;
1919 return ExprError();
1920 }
1921 if (RD->isLambda())
1922 return RoutineName;
1923 } else if (VarDTy->isDependentType()) {
1924 // If this is a dependent variable, it might be a lambda. So we just
1925 // accept this and catch it next time.
1926 return RoutineName;
1927 }
1928 }
1929 }
1930
1931 Diag(RoutineName->getBeginLoc(), diag::err_acc_routine_not_func)
1932 << RoutineName;
1933 return ExprError();
1934 } else if (isa<OverloadExpr>(RoutineName)) {
1935 // This happens in function templates, even when the template arguments are
1936 // fully specified. We could possibly do some sort of matching to make sure
1937 // that this is looked up/deduced, but GCC does not do this, so there
1938 // doesn't seem to be a good reason for us to do it either.
1939 Diag(RoutineName->getBeginLoc(), diag::err_acc_routine_overload_set)
1940 << RoutineName;
1941 return ExprError();
1942 }
1943
1944 Diag(RoutineName->getBeginLoc(), diag::err_acc_routine_not_func)
1945 << RoutineName;
1946 return ExprError();
1947}
1949 if (!getLangOpts().OpenACC || VD->isInvalidDecl() || !VD->isStaticLocal())
1950 return;
1951
1952 // This cast should be safe, since a static-local can only happen in a
1953 // function declaration. However, in error cases (or perhaps ObjC/C++?), this
1954 // could possibly be something like a 'block' decl, so if this is NOT a
1955 // function decl, just give up.
1956 auto *ContextDecl = dyn_cast<FunctionDecl>(getCurContext());
1957
1958 if (!ContextDecl)
1959 return;
1960
1961 // OpenACC 3.3 2.15:
1962 // In C and C++, function static variables are not supported in functions to
1963 // which a routine directive applies.
1964 for (const auto *A : ContextDecl->attrs()) {
1966 Diag(VD->getBeginLoc(), diag::err_acc_magic_static_in_routine);
1967 Diag(A->getLocation(), diag::note_acc_construct_here)
1969 return;
1970 }
1971 }
1972
1973 MagicStaticLocs.insert({ContextDecl->getCanonicalDecl(), VD->getBeginLoc()});
1974}
1975void SemaOpenACC::CheckLastRoutineDeclNameConflict(const NamedDecl *ND) {
1976 // OpenACC 3.3 A.3.4
1977 // When a procedure with that name is in scope and it is not the same
1978 // procedure as the immediately following procedure declaration or
1979 // definition, the resolution of the name can be confusing. Implementations
1980 // should then issue a compile-time warning diagnostic even though the
1981 // application is conforming.
1982
1983 // If we haven't created one, also can't diagnose.
1984 if (!LastRoutineDecl)
1985 return;
1986
1987 // If the currently created function doesn't have a name, we can't diagnose on
1988 // a match.
1989 if (!ND->getDeclName().isIdentifier())
1990 return;
1991
1992 // If the two are in different decl contexts, it doesn't make sense to
1993 // diagnose.
1994 if (LastRoutineDecl->getDeclContext() != ND->getLexicalDeclContext())
1995 return;
1996
1997 // If we don't have a referenced thing yet, we can't diagnose.
1998 FunctionDecl *RoutineTarget =
1999 getFunctionFromRoutineName(LastRoutineDecl->getFunctionReference());
2000 if (!RoutineTarget)
2001 return;
2002
2003 // If the Routine target doesn't have a name, we can't diagnose.
2004 if (!RoutineTarget->getDeclName().isIdentifier())
2005 return;
2006
2007 // Of course don't diagnose if the names don't match.
2008 if (ND->getName() != RoutineTarget->getName())
2009 return;
2010
2012 long LastLine =
2014
2015 // Do some line-number math to make sure they are within a line of eachother.
2016 // Comments or newlines can be inserted to clarify intent.
2017 if (NDLine - LastLine > 1)
2018 return;
2019
2020 // Don't warn if it actually DOES apply to this function via redecls.
2021 if (ND->getCanonicalDecl() == RoutineTarget->getCanonicalDecl())
2022 return;
2023
2024 Diag(LastRoutineDecl->getFunctionReference()->getBeginLoc(),
2025 diag::warn_acc_confusing_routine_name);
2026 Diag(RoutineTarget->getBeginLoc(), diag::note_previous_decl) << ND;
2027}
2028
2030 if (!VD || !getLangOpts().OpenACC || InitType.isNull())
2031 return;
2032
2033 // To avoid double-diagnostic, just diagnose this during instantiation. We'll
2034 // get 1 warning per instantiation, but this permits us to be more sensible
2035 // for cases where the lookup is confusing.
2037 return;
2038
2039 const auto *RD = InitType->getAsCXXRecordDecl();
2040 // If this isn't a lambda, no sense in diagnosing.
2041 if (!RD || !RD->isLambda())
2042 return;
2043
2044 CheckLastRoutineDeclNameConflict(VD);
2045}
2046
2048 if (!FD || !getLangOpts().OpenACC)
2049 return;
2050 CheckLastRoutineDeclNameConflict(FD);
2051}
2052
2056
2057 // Declaration directives an appear in a statement location, so call into that
2058 // function here.
2060 return ActOnStartDeclDirective(K, StartLoc, Clauses);
2061
2062 SemaRef.DiscardCleanupsInEvaluationContext();
2063 SemaRef.PopExpressionEvaluationContext();
2064
2065 // OpenACC 3.3 2.9.1:
2066 // Intervening code must not contain other OpenACC directives or calls to API
2067 // routines.
2068 //
2069 // ALL constructs are ill-formed if there is an active 'collapse'
2070 if (CollapseInfo.CurCollapseCount && *CollapseInfo.CurCollapseCount > 0) {
2071 Diag(StartLoc, diag::err_acc_invalid_in_loop)
2072 << /*OpenACC Construct*/ 0 << CollapseInfo.DirectiveKind
2074 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
2075 Diag(CollapseInfo.ActiveCollapse->getBeginLoc(),
2076 diag::note_acc_active_clause_here)
2078 }
2079 if (TileInfo.CurTileCount && *TileInfo.CurTileCount > 0) {
2080 Diag(StartLoc, diag::err_acc_invalid_in_loop)
2081 << /*OpenACC Construct*/ 0 << TileInfo.DirectiveKind
2083 assert(TileInfo.ActiveTile && "Tile count without object?");
2084 Diag(TileInfo.ActiveTile->getBeginLoc(), diag::note_acc_active_clause_here)
2086 }
2087
2088 if (DiagnoseRequiredClauses(K, StartLoc, Clauses))
2089 return true;
2090 return diagnoseConstructAppertainment(*this, K, StartLoc, /*IsStmt=*/true);
2091}
2092
2095 SourceLocation LParenLoc, SourceLocation MiscLoc, ArrayRef<Expr *> Exprs,
2096 OpenACCAtomicKind AtomicKind, SourceLocation RParenLoc,
2098 StmtResult AssocStmt) {
2099 switch (K) {
2101 return StmtError();
2105 return OpenACCComputeConstruct::Create(
2106 getASTContext(), K, StartLoc, DirLoc, EndLoc, Clauses,
2107 AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2108 }
2113 getASTContext(), K, StartLoc, DirLoc, EndLoc, Clauses,
2114 AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2115 }
2118 getASTContext(), ActiveComputeConstructInfo.Kind, StartLoc, DirLoc,
2119 EndLoc, Clauses, AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2120 }
2123 getASTContext(), StartLoc, DirLoc, EndLoc, Clauses,
2124 AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2125 }
2127 return OpenACCEnterDataConstruct::Create(getASTContext(), StartLoc, DirLoc,
2128 EndLoc, Clauses);
2129 }
2131 return OpenACCExitDataConstruct::Create(getASTContext(), StartLoc, DirLoc,
2132 EndLoc, Clauses);
2133 }
2136 getASTContext(), StartLoc, DirLoc, EndLoc, Clauses,
2137 AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2138 }
2141 getASTContext(), StartLoc, DirLoc, LParenLoc, Exprs.front(), MiscLoc,
2142 Exprs.drop_front(), RParenLoc, EndLoc, Clauses);
2143 }
2145 return OpenACCInitConstruct::Create(getASTContext(), StartLoc, DirLoc,
2146 EndLoc, Clauses);
2147 }
2149 return OpenACCShutdownConstruct::Create(getASTContext(), StartLoc, DirLoc,
2150 EndLoc, Clauses);
2151 }
2153 return OpenACCSetConstruct::Create(getASTContext(), StartLoc, DirLoc,
2154 EndLoc, Clauses);
2155 }
2157 return OpenACCUpdateConstruct::Create(getASTContext(), StartLoc, DirLoc,
2158 EndLoc, Clauses);
2159 }
2162 getASTContext(), StartLoc, DirLoc, AtomicKind, EndLoc, Clauses,
2163 AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2164 }
2166 assert(Clauses.empty() && "Cache doesn't allow clauses");
2167 return OpenACCCacheConstruct::Create(getASTContext(), StartLoc, DirLoc,
2168 LParenLoc, MiscLoc, Exprs, RParenLoc,
2169 EndLoc);
2170 }
2172 llvm_unreachable("routine shouldn't handled here");
2174 // Declare and routine arei declaration directives, but can be used here as
2175 // long as we wrap it in a DeclStmt. So make sure we do that here.
2176 DeclGroupRef DR = ActOnEndDeclDirective(K, StartLoc, DirLoc, LParenLoc,
2177 RParenLoc, EndLoc, Clauses);
2178
2179 return SemaRef.ActOnDeclStmt(DeclGroupPtrTy::make(DR), StartLoc, EndLoc);
2180 }
2181 }
2182 llvm_unreachable("Unhandled case in directive handling?");
2183}
2184
2186 SourceLocation DirectiveLoc, OpenACCDirectiveKind K,
2188 StmtResult AssocStmt) {
2189 switch (K) {
2190 default:
2191 llvm_unreachable("Unimplemented associated statement application");
2199 llvm_unreachable(
2200 "these don't have associated statements, so shouldn't get here");
2202 return CheckAtomicAssociatedStmt(DirectiveLoc, AtKind, AssocStmt);
2208 // There really isn't any checking here that could happen. As long as we
2209 // have a statement to associate, this should be fine.
2210 // OpenACC 3.3 Section 6:
2211 // Structured Block: in C or C++, an executable statement, possibly
2212 // compound, with a single entry at the top and a single exit at the
2213 // bottom.
2214 // FIXME: Should we reject DeclStmt's here? The standard isn't clear, and
2215 // an interpretation of it is to allow this and treat the initializer as
2216 // the 'structured block'.
2217 return AssocStmt;
2222 if (!AssocStmt.isUsable())
2223 return StmtError();
2224
2225 if (!isa<CXXForRangeStmt, ForStmt>(AssocStmt.get())) {
2226 Diag(AssocStmt.get()->getBeginLoc(), diag::err_acc_loop_not_for_loop)
2227 << K;
2228 Diag(DirectiveLoc, diag::note_acc_construct_here) << K;
2229 return StmtError();
2230 }
2231
2232 if (!CollapseInfo.CollapseDepthSatisfied || !TileInfo.TileDepthSatisfied) {
2233 if (!CollapseInfo.CollapseDepthSatisfied) {
2234 Diag(DirectiveLoc, diag::err_acc_insufficient_loops)
2236 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
2237 Diag(CollapseInfo.ActiveCollapse->getBeginLoc(),
2238 diag::note_acc_active_clause_here)
2240 }
2241
2242 if (!TileInfo.TileDepthSatisfied) {
2243 Diag(DirectiveLoc, diag::err_acc_insufficient_loops)
2245 assert(TileInfo.ActiveTile && "Collapse count without object?");
2246 Diag(TileInfo.ActiveTile->getBeginLoc(),
2247 diag::note_acc_active_clause_here)
2249 }
2250 return StmtError();
2251 }
2252
2253 return AssocStmt.get();
2254 }
2255 llvm_unreachable("Invalid associated statement application");
2256}
2257
2258namespace {
2259
2260// Routine has some pretty complicated set of rules for how device_type
2261// interacts with 'gang', 'worker', 'vector', and 'seq'. Enforce part of it
2262// here.
2263bool CheckValidRoutineGangWorkerVectorSeqClauses(
2264 SemaOpenACC &SemaRef, SourceLocation DirectiveLoc,
2266 auto RequiredPred = llvm::IsaPred<OpenACCGangClause, OpenACCWorkerClause,
2268 // The clause handling has assured us that there is no duplicates. That is,
2269 // if there is 1 before a device_type, there are none after a device_type.
2270 // If not, there is at most 1 applying to each device_type.
2271
2272 // What is left to legalize is that either:
2273 // 1- there is 1 before the first device_type.
2274 // 2- there is 1 AFTER each device_type.
2275 auto *FirstDeviceType =
2276 llvm::find_if(Clauses, llvm::IsaPred<OpenACCDeviceTypeClause>);
2277
2278 // If there is 1 before the first device_type (or at all if no device_type),
2279 // we are legal.
2280 auto *ClauseItr =
2281 std::find_if(Clauses.begin(), FirstDeviceType, RequiredPred);
2282
2283 if (ClauseItr != FirstDeviceType)
2284 return false;
2285
2286 // If there IS no device_type, and no clause, diagnose.
2287 if (FirstDeviceType == Clauses.end())
2288 return SemaRef.Diag(DirectiveLoc, diag::err_acc_construct_one_clause_of)
2290 << "'gang', 'seq', 'vector', or 'worker'";
2291
2292 // Else, we have to check EACH device_type group. PrevDeviceType is the
2293 // device-type before the current group.
2294 auto *PrevDeviceType = FirstDeviceType;
2295
2296 while (PrevDeviceType != Clauses.end()) {
2297 auto *NextDeviceType =
2298 std::find_if(std::next(PrevDeviceType), Clauses.end(),
2299 llvm::IsaPred<OpenACCDeviceTypeClause>);
2300
2301 ClauseItr = std::find_if(PrevDeviceType, NextDeviceType, RequiredPred);
2302
2303 if (ClauseItr == NextDeviceType)
2304 return SemaRef.Diag((*PrevDeviceType)->getBeginLoc(),
2305 diag::err_acc_clause_routine_one_of_in_region);
2306
2307 PrevDeviceType = NextDeviceType;
2308 }
2309
2310 return false;
2311}
2312} // namespace
2313
2317 // OpenCC3.3 2.1 (line 889)
2318 // A program must not depend on the order of evaluation of expressions in
2319 // clause arguments or on any side effects of the evaluations.
2320 SemaRef.DiscardCleanupsInEvaluationContext();
2321 SemaRef.PopExpressionEvaluationContext();
2322
2323 if (DiagnoseRequiredClauses(K, StartLoc, Clauses))
2324 return true;
2326 CheckValidRoutineGangWorkerVectorSeqClauses(*this, StartLoc, Clauses))
2327 return true;
2328
2329 return diagnoseConstructAppertainment(*this, K, StartLoc, /*IsStmt=*/false);
2330}
2331
2334 SourceLocation LParenLoc, SourceLocation RParenLoc, SourceLocation EndLoc,
2335 ArrayRef<OpenACCClause *> Clauses) {
2336 switch (K) {
2337 default:
2339 return DeclGroupRef{};
2341 // OpenACC3.3 2.13: At least one clause must appear on a declare directive.
2342 if (Clauses.empty()) {
2343 Diag(EndLoc, diag::err_acc_declare_required_clauses);
2344 // No reason to add this to the AST, as we would just end up trying to
2345 // instantiate this, which would double-diagnose here, which we wouldn't
2346 // want to do.
2347 return DeclGroupRef{};
2348 }
2349
2350 auto *DeclareDecl = OpenACCDeclareDecl::Create(
2351 getASTContext(), getCurContext(), StartLoc, DirLoc, EndLoc, Clauses);
2352 DeclareDecl->setAccess(AS_public);
2353 getCurContext()->addDecl(DeclareDecl);
2354 return DeclGroupRef{DeclareDecl};
2355 }
2357 llvm_unreachable("routine shouldn't be handled here");
2358 }
2359 llvm_unreachable("unhandled case in directive handling?");
2360}
2361
2362namespace {
2363// Given the decl on the next line, figure out if it is one that is acceptable
2364// to `routine`, or looks like the sort of decl we should be diagnosing against.
2365FunctionDecl *LegalizeNextParsedDecl(Decl *D) {
2366 if (!D)
2367 return nullptr;
2368
2369 // Functions are per-fact acceptable as-is.
2370 if (auto *FD = dyn_cast<FunctionDecl>(D))
2371 return FD;
2372
2373 // Function templates are functions, so attach to the templated decl.
2374 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
2375 return FTD->getTemplatedDecl();
2376
2377 if (auto *FD = dyn_cast<FieldDecl>(D)) {
2378 auto *RD =
2379 FD->getType().isNull() ? nullptr : FD->getType()->getAsCXXRecordDecl();
2380
2381 if (RD && RD->isGenericLambda())
2382 return RD->getDependentLambdaCallOperator()->getTemplatedDecl();
2383 if (RD && RD->isLambda())
2384 return RD->getLambdaCallOperator();
2385 }
2386 // VarDecl we can look at the init instead of the type of the variable, this
2387 // makes us more tolerant of the 'auto' deduced type.
2388 if (auto *VD = dyn_cast<VarDecl>(D)) {
2389 Expr *Init = VD->getInit();
2390 if (!Init || Init->getType().isNull())
2391 return nullptr;
2392
2393 const auto *RD = Init->getType()->getAsCXXRecordDecl();
2394 if (RD && RD->isGenericLambda())
2395 return RD->getDependentLambdaCallOperator()->getTemplatedDecl();
2396 if (RD && RD->isLambda())
2397 return RD->getLambdaCallOperator();
2398
2399 // FIXME: We could try harder in the case where this is a dependent thing
2400 // that ends up being a lambda (that is, the init is an unresolved lookup
2401 // expr), but we can't attach to the call/lookup expr. If we instead try to
2402 // attach to the VarDecl, when we go to instantiate it, attributes are
2403 // instantiated before the init, so we can't actually see the type at any
2404 // point where it would be relevant/able to be checked. We could perhaps do
2405 // some sort of 'after-init' instantiation/checking here, but that doesn't
2406 // seem valuable for a situation that other compilers don't handle.
2407 }
2408 return nullptr;
2409}
2410
2411void CreateRoutineDeclAttr(SemaOpenACC &SemaRef, SourceLocation DirLoc,
2412 ArrayRef<const OpenACCClause *> Clauses,
2413 ValueDecl *AddTo) {
2414 OpenACCRoutineDeclAttr *A =
2415 OpenACCRoutineDeclAttr::Create(SemaRef.getASTContext(), DirLoc);
2416 A->Clauses.assign(Clauses.begin(), Clauses.end());
2417 AddTo->addAttr(A);
2418}
2419} // namespace
2420
2421// Variant that adds attributes, because this is the unnamed case.
2424 Decl *NextParsedDecl) {
2425
2426 FunctionDecl *NextParsedFDecl = LegalizeNextParsedDecl(NextParsedDecl);
2427
2428 if (!NextParsedFDecl) {
2429 // If we don't have a valid 'next thing', just diagnose.
2430 SemaRef.Diag(DirLoc, diag::err_acc_decl_for_routine);
2431 return;
2432 }
2433
2434 // OpenACC 3.3 2.15:
2435 // In C and C++, function static variables are not supported in functions to
2436 // which a routine directive applies.
2437 if (auto Itr = MagicStaticLocs.find(NextParsedFDecl->getCanonicalDecl());
2438 Itr != MagicStaticLocs.end()) {
2439 Diag(Itr->second, diag::err_acc_magic_static_in_routine);
2440 Diag(DirLoc, diag::note_acc_construct_here)
2442
2443 return;
2444 }
2445
2446 auto BindItr = llvm::find_if(Clauses, llvm::IsaPred<OpenACCBindClause>);
2447 if (BindItr != Clauses.end()) {
2448 for (auto *A : NextParsedFDecl->attrs()) {
2449 // OpenACC 3.3 2.15:
2450 // If a procedure has a bind clause on both the declaration and definition
2451 // than they both must bind to the same name.
2452 if (auto *RA = dyn_cast<OpenACCRoutineDeclAttr>(A)) {
2453 auto OtherBindItr =
2454 llvm::find_if(RA->Clauses, llvm::IsaPred<OpenACCBindClause>);
2455 if (OtherBindItr != RA->Clauses.end() &&
2456 (*cast<OpenACCBindClause>(*BindItr)) !=
2457 (*cast<OpenACCBindClause>(*OtherBindItr))) {
2458 Diag((*BindItr)->getBeginLoc(), diag::err_acc_duplicate_unnamed_bind);
2459 Diag((*OtherBindItr)->getEndLoc(),
2460 diag::note_acc_previous_clause_here)
2461 << (*BindItr)->getClauseKind();
2462 return;
2463 }
2464 }
2465
2466 // OpenACC 3.3 2.15:
2467 // A bind clause may not bind to a routine name that has a visible bind
2468 // clause.
2469 // We take the combo of these two 2.15 restrictions to mean that the
2470 // 'declaration'/'definition' quote is an exception to this. So we're
2471 // going to disallow mixing of the two types entirely.
2472 if (auto *RA = dyn_cast<OpenACCRoutineAnnotAttr>(A);
2473 RA && RA->getRange().getEnd().isValid()) {
2474 Diag((*BindItr)->getBeginLoc(), diag::err_acc_duplicate_bind);
2475 Diag(RA->getRange().getEnd(), diag::note_acc_previous_clause_here)
2476 << "bind";
2477 return;
2478 }
2479 }
2480 }
2481
2482 CreateRoutineDeclAttr(*this, DirLoc, Clauses, NextParsedFDecl);
2483}
2484
2485// Variant that adds a decl, because this is the named case.
2487 SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc,
2488 Expr *FuncRef, SourceLocation RParenLoc,
2490 assert(LParenLoc.isValid());
2491
2492 FunctionDecl *FD = nullptr;
2493 if ((FD = getFunctionFromRoutineName(FuncRef))) {
2494 // OpenACC 3.3 2.15:
2495 // In C and C++, function static variables are not supported in functions to
2496 // which a routine directive applies.
2497 if (auto Itr = MagicStaticLocs.find(FD->getCanonicalDecl());
2498 Itr != MagicStaticLocs.end()) {
2499 Diag(Itr->second, diag::err_acc_magic_static_in_routine);
2500 Diag(DirLoc, diag::note_acc_construct_here)
2502
2503 return nullptr;
2504 }
2505
2506 // OpenACC 3.3 2.15:
2507 // A bind clause may not bind to a routine name that has a visible bind
2508 // clause.
2509 auto BindItr = llvm::find_if(Clauses, llvm::IsaPred<OpenACCBindClause>);
2510 SourceLocation BindLoc;
2511 if (BindItr != Clauses.end()) {
2512 BindLoc = (*BindItr)->getBeginLoc();
2513 // Since this is adding a 'named' routine, we aren't allowed to combine
2514 // with ANY other visible bind clause. Error if we see either.
2515
2516 for (auto *A : FD->attrs()) {
2517 if (auto *RA = dyn_cast<OpenACCRoutineDeclAttr>(A)) {
2518 auto OtherBindItr =
2519 llvm::find_if(RA->Clauses, llvm::IsaPred<OpenACCBindClause>);
2520 if (OtherBindItr != RA->Clauses.end()) {
2521 Diag((*BindItr)->getBeginLoc(), diag::err_acc_duplicate_bind);
2522 Diag((*OtherBindItr)->getEndLoc(),
2523 diag::note_acc_previous_clause_here)
2524 << (*BindItr)->getClauseKind();
2525 return nullptr;
2526 }
2527 }
2528
2529 if (auto *RA = dyn_cast<OpenACCRoutineAnnotAttr>(A);
2530 RA && RA->getRange().getEnd().isValid()) {
2531 Diag((*BindItr)->getBeginLoc(), diag::err_acc_duplicate_bind);
2532 Diag(RA->getRange().getEnd(), diag::note_acc_previous_clause_here)
2533 << (*BindItr)->getClauseKind();
2534 return nullptr;
2535 }
2536 }
2537 }
2538
2539 // Set the end-range to the 'bind' clause here, so we can look it up
2540 // later.
2541 auto *RAA = OpenACCRoutineAnnotAttr::CreateImplicit(getASTContext(),
2542 {DirLoc, BindLoc});
2543 FD->addAttr(RAA);
2544 // In case we are referencing not the 'latest' version, make sure we add
2545 // the attribute to all declarations after the 'found' one.
2546 for (auto *CurFD : FD->redecls())
2547 CurFD->addAttr(RAA->clone(getASTContext()));
2548 }
2549
2550 LastRoutineDecl = OpenACCRoutineDecl::Create(
2551 getASTContext(), getCurContext(), StartLoc, DirLoc, LParenLoc, FuncRef,
2552 RParenLoc, EndLoc, Clauses);
2553 LastRoutineDecl->setAccess(AS_public);
2554 getCurContext()->addDecl(LastRoutineDecl);
2555
2556 if (FD) {
2557 // Add this attribute to the list of annotations so that codegen can visit
2558 // it later. FD doesn't necessarily exist, but that case should be
2559 // diagnosed.
2560 RoutineRefList.emplace_back(FD, LastRoutineDecl);
2561 }
2562 return LastRoutineDecl;
2563}
2564
2566 for (auto [FD, RoutineDecl] : RoutineRefList)
2567 SemaRef.Consumer.HandleOpenACCRoutineReference(FD, RoutineDecl);
2568}
2569
2571 SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc,
2572 Expr *ReferencedFunc, SourceLocation RParenLoc,
2574 DeclGroupPtrTy NextDecl) {
2575 assert((!ReferencedFunc || !NextDecl) &&
2576 "Only one of these should be filled");
2577
2578 if (LParenLoc.isInvalid()) {
2579 Decl *NextLineDecl = nullptr;
2580 if (NextDecl && NextDecl.get().isSingleDecl())
2581 NextLineDecl = NextDecl.get().getSingleDecl();
2582
2583 CheckRoutineDecl(DirLoc, Clauses, NextLineDecl);
2584
2585 return NextDecl.get();
2586 }
2587
2589 StartLoc, DirLoc, LParenLoc, ReferencedFunc, RParenLoc, Clauses, EndLoc)};
2590}
2591
2593 SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc,
2594 Expr *ReferencedFunc, SourceLocation RParenLoc,
2596 Stmt *NextStmt) {
2597 assert((!ReferencedFunc || !NextStmt) &&
2598 "Only one of these should be filled");
2599
2600 if (LParenLoc.isInvalid()) {
2601 Decl *NextLineDecl = nullptr;
2602 if (NextStmt)
2603 if (DeclStmt *DS = dyn_cast<DeclStmt>(NextStmt); DS && DS->isSingleDecl())
2604 NextLineDecl = DS->getSingleDecl();
2605
2606 CheckRoutineDecl(DirLoc, Clauses, NextLineDecl);
2607 return NextStmt;
2608 }
2609
2610 DeclGroupRef DR{CheckRoutineDecl(StartLoc, DirLoc, LParenLoc, ReferencedFunc,
2611 RParenLoc, Clauses, EndLoc)};
2612 return SemaRef.ActOnDeclStmt(DeclGroupPtrTy::make(DR), StartLoc, EndLoc);
2613}
2614
2615OpenACCRoutineDeclAttr *
2616SemaOpenACC::mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old) {
2617 OpenACCRoutineDeclAttr *New =
2618 OpenACCRoutineDeclAttr::Create(getASTContext(), Old.getLocation());
2619 // We should jsut be able to copy these, there isn't really any
2620 // merging/inheriting we have to do, so no worry about doing a deep copy.
2621 New->Clauses = Old.Clauses;
2622 return New;
2623}
2628
2633
2634namespace {
2635enum class InitKind { Invalid, Zero, One, AllOnes, Least, Largest };
2636llvm::APFloat getInitFloatValue(ASTContext &Context, InitKind IK, QualType Ty) {
2637 switch (IK) {
2638 case InitKind::Invalid:
2639 llvm_unreachable("invalid init kind");
2640 case InitKind::Zero:
2641 return llvm::APFloat::getZero(Context.getFloatTypeSemantics(Ty));
2642 case InitKind::One:
2643 return llvm::APFloat::getOne(Context.getFloatTypeSemantics(Ty));
2644 case InitKind::AllOnes:
2645 return llvm::APFloat::getAllOnesValue(Context.getFloatTypeSemantics(Ty));
2646 case InitKind::Least:
2647 return llvm::APFloat::getLargest(Context.getFloatTypeSemantics(Ty),
2648 /*Negative=*/true);
2649 case InitKind::Largest:
2650 return llvm::APFloat::getLargest(Context.getFloatTypeSemantics(Ty));
2651 }
2652 llvm_unreachable("unknown init kind");
2653}
2654
2655llvm::APInt getInitIntValue(ASTContext &Context, InitKind IK, QualType Ty) {
2656 switch (IK) {
2657 case InitKind::Invalid:
2658 llvm_unreachable("invalid init kind");
2659 case InitKind::Zero:
2660 return llvm::APInt(Context.getIntWidth(Ty), 0);
2661 case InitKind::One:
2662 return llvm::APInt(Context.getIntWidth(Ty), 1);
2663 case InitKind::AllOnes:
2664 return llvm::APInt::getAllOnes(Context.getIntWidth(Ty));
2665 case InitKind::Least:
2667 return llvm::APInt::getSignedMinValue(Context.getIntWidth(Ty));
2668 return llvm::APInt::getMinValue(Context.getIntWidth(Ty));
2669 case InitKind::Largest:
2671 return llvm::APInt::getSignedMaxValue(Context.getIntWidth(Ty));
2672 return llvm::APInt::getMaxValue(Context.getIntWidth(Ty));
2673 }
2674 llvm_unreachable("unknown init kind");
2675}
2676
2677/// Loops through a type and generates an appropriate InitListExpr to
2678/// generate type initialization.
2679Expr *GenerateReductionInitRecipeExpr(ASTContext &Context,
2680 SourceRange ExprRange, QualType Ty,
2681 InitKind IK) {
2682 if (IK == InitKind::Invalid)
2683 return nullptr;
2684
2685 if (IK == InitKind::Zero) {
2686 Expr *InitExpr =
2687 new (Context) InitListExpr(Context, ExprRange.getBegin(), {},
2688 ExprRange.getEnd(), /*isExplicit=*/false);
2689 InitExpr->setType(Context.VoidTy);
2690 return InitExpr;
2691 }
2692
2693 Ty = Ty.getCanonicalType();
2694 llvm::SmallVector<Expr *> Exprs;
2695
2696 if (const RecordDecl *RD = Ty->getAsRecordDecl()) {
2697 for (auto *F : RD->fields()) {
2698 if (Expr *NewExpr = GenerateReductionInitRecipeExpr(Context, ExprRange,
2699 F->getType(), IK))
2700 Exprs.push_back(NewExpr);
2701 else
2702 return nullptr;
2703 }
2704 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2705 for (uint64_t Idx = 0; Idx < AT->getZExtSize(); ++Idx) {
2706 if (Expr *NewExpr = GenerateReductionInitRecipeExpr(
2707 Context, ExprRange, AT->getElementType(), IK))
2708 Exprs.push_back(NewExpr);
2709 else
2710 return nullptr;
2711 }
2712
2713 } else if (Ty->isPointerType()) {
2714 // For now, we are going to punt/not initialize pointer types, as
2715 // discussions/designs are ongoing on how to express this behavior,
2716 // particularly since they probably need the 'bounds' passed to them
2717 // correctly. A future patch/patch set will go through all of the pointer
2718 // values for all of the recipes to make sure we have a sane behavior.
2719
2720 // For now, this will result in a NYI during code generation for
2721 // no-initializer.
2722 return nullptr;
2723 } else {
2724 assert(Ty->isScalarType() && !Ty->isObjCObjectPointerType() &&
2725 !Ty->isBlockPointerType() && !Ty->isFixedPointType());
2726
2727 if (const auto *Cplx = Ty->getAs<ComplexType>()) {
2728 // we can get here in error cases, so make sure we generate something that
2729 // will work if we find ourselves wanting to enable this, so emit '0,0'
2730 // for both ints and floats.
2731
2732 QualType EltTy = Cplx->getElementType();
2733 if (EltTy->isFloatingType()) {
2734 Exprs.push_back(FloatingLiteral::Create(
2735 Context, getInitFloatValue(Context, InitKind::Zero, EltTy),
2736 /*isExact=*/true, EltTy, ExprRange.getBegin()));
2737 Exprs.push_back(FloatingLiteral::Create(
2738 Context, getInitFloatValue(Context, InitKind::Zero, EltTy),
2739 /*isExact=*/true, EltTy, ExprRange.getBegin()));
2740 } else {
2741 Exprs.push_back(IntegerLiteral::Create(
2742 Context, getInitIntValue(Context, InitKind::Zero, EltTy), EltTy,
2743 ExprRange.getBegin()));
2744 Exprs.push_back(IntegerLiteral::Create(
2745 Context, getInitIntValue(Context, InitKind::Zero, EltTy), EltTy,
2746 ExprRange.getBegin()));
2747 }
2748
2749 } else if (Ty->isFloatingType()) {
2750 Exprs.push_back(
2751 FloatingLiteral::Create(Context, getInitFloatValue(Context, IK, Ty),
2752 /*isExact=*/true, Ty, ExprRange.getBegin()));
2753 } else if (Ty->isBooleanType()) {
2754 Exprs.push_back(CXXBoolLiteralExpr::Create(Context,
2755 (IK == InitKind::One ||
2756 IK == InitKind::AllOnes ||
2757 IK == InitKind::Largest),
2758 Ty, ExprRange.getBegin()));
2759 } else if (Ty->isNullPtrType()) {
2760 Exprs.push_back(new (Context)
2761 CXXNullPtrLiteralExpr(Ty, ExprRange.getBegin()));
2762 } else {
2763 Exprs.push_back(IntegerLiteral::Create(
2764 Context, getInitIntValue(Context, IK, Ty), Ty, ExprRange.getBegin()));
2765 }
2766 }
2767
2768 Expr *InitExpr =
2769 new (Context) InitListExpr(Context, ExprRange.getBegin(), Exprs,
2770 ExprRange.getEnd(), /*isExplicit=*/false);
2771 InitExpr->setType(Ty);
2772 return InitExpr;
2773}
2774
2775VarDecl *CreateAllocaDecl(ASTContext &Ctx, DeclContext *DC,
2776 SourceLocation BeginLoc, IdentifierInfo *VarName,
2777 QualType VarTy) {
2778 auto *VD = VarDecl::Create(Ctx, DC, BeginLoc, BeginLoc, VarName, VarTy,
2779 Ctx.getTrivialTypeSourceInfo(VarTy), SC_Auto);
2780 VD->markUsed(Ctx);
2781 return VD;
2782}
2783
2784ExprResult FinishValueInit(Sema &S, InitializedEntity &Entity,
2785 SourceLocation Loc, QualType VarTy, Expr *InitExpr) {
2786 if (!InitExpr)
2787 return ExprEmpty();
2788
2789 InitializationKind Kind =
2790 InitializationKind::CreateForInit(Loc, /*DirectInit=*/true, InitExpr);
2791 InitializationSequence InitSeq(S, Entity, Kind, InitExpr,
2792 /*TopLevelOfInitList=*/false,
2793 /*TreatUnavailableAsInvalid=*/false);
2794
2795 return InitSeq.Perform(S, Entity, Kind, InitExpr, &VarTy);
2796}
2797
2798} // namespace
2799
2801 // We don't strip bounds here, so that we are doing our recipe init at the
2802 // 'lowest' possible level. Codegen is going to have to do its own 'looping'.
2803 if (!VarExpr || VarExpr->getType()->isDependentType())
2805
2806 QualType VarTy =
2808
2809 // Array sections are special, and we have to treat them that way.
2810 if (const auto *ASE =
2811 dyn_cast<ArraySectionExpr>(VarExpr->IgnoreParenImpCasts()))
2812 VarTy = ASE->getElementType();
2813
2814 VarDecl *AllocaDecl = CreateAllocaDecl(
2815 getASTContext(), SemaRef.getCurContext(), VarExpr->getBeginLoc(),
2816 &getASTContext().Idents.get("openacc.private.init"), VarTy);
2817
2820 InitializationKind Kind =
2822 InitializationSequence InitSeq(SemaRef.SemaRef, Entity, Kind, {});
2823 ExprResult Init = InitSeq.Perform(SemaRef.SemaRef, Entity, Kind, {});
2824
2825 // For 'no bounds' version, we can use this as a shortcut, so set the init
2826 // anyway.
2827 if (Init.isUsable()) {
2828 AllocaDecl->setInit(Init.get());
2829 AllocaDecl->setInitStyle(VarDecl::CallInit);
2830 }
2831
2832 return OpenACCPrivateRecipe(AllocaDecl);
2833}
2834
2837 // We don't strip bounds here, so that we are doing our recipe init at the
2838 // 'lowest' possible level. Codegen is going to have to do its own 'looping'.
2839 if (!VarExpr || VarExpr->getType()->isDependentType())
2841
2842 QualType VarTy =
2844
2845 // Array sections are special, and we have to treat them that way.
2846 if (const auto *ASE =
2847 dyn_cast<ArraySectionExpr>(VarExpr->IgnoreParenImpCasts()))
2848 VarTy = ASE->getElementType();
2849
2850 VarDecl *AllocaDecl = CreateAllocaDecl(
2851 getASTContext(), SemaRef.getCurContext(), VarExpr->getBeginLoc(),
2852 &getASTContext().Idents.get("openacc.firstprivate.init"), VarTy);
2853
2854 VarDecl *Temporary = CreateAllocaDecl(
2855 getASTContext(), SemaRef.getCurContext(), VarExpr->getBeginLoc(),
2856 &getASTContext().Idents.get("openacc.temp"), VarTy);
2857
2858 auto *TemporaryDRE = DeclRefExpr::Create(
2860 /*ReferstoEnclosingVariableOrCapture=*/false,
2862 VarExpr->getBeginLoc()},
2863 VarTy, clang::VK_LValue, Temporary, nullptr, NOUR_None);
2864
2867
2868 const auto *ArrTy = getASTContext().getAsConstantArrayType(VarTy);
2869 if (!ArrTy) {
2870 ExprResult Init = FinishValueInit(
2871 SemaRef.SemaRef, Entity, VarExpr->getBeginLoc(), VarTy, TemporaryDRE);
2872
2873 // For 'no bounds' version, we can use this as a shortcut, so set the init
2874 // anyway.
2875 if (Init.isUsable()) {
2876 AllocaDecl->setInit(Init.get());
2877 AllocaDecl->setInitStyle(VarDecl::CallInit);
2878 }
2879 return OpenACCFirstPrivateRecipe(AllocaDecl, Temporary);
2880 }
2881
2882 // Arrays need to have each individual element initialized as there
2883 // isn't a normal 'equals' feature in C/C++. This section sets these up
2884 // as an init list after 'initializing' each individual element.
2886 // Decay to pointer for the array subscript expression.
2887 auto *CastToPtr = ImplicitCastExpr::Create(
2888 getASTContext(), getASTContext().getPointerType(ArrTy->getElementType()),
2889 CK_ArrayToPointerDecay, TemporaryDRE, /*BasePath=*/nullptr,
2891
2892 for (std::size_t I = 0; I < ArrTy->getLimitedSize(); ++I) {
2893 // Each element needs to be some sort of copy initialization from an
2894 // array-index of the original temporary (referenced via a
2895 // DeclRefExpr).
2896 auto *Idx = IntegerLiteral::Create(
2897 getASTContext(),
2898 llvm::APInt(getASTContext().getTypeSize(getASTContext().getSizeType()),
2899 I),
2900 getASTContext().getSizeType(), VarExpr->getBeginLoc());
2901
2902 Expr *Subscript = new (getASTContext()) ArraySubscriptExpr(
2903 CastToPtr, Idx, ArrTy->getElementType(), clang::VK_LValue, OK_Ordinary,
2904 VarExpr->getBeginLoc());
2905 // Generate a simple copy from the result of the subscript. This will
2906 // do a bitwise copy or a copy-constructor, as necessary.
2907 InitializedEntity CopyEntity =
2909 InitializationKind CopyKind =
2911 InitializationSequence CopySeq(SemaRef.SemaRef, CopyEntity, CopyKind,
2912 Subscript,
2913 /*TopLevelOfInitList=*/true);
2914 ExprResult ElemRes =
2915 CopySeq.Perform(SemaRef.SemaRef, CopyEntity, CopyKind, Subscript);
2916 Args.push_back(ElemRes.get());
2917 }
2918
2919 Expr *InitExpr = new (getASTContext())
2920 InitListExpr(getASTContext(), VarExpr->getBeginLoc(), Args,
2921 VarExpr->getEndLoc(), /*isExplicit=*/false);
2922 InitExpr->setType(VarTy);
2923
2924 ExprResult Init = FinishValueInit(SemaRef.SemaRef, Entity,
2925 VarExpr->getBeginLoc(), VarTy, InitExpr);
2926
2927 // For 'no bounds' version, we can use this as a shortcut, so set the init
2928 // anyway.
2929 if (Init.isUsable()) {
2930 AllocaDecl->setInit(Init.get());
2931 AllocaDecl->setInitStyle(VarDecl::CallInit);
2932 }
2933
2934 return OpenACCFirstPrivateRecipe(AllocaDecl, Temporary);
2935}
2936
2938 OpenACCReductionOperator ReductionOperator, const Expr *VarExpr) {
2939 // We don't strip bounds here, so that we are doing our recipe init at the
2940 // 'lowest' possible level. Codegen is going to have to do its own 'looping'.
2941 if (!VarExpr || VarExpr->getType()->isDependentType())
2943
2944 QualType VarTy =
2946
2947 // Array sections are special, and we have to treat them that way.
2948 if (const auto *ASE =
2949 dyn_cast<ArraySectionExpr>(VarExpr->IgnoreParenImpCasts()))
2950 VarTy = ASE->getElementType();
2951
2953
2954 // We use the 'set-ness' of the alloca-decl to determine whether the combiner
2955 // is 'set' or not, so we can skip any attempts at it if we're going to fail
2956 // at any of the combiners.
2957 if (CreateReductionCombinerRecipe(VarExpr->getBeginLoc(), ReductionOperator,
2958 VarTy, CombinerRecipes))
2960
2961 VarDecl *AllocaDecl = CreateAllocaDecl(
2962 getASTContext(), SemaRef.getCurContext(), VarExpr->getBeginLoc(),
2963 &getASTContext().Idents.get("openacc.reduction.init"), VarTy);
2964
2967
2968 InitKind IK = InitKind::Invalid;
2969 switch (ReductionOperator) {
2971 // This can only happen when there is an error, and since these inits
2972 // are used for code generation, we can just ignore/not bother doing any
2973 // initialization here.
2974 IK = InitKind::Invalid;
2975 break;
2977 IK = InitKind::Least;
2978 break;
2980 IK = InitKind::Largest;
2981 break;
2983 IK = InitKind::AllOnes;
2984 break;
2987 IK = InitKind::One;
2988 break;
2993 IK = InitKind::Zero;
2994 break;
2995 }
2996
2997 Expr *InitExpr = GenerateReductionInitRecipeExpr(
2998 getASTContext(), VarExpr->getSourceRange(), VarTy, IK);
2999
3000 ExprResult Init = FinishValueInit(SemaRef.SemaRef, Entity,
3001 VarExpr->getBeginLoc(), VarTy, InitExpr);
3002
3003 // For 'no bounds' version, we can use this as a shortcut, so set the init
3004 // anyway.
3005 if (Init.isUsable()) {
3006 AllocaDecl->setInit(Init.get());
3007 AllocaDecl->setInitStyle(VarDecl::CallInit);
3008 }
3009
3010 return OpenACCReductionRecipeWithStorage(AllocaDecl, CombinerRecipes);
3011}
3012
3013bool SemaOpenACC::CreateReductionCombinerRecipe(
3014 SourceLocation Loc, OpenACCReductionOperator ReductionOperator,
3015 QualType VarTy,
3017 &CombinerRecipes) {
3018 // Now we can try to generate the 'combiner' recipe. This is a little
3019 // complicated in that if the 'VarTy' is an array type, we want to take its
3020 // element type so we can generate that. Additionally, if this is a struct,
3021 // we have two options: If there is overloaded operators, we want to take
3022 // THOSE, else we want to do the individual elements.
3023
3024 BinaryOperatorKind BinOp;
3025 switch (ReductionOperator) {
3027 // This can only happen when there is an error, and since these inits
3028 // are used for code generation, we can just ignore/not bother doing any
3029 // initialization here.
3030 CombinerRecipes.push_back({nullptr, nullptr, nullptr});
3031 return false;
3033 BinOp = BinaryOperatorKind::BO_AddAssign;
3034 break;
3036 BinOp = BinaryOperatorKind::BO_MulAssign;
3037 break;
3039 BinOp = BinaryOperatorKind::BO_AndAssign;
3040 break;
3042 BinOp = BinaryOperatorKind::BO_OrAssign;
3043 break;
3045 BinOp = BinaryOperatorKind::BO_XorAssign;
3046 break;
3047
3050 BinOp = BinaryOperatorKind::BO_LT;
3051 break;
3053 BinOp = BinaryOperatorKind::BO_LAnd;
3054 break;
3056 BinOp = BinaryOperatorKind::BO_LOr;
3057 break;
3058 }
3059
3060 // If VarTy is an array type, at the top level only, we want to do our
3061 // compares/decomp/etc at the element level.
3062 if (auto *AT = getASTContext().getAsArrayType(VarTy))
3063 VarTy = AT->getElementType();
3064
3065 assert(!VarTy->isArrayType() && "Only 1 level of array allowed");
3066
3067 enum class CombinerFailureKind {
3068 None = 0,
3069 BinOp = 1,
3070 Conditional = 2,
3071 Assignment = 3,
3072 };
3073
3074 auto genCombiner = [&, this](DeclRefExpr *LHSDRE, DeclRefExpr *RHSDRE)
3075 -> std::pair<ExprResult, CombinerFailureKind> {
3076 ExprResult BinOpRes =
3077 SemaRef.BuildBinOp(SemaRef.getCurScope(), Loc, BinOp, LHSDRE, RHSDRE,
3078 /*ForFoldExpr=*/false);
3079 switch (ReductionOperator) {
3085 // These 5 are simple and are being done as compound operators, so we can
3086 // immediately quit here.
3087 return {BinOpRes, BinOpRes.isUsable() ? CombinerFailureKind::None
3088 : CombinerFailureKind::BinOp};
3091 // These are done as:
3092 // LHS = (LHS < RHS) ? LHS : RHS; and LHS = (LHS < RHS) ? RHS : LHS;
3093 //
3094 // The BinOpRes should have been created with the less-than, so we just
3095 // have to build the conditional and assignment.
3096 if (!BinOpRes.isUsable())
3097 return {BinOpRes, CombinerFailureKind::BinOp};
3098
3099 // Create the correct conditional operator, swapping the results
3100 // (true/false value) depending on min/max.
3101 ExprResult CondRes;
3102 if (ReductionOperator == OpenACCReductionOperator::Min)
3103 CondRes = SemaRef.ActOnConditionalOp(Loc, Loc, BinOpRes.get(), LHSDRE,
3104 RHSDRE);
3105 else
3106 CondRes = SemaRef.ActOnConditionalOp(Loc, Loc, BinOpRes.get(), RHSDRE,
3107 LHSDRE);
3108
3109 if (!CondRes.isUsable())
3110 return {CondRes, CombinerFailureKind::Conditional};
3111
3112 // Build assignment.
3113 ExprResult Assignment = SemaRef.BuildBinOp(SemaRef.getCurScope(), Loc,
3114 BinaryOperatorKind::BO_Assign,
3115 LHSDRE, CondRes.get(),
3116 /*ForFoldExpr=*/false);
3117 return {Assignment, Assignment.isUsable()
3118 ? CombinerFailureKind::None
3119 : CombinerFailureKind::Assignment};
3120 }
3123 // These are done as LHS = LHS && RHS (or LHS = LHS || RHS). So after the
3124 // binop, all we have to do is the assignment.
3125 if (!BinOpRes.isUsable())
3126 return {BinOpRes, CombinerFailureKind::BinOp};
3127
3128 // Build assignment.
3129 ExprResult Assignment = SemaRef.BuildBinOp(SemaRef.getCurScope(), Loc,
3130 BinaryOperatorKind::BO_Assign,
3131 LHSDRE, BinOpRes.get(),
3132 /*ForFoldExpr=*/false);
3133 return {Assignment, Assignment.isUsable()
3134 ? CombinerFailureKind::None
3135 : CombinerFailureKind::Assignment};
3136 }
3138 llvm_unreachable("Invalid should have been caught above");
3139 }
3140 llvm_unreachable("Unhandled case");
3141 };
3142
3143 auto tryCombiner = [&, this](DeclRefExpr *LHSDRE, DeclRefExpr *RHSDRE,
3144 bool IncludeTrap) {
3145 if (IncludeTrap) {
3146 // Trap all of the errors here, we'll emit our own at the end.
3147 Sema::TentativeAnalysisScope Trap{SemaRef};
3148 return genCombiner(LHSDRE, RHSDRE);
3149 }
3150 return genCombiner(LHSDRE, RHSDRE);
3151 };
3152
3153 struct CombinerAttemptTy {
3154 CombinerFailureKind FailKind;
3155 VarDecl *LHS;
3156 DeclRefExpr *LHSDRE;
3157 VarDecl *RHS;
3158 DeclRefExpr *RHSDRE;
3159 Expr *Op;
3160 };
3161
3162 auto formCombiner = [&, this](QualType Ty) -> CombinerAttemptTy {
3163 VarDecl *LHSDecl = CreateAllocaDecl(
3164 getASTContext(), SemaRef.getCurContext(), Loc,
3165 &getASTContext().Idents.get("openacc.reduction.combiner.lhs"), Ty);
3166 auto *LHSDRE = DeclRefExpr::Create(
3167 getASTContext(), NestedNameSpecifierLoc{}, SourceLocation{}, LHSDecl,
3168 /*ReferstoEnclosingVariableOrCapture=*/false,
3169 DeclarationNameInfo{DeclarationName{LHSDecl->getDeclName()},
3170 LHSDecl->getBeginLoc()},
3171 Ty, clang::VK_LValue, LHSDecl, nullptr, NOUR_None);
3172 VarDecl *RHSDecl = CreateAllocaDecl(
3173 getASTContext(), SemaRef.getCurContext(), Loc,
3174 &getASTContext().Idents.get("openacc.reduction.combiner.lhs"), Ty);
3175 auto *RHSDRE = DeclRefExpr::Create(
3176 getASTContext(), NestedNameSpecifierLoc{}, SourceLocation{}, RHSDecl,
3177 /*ReferstoEnclosingVariableOrCapture=*/false,
3178 DeclarationNameInfo{DeclarationName{RHSDecl->getDeclName()},
3179 RHSDecl->getBeginLoc()},
3180 Ty, clang::VK_LValue, RHSDecl, nullptr, NOUR_None);
3181
3182 std::pair<ExprResult, CombinerFailureKind> BinOpResult =
3183 tryCombiner(LHSDRE, RHSDRE, /*IncludeTrap=*/true);
3184
3185 return {BinOpResult.second, LHSDecl, LHSDRE, RHSDecl, RHSDRE,
3186 BinOpResult.first.get()};
3187 };
3188
3189 CombinerAttemptTy TopLevelCombinerInfo = formCombiner(VarTy);
3190
3191 if (TopLevelCombinerInfo.Op) {
3192 if (!TopLevelCombinerInfo.Op->containsErrors() &&
3193 TopLevelCombinerInfo.Op->isInstantiationDependent()) {
3194 // If this is instantiation dependent, we're just going to 'give up' here
3195 // and count on us to get it right during instantaition.
3196 CombinerRecipes.push_back({nullptr, nullptr, nullptr});
3197 return false;
3198 } else if (!TopLevelCombinerInfo.Op->containsErrors()) {
3199 // Else, we succeeded, we can just return this combiner.
3200 CombinerRecipes.push_back({TopLevelCombinerInfo.LHS,
3201 TopLevelCombinerInfo.RHS,
3202 TopLevelCombinerInfo.Op});
3203 return false;
3204 }
3205 }
3206
3207 auto EmitFailureNote = [&](CombinerFailureKind CFK) {
3208 if (CFK == CombinerFailureKind::BinOp)
3209 return Diag(Loc, diag::note_acc_reduction_combiner_forming)
3210 << CFK << BinaryOperator::getOpcodeStr(BinOp);
3211 return Diag(Loc, diag::note_acc_reduction_combiner_forming) << CFK;
3212 };
3213
3214 // Since the 'root' level didn't fail, the only thing that could be successful
3215 // is a struct that we decompose on its individual fields.
3216
3217 RecordDecl *RD = VarTy->getAsRecordDecl();
3218 if (!RD) {
3219 Diag(Loc, diag::err_acc_reduction_recipe_no_op) << VarTy;
3220 EmitFailureNote(TopLevelCombinerInfo.FailKind);
3221 tryCombiner(TopLevelCombinerInfo.LHSDRE, TopLevelCombinerInfo.RHSDRE,
3222 /*IncludeTrap=*/false);
3223 return true;
3224 }
3225
3226 for (const FieldDecl *FD : RD->fields()) {
3227 CombinerAttemptTy FieldCombinerInfo = formCombiner(FD->getType());
3228
3229 if (!FieldCombinerInfo.Op || FieldCombinerInfo.Op->containsErrors()) {
3230 Diag(Loc, diag::err_acc_reduction_recipe_no_op) << FD->getType();
3231 Diag(FD->getBeginLoc(), diag::note_acc_reduction_recipe_noop_field) << RD;
3232 EmitFailureNote(FieldCombinerInfo.FailKind);
3233 tryCombiner(FieldCombinerInfo.LHSDRE, FieldCombinerInfo.RHSDRE,
3234 /*IncludeTrap=*/false);
3235 return true;
3236 }
3237
3238 if (FieldCombinerInfo.Op->isInstantiationDependent()) {
3239 // If this is instantiation dependent, we're just going to 'give up' here
3240 // and count on us to get it right during instantaition.
3241 CombinerRecipes.push_back({nullptr, nullptr, nullptr});
3242 } else {
3243 CombinerRecipes.push_back(
3244 {FieldCombinerInfo.LHS, FieldCombinerInfo.RHS, FieldCombinerInfo.Op});
3245 }
3246 }
3247
3248 return false;
3249}
This file defines OpenACC nodes for declarative directives.
Defines some OpenACC-specific enums and functions.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for OpenACC constructs and clauses.
Defines the SourceManager interface.
This file defines OpenACC AST classes for statement-level contructs.
static OpenACCAtomicConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, OpenACCAtomicKind AtKind, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses, Stmt *AssociatedStmt)
static OpenACCCacheConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation LParenLoc, SourceLocation ReadOnlyLoc, ArrayRef< Expr * > VarList, SourceLocation RParenLoc, SourceLocation End)
static OpenACCCombinedConstruct * Create(const ASTContext &C, OpenACCDirectiveKind K, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses, Stmt *StructuredBlock)
static OpenACCDataConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses, Stmt *StructuredBlock)
static OpenACCEnterDataConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCExitDataConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCHostDataConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses, Stmt *StructuredBlock)
static OpenACCInitConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCLoopConstruct * Create(const ASTContext &C, OpenACCDirectiveKind ParentKind, SourceLocation BeginLoc, SourceLocation DirLoc, SourceLocation EndLoc, ArrayRef< const OpenACCClause * > Clauses, Stmt *Loop)
static OpenACCSetConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCShutdownConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCUpdateConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCWaitConstruct * Create(const ASTContext &C, SourceLocation Start, SourceLocation DirectiveLoc, SourceLocation LParenLoc, Expr *DevNumExpr, SourceLocation QueuesLoc, ArrayRef< Expr * > QueueIdExprs, SourceLocation RParenLoc, SourceLocation End, ArrayRef< const OpenACCClause * > Clauses)
a trap message and trap category.
APSInt & getInt()
Definition APValue.h:573
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
unsigned getIntWidth(QualType T) const
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType VoidTy
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
This class represents BOTH the OpenMP Array Section and OpenACC 'subarray', with a boolean differenti...
Definition Expr.h:7305
static QualType getBaseOriginalType(const Expr *Base)
Return original type of the base expression for array section.
Definition Expr.cpp:5442
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
QualType getElementType() const
Definition TypeBase.h:3832
StringRef getOpcodeStr() const
Definition Expr.h:4173
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition ExprCXX.h:740
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2994
base_class_range bases()
Definition DeclCXX.h:609
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
void addDecl(Decl *D)
Add the declaration D into this context.
Decl * getSingleDecl()
Definition DeclGroup.h:79
bool isSingleDecl() const
Definition DeclGroup.h:76
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1655
const Decl * getSingleDecl() const
Definition Stmt.h:1657
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void addAttr(Attr *A)
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:594
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
DeclContext * getDeclContext()
Definition DeclBase.h:457
attr_range attrs() const
Definition DeclBase.h:544
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclBase.h:440
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:936
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:996
The name of a declaration.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
This represents one expression.
Definition Expr.h:114
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
void setType(QualType t)
Definition Expr.h:147
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:196
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3129
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:225
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:528
Represents difference between two FPOptions values.
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition Expr.cpp:1086
Represents a function declaration or definition.
Definition Decl.h:2082
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3820
bool isDeleted() const
Whether this function has been deleted.
Definition Decl.h:2709
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
Describes an C or C++ initializer list.
Definition Expr.h:5377
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
Describes the sequence of initializations required to initialize a given object or reference with a s...
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeElement(ASTContext &Context, unsigned Index, const InitializedEntity &Parent)
Create the initialization entity for an array element.
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:985
This represents a decl that may have a name.
Definition Decl.h:276
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
A C++ nested-name-specifier augmented with source location information.
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(DeclGroupRef P)
Definition Ownership.h:61
static OpenACCAsteriskSizeExpr * Create(const ASTContext &C, SourceLocation Loc)
Definition Expr.cpp:5714
SourceLocation getBeginLoc() const
Represents a 'collapse' clause on a 'loop' construct.
const Expr * getLoopCount() const
static OpenACCDeclareDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation EndLoc, ArrayRef< const OpenACCClause * > Clauses)
static OpenACCRoutineDecl * Create(ASTContext &Ctx, DeclContext *DC, SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc, Expr *FuncRef, SourceLocation RParenLoc, SourceLocation EndLoc, ArrayRef< const OpenACCClause * > Clauses)
const Expr * getFunctionReference() const
ArrayRef< Expr * > getSizeExprs() const
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
QualType getCanonicalType() const
Definition TypeBase.h:8630
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
field_range fields() const
Definition Decl.h:4709
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
unsigned getDepth() const
Returns the depth of this scope. The translation-unit has scope depth 0.
Definition Scope.h:325
bool isOpenACCLoopConstructScope() const
Definition Scope.h:554
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:120
SemaBase(Sema &S)
Definition SemaBase.cpp:7
ASTContext & getASTContext() const
Definition SemaBase.cpp:9
Sema & SemaRef
Definition SemaBase.h:49
const LangOptions & getLangOpts() const
Definition SemaBase.cpp:11
DeclContext * getCurContext() const
Definition SemaBase.cpp:12
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
AssociatedStmtRAII(SemaOpenACC &, OpenACCDirectiveKind, SourceLocation, ArrayRef< const OpenACCClause * >, ArrayRef< OpenACCClause * >)
void SetTileInfoBeforeAssociatedStmt(ArrayRef< const OpenACCClause * > UnInstClauses, ArrayRef< OpenACCClause * > Clauses)
void SetCollapseInfoBeforeAssociatedStmt(ArrayRef< const OpenACCClause * > UnInstClauses, ArrayRef< OpenACCClause * > Clauses)
ExprResult ActOnRoutineName(Expr *RoutineName)
OpenACCPrivateRecipe CreatePrivateInitRecipe(const Expr *VarExpr)
bool ActOnStartDeclDirective(OpenACCDirectiveKind K, SourceLocation StartLoc, ArrayRef< const OpenACCClause * > Clauses)
Called after the directive, including its clauses, have been parsed and parsing has consumed the 'ann...
bool ActOnStartStmtDirective(OpenACCDirectiveKind K, SourceLocation StartLoc, ArrayRef< const OpenACCClause * > Clauses)
Called after the directive, including its clauses, have been parsed and parsing has consumed the 'ann...
ExprResult BuildOpenACCAsteriskSizeExpr(SourceLocation AsteriskLoc)
ExprResult ActOnIntExpr(OpenACCDirectiveKind DK, OpenACCClauseKind CK, SourceLocation Loc, Expr *IntExpr)
Called when encountering an 'int-expr' for OpenACC, and manages conversions and diagnostics to 'int'.
void ActOnVariableDeclarator(VarDecl *VD)
Function called when a variable declarator is created, which lets us implement the 'routine' 'functio...
void ActOnWhileStmt(SourceLocation WhileLoc)
SourceLocation LoopWorkerClauseLoc
If there is a current 'active' loop construct with a 'worker' clause on it (on any sort of construct)...
DeclGroupRef ActOnEndRoutineDeclDirective(SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc, Expr *ReferencedFunc, SourceLocation RParenLoc, ArrayRef< const OpenACCClause * > Clauses, SourceLocation EndLoc, DeclGroupPtrTy NextDecl)
void ActOnInvalidParseVar()
Called only if the parse of a 'var' was invalid, else 'ActOnVar' should be called.
void CheckRoutineDecl(SourceLocation DirLoc, ArrayRef< const OpenACCClause * > Clauses, Decl *NextParsedDecl)
void ActOnEndOfTranslationUnit(TranslationUnitDecl *TU)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition SemaOpenACC.h:39
bool CheckVarIsPointerType(OpenACCClauseKind ClauseKind, Expr *VarExpr)
Called to check the 'var' type is a variable of pointer type, necessary for 'deviceptr' and 'attach' ...
struct clang::SemaOpenACC::LoopGangOnKernelTy LoopGangClauseOnKernel
StmtResult ActOnEndRoutineStmtDirective(SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc, Expr *ReferencedFunc, SourceLocation RParenLoc, ArrayRef< const OpenACCClause * > Clauses, SourceLocation EndLoc, Stmt *NextStmt)
void CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D)
StmtResult ActOnAssociatedStmt(SourceLocation DirectiveLoc, OpenACCDirectiveKind K, OpenACCAtomicKind AtKind, ArrayRef< const OpenACCClause * > Clauses, StmtResult AssocStmt)
Called when we encounter an associated statement for our construct, this should check legality of the...
OpenACCRoutineDeclAttr * mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old)
void ActOnFunctionDeclarator(FunctionDecl *FD)
Called when a function decl is created, which lets us implement the 'routine' 'doesn't match next thi...
ExprResult ActOnCacheVar(Expr *VarExpr)
Helper function called by ActonVar that is used to check a 'cache' var.
struct clang::SemaOpenACC::LoopWithoutSeqCheckingInfo LoopWithoutSeqInfo
DeclGroupRef ActOnEndDeclDirective(OpenACCDirectiveKind K, SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, SourceLocation EndLoc, ArrayRef< OpenACCClause * > Clauses)
Called after the directive has been completely parsed, including the declaration group or associated ...
SourceLocation LoopVectorClauseLoc
If there is a current 'active' loop construct with a 'vector' clause on it (on any sort of construct)...
ExprResult ActOnVar(OpenACCDirectiveKind DK, OpenACCClauseKind CK, Expr *VarExpr)
Called when encountering a 'var' for OpenACC, ensures it is actually a declaration reference to a var...
void ActOnConstruct(OpenACCDirectiveKind K, SourceLocation DirLoc)
Called after the construct has been parsed, but clauses haven't been parsed.
ExprResult ActOnOpenACCAsteriskSizeExpr(SourceLocation AsteriskLoc)
void ActOnDoStmt(SourceLocation DoLoc)
void ActOnVariableInit(VarDecl *VD, QualType InitType)
Called when a variable is initialized, so we can implement the 'routine 'doesn't match the next thing...
void ActOnRangeForStmtBegin(SourceLocation ForLoc, const Stmt *OldRangeFor, const Stmt *RangeFor)
void ActOnStartParseVar(OpenACCDirectiveKind DK, OpenACCClauseKind CK)
Called right before a 'var' is parsed, so we can set the state for parsing a 'cache' var.
OpenACCFirstPrivateRecipe CreateFirstPrivateInitRecipe(const Expr *VarExpr)
StmtResult ActOnEndStmtDirective(OpenACCDirectiveKind K, SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc, SourceLocation MiscLoc, ArrayRef< Expr * > Exprs, OpenACCAtomicKind AK, SourceLocation RParenLoc, SourceLocation EndLoc, ArrayRef< OpenACCClause * > Clauses, StmtResult AssocStmt)
Called after the directive has been completely parsed, including the declaration group or associated ...
void ActOnForStmtEnd(SourceLocation ForLoc, StmtResult Body)
StmtResult CheckAtomicAssociatedStmt(SourceLocation AtomicDirLoc, OpenACCAtomicKind AtKind, StmtResult AssocStmt)
Called to check the form of the atomic construct which has some fairly sizable restrictions.
void ActOnForStmtBegin(SourceLocation ForLoc, const Stmt *First, const Stmt *Second, const Stmt *Third)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
OpenACCReductionRecipeWithStorage CreateReductionInitRecipe(OpenACCReductionOperator ReductionOperator, const Expr *VarExpr)
CXXMethodDecl * getMethod() const
Definition Sema.h:9515
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12764
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
@ Normal
Apply the normal rules for complete types.
Definition Sema.h:15421
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6927
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
SourceManager & SourceMgr
Definition Sema.h:1334
SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMemberKind SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis)
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3999
The top declaration context.
Definition Decl.h:107
bool isDependentSizedArrayType() const
Definition TypeBase.h:8934
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isBooleanType() const
Definition TypeBase.h:9341
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2415
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8918
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8914
bool isPointerType() const
Definition TypeBase.h:8815
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
bool isEnumeralType() const
Definition TypeBase.h:8946
bool isScalarType() const
Definition TypeBase.h:9310
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9194
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2871
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9264
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isFunctionType() const
Definition TypeBase.h:8811
bool isObjCObjectPointerType() const
Definition TypeBase.h:8994
bool isFloatingType() const
Definition Type.cpp:2517
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
bool isNullPtrType() const
Definition TypeBase.h:9241
bool isRecordType() const
Definition TypeBase.h:8942
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2132
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1489
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:942
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
void setInit(Expr *I)
Definition Decl.cpp:2470
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
Top level wrappers for InstallAPI frontend operations.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
OpenACCDirectiveKind
OpenACCReductionOperator
@ Invalid
Invalid Reduction Clause Kind.
bool isa(CodeGen::Address addr)
Definition Address.h:330
OpenACCAtomicKind
@ Conditional
A conditional (?:) operator.
Definition Sema.h:662
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:155
OpenACCClauseKind
Represents the kind of an OpenACC clause.
@ Collapse
'collapse' clause, allowed on 'loop' and Combined constructs.
@ Private
'private' clause, allowed on 'parallel', 'serial', 'loop', 'parallel loop', and 'serial loop' constru...
@ Invalid
Represents an invalid clause, for the purposes of parsing.
@ UseDevice
'use_device' clause, allowed on 'host_data' construct.
@ Reduction
'reduction' clause, allowed on Parallel, Serial, Loop, and the combined constructs.
@ FirstPrivate
'firstprivate' clause, allowed on 'parallel', 'serial', 'parallel loop', and 'serial loop' constructs...
@ Tile
'tile' clause, allowed on 'loop' and Combined constructs.
@ AS_public
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_Auto
Definition Specifiers.h:260
ExprResult ExprEmpty()
Definition Ownership.h:272
StmtResult StmtError()
Definition Ownership.h:266
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
ExprResult ExprError()
Definition Ownership.h:265
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:143
U cast(CodeGen::Address addr)
Definition Address.h:327
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
@ NOUR_None
This is an odr-use.
Definition Specifiers.h:179
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
static OpenACCFirstPrivateRecipe Empty()
static OpenACCPrivateRecipe Empty()
static OpenACCReductionRecipeWithStorage Empty()