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
14#include "clang/Sema/SemaOpenACC.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/DeclOpenACC.h"
17#include "clang/AST/StmtOpenACC.h"
18#include "clang/Basic/DiagnosticSema.h"
19#include "clang/Basic/OpenACCKinds.h"
20#include "clang/Basic/SourceManager.h"
21#include "clang/Sema/Initialization.h"
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:
34 case OpenACCDirectiveKind::Invalid:
35 // Nothing to do here, both invalid and unimplemented don't really need to
36 // do anything.
37 break;
38 case OpenACCDirectiveKind::Parallel:
39 case OpenACCDirectiveKind::ParallelLoop:
40 case OpenACCDirectiveKind::Serial:
41 case OpenACCDirectiveKind::SerialLoop:
42 case OpenACCDirectiveKind::Kernels:
43 case OpenACCDirectiveKind::KernelsLoop:
44 case OpenACCDirectiveKind::Loop:
45 case OpenACCDirectiveKind::Data:
46 case OpenACCDirectiveKind::EnterData:
47 case OpenACCDirectiveKind::ExitData:
48 case OpenACCDirectiveKind::HostData:
49 case OpenACCDirectiveKind::Wait:
50 case OpenACCDirectiveKind::Update:
51 case OpenACCDirectiveKind::Init:
52 case OpenACCDirectiveKind::Shutdown:
53 case OpenACCDirectiveKind::Cache:
54 case OpenACCDirectiveKind::Atomic:
55 if (!IsStmt)
56 return S.Diag(Loc: StartLoc, DiagID: diag::err_acc_construct_appertainment) << K;
57 break;
58 }
59 return false;
60}
61
62void CollectActiveReductionClauses(
63 llvm::SmallVector<OpenACCReductionClause *> &ActiveClauses,
64 ArrayRef<OpenACCClause *> CurClauses) {
65 for (auto *CurClause : CurClauses) {
66 if (auto *RedClause = dyn_cast<OpenACCReductionClause>(Val: CurClause);
67 RedClause && !RedClause->getVarList().empty())
68 ActiveClauses.push_back(Elt: 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) {
76 case OpenACCDirectiveKind::Parallel:
77 case OpenACCDirectiveKind::ParallelLoop:
78 case OpenACCDirectiveKind::Serial:
79 case OpenACCDirectiveKind::SerialLoop:
80 case OpenACCDirectiveKind::Kernels:
81 case OpenACCDirectiveKind::KernelsLoop:
82 case OpenACCDirectiveKind::Loop:
83 return false;
84 case OpenACCDirectiveKind::Data:
85 case OpenACCDirectiveKind::HostData:
86 case OpenACCDirectiveKind::Atomic:
87 return true;
88 case OpenACCDirectiveKind::Cache:
89 case OpenACCDirectiveKind::Routine:
90 case OpenACCDirectiveKind::Declare:
91 case OpenACCDirectiveKind::EnterData:
92 case OpenACCDirectiveKind::ExitData:
93 case OpenACCDirectiveKind::Wait:
94 case OpenACCDirectiveKind::Init:
95 case OpenACCDirectiveKind::Shutdown:
96 case OpenACCDirectiveKind::Set:
97 case OpenACCDirectiveKind::Update:
98 llvm_unreachable("Doesn't have an associated stmt");
99 case OpenACCDirectiveKind::Invalid:
100 llvm_unreachable("Unhandled directive kind?");
101 }
102 llvm_unreachable("Unhandled directive kind?");
103}
104
105} // namespace
106
107SemaOpenACC::SemaOpenACC(Sema &S) : SemaBase(S) {}
108
109SemaOpenACC::AssociatedStmtRAII::AssociatedStmtRAII(
110 SemaOpenACC &S, OpenACCDirectiveKind DK, SourceLocation DirLoc,
111 ArrayRef<const OpenACCClause *> UnInstClauses,
112 ArrayRef<OpenACCClause *> Clauses)
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(DK: DirKind)) {
120
121 // Compute constructs end up taking their 'loop'.
122 if (DirKind == OpenACCDirectiveKind::Parallel ||
123 DirKind == OpenACCDirectiveKind::Serial ||
124 DirKind == OpenACCDirectiveKind::Kernels) {
125 CollectActiveReductionClauses(ActiveClauses&: S.ActiveReductionClauses, CurClauses: 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 ||
140 DirKind == OpenACCDirectiveKind::SerialLoop ||
141 DirKind == OpenACCDirectiveKind::KernelsLoop) {
142 SemaRef.ActiveComputeConstructInfo.Kind = DirKind;
143 SemaRef.ActiveComputeConstructInfo.Clauses = Clauses;
144
145 CollectActiveReductionClauses(ActiveClauses&: S.ActiveReductionClauses, CurClauses: 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(Range&: Clauses, P: llvm::IsaPred<OpenACCSeqClause>))
158 SemaRef.LoopWithoutSeqInfo = {.Kind: DirKind, .Loc: 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(Range&: Clauses, P: llvm::IsaPred<OpenACCGangClause>);
171 if (Itr != Clauses.end())
172 SemaRef.LoopGangClauseOnKernel = {.Loc: (*Itr)->getBeginLoc(), .DirKind: DirKind};
173 }
174
175 if (UnInstClauses.empty()) {
176 auto *Itr = llvm::find_if(Range&: Clauses, P: llvm::IsaPred<OpenACCWorkerClause>);
177 if (Itr != Clauses.end())
178 SemaRef.LoopWorkerClauseLoc = (*Itr)->getBeginLoc();
179
180 auto *Itr2 = llvm::find_if(Range&: Clauses, P: llvm::IsaPred<OpenACCVectorClause>);
181 if (Itr2 != Clauses.end())
182 SemaRef.LoopVectorClauseLoc = (*Itr2)->getBeginLoc();
183 }
184 } else if (DirKind == OpenACCDirectiveKind::Loop) {
185 CollectActiveReductionClauses(ActiveClauses&: S.ActiveReductionClauses, CurClauses: 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(Range&: Clauses, P: llvm::IsaPred<OpenACCSeqClause>))
194 SemaRef.LoopWithoutSeqInfo = {.Kind: DirKind, .Loc: 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 ==
205 OpenACCDirectiveKind::Kernels &&
206 UnInstClauses.empty()) {
207 // This handles the 'outer loop' part of this.
208 auto *Itr = llvm::find_if(Range&: Clauses, P: llvm::IsaPred<OpenACCGangClause>);
209 if (Itr != Clauses.end())
210 SemaRef.LoopGangClauseOnKernel = {.Loc: (*Itr)->getBeginLoc(),
211 .DirKind: OpenACCDirectiveKind::Kernels};
212 }
213
214 if (UnInstClauses.empty()) {
215 auto *Itr = llvm::find_if(Range&: Clauses, P: llvm::IsaPred<OpenACCWorkerClause>);
216 if (Itr != Clauses.end())
217 SemaRef.LoopWorkerClauseLoc = (*Itr)->getBeginLoc();
218
219 auto *Itr2 = llvm::find_if(Range&: Clauses, P: 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.
230const OpenACCCollapseClause *
231getBestCollapseCandidate(const OpenACCCollapseClause *Old,
232 const OpenACCCollapseClause *New,
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>(Val: Old->getLoopCount())->getResultAsAPSInt() <
261 cast<ConstantExpr>(Val: New->getLoopCount())->getResultAsAPSInt())
262 return New;
263
264 return Old;
265}
266} // namespace
267
268void SemaOpenACC::AssociatedStmtRAII::SetCollapseInfoBeforeAssociatedStmt(
269 ArrayRef<const OpenACCClause *> UnInstClauses,
270 ArrayRef<OpenACCClause *> Clauses) {
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(Range&: UnInstClauses, P: llvm::IsaPred<OpenACCCollapseClause>);
289 auto *ClauseItr =
290 llvm::find_if(Range&: Clauses, P: 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>(Val: *ClauseItr);
302 const OpenACCCollapseClause *UnInstCurClause =
303 UnInstClauseItr == UnInstClauses.end()
304 ? nullptr
305 : cast<OpenACCCollapseClause>(Val: *UnInstClauseItr);
306
307 FoundClause =
308 getBestCollapseCandidate(Old: FoundClause, New: CurClause, UnInstNew: UnInstCurClause);
309
310 UnInstClauseItr =
311 UnInstClauseItr == UnInstClauses.end()
312 ? UnInstClauseItr
313 : std::find_if(first: std::next(x: UnInstClauseItr), last: UnInstClauses.end(),
314 pred: llvm::IsaPred<OpenACCCollapseClause>);
315 ClauseItr = std::find_if(first: std::next(x: ClauseItr), last: Clauses.end(),
316 pred: 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>(Val: FoundClause->getLoopCount())->getResultAsAPSInt();
326 SemaRef.CollapseInfo.DirectiveKind = DirKind;
327}
328
329void SemaOpenACC::AssociatedStmtRAII::SetTileInfoBeforeAssociatedStmt(
330 ArrayRef<const OpenACCClause *> UnInstClauses,
331 ArrayRef<OpenACCClause *> Clauses) {
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(Range&: Clauses, P: llvm::IsaPred<OpenACCTileClause>);
339
340 if (Clauses.end() == TileClauseItr)
341 return;
342
343 OpenACCTileClause *TileClause = cast<OpenACCTileClause>(Val: *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(first: std::next(x: TileClauseItr), last: Clauses.end(),
349 pred: llvm::IsaPred<OpenACCTileClause>))) {
350 OpenACCTileClause *NewClause = cast<OpenACCTileClause>(Val: *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
362SemaOpenACC::AssociatedStmtRAII::~AssociatedStmtRAII() {
363 if (DirKind == OpenACCDirectiveKind::Parallel ||
364 DirKind == OpenACCDirectiveKind::Serial ||
365 DirKind == OpenACCDirectiveKind::Kernels ||
366 DirKind == OpenACCDirectiveKind::Loop ||
367 DirKind == OpenACCDirectiveKind::ParallelLoop ||
368 DirKind == OpenACCDirectiveKind::SerialLoop ||
369 DirKind == OpenACCDirectiveKind::KernelsLoop) {
370 SemaRef.ActiveComputeConstructInfo = OldActiveComputeConstructInfo;
371 SemaRef.LoopGangClauseOnKernel = OldLoopGangClauseOnKernel;
372 SemaRef.LoopWorkerClauseLoc = OldLoopWorkerClauseLoc;
373 SemaRef.LoopVectorClauseLoc = OldLoopVectorClauseLoc;
374 SemaRef.LoopWithoutSeqInfo = OldLoopWithoutSeqInfo;
375 SemaRef.ActiveReductionClauses.swap(RHS&: ActiveReductionClauses);
376 } else if (DirKind == OpenACCDirectiveKind::Data ||
377 DirKind == OpenACCDirectiveKind::HostData) {
378 // Intentionally doesn't reset the Loop, Compute Construct, or reduction
379 // effects.
380 }
381}
382
383void SemaOpenACC::ActOnConstruct(OpenACCDirectiveKind K,
384 SourceLocation DirLoc) {
385 // Start an evaluation context to parse the clause arguments on.
386 SemaRef.PushExpressionEvaluationContext(
387 NewContext: Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
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
393ExprResult SemaOpenACC::ActOnIntExpr(OpenACCDirectiveKind DK,
394 OpenACCClauseKind CK, SourceLocation Loc,
395 Expr *IntExpr) {
396
397 assert(((DK != OpenACCDirectiveKind::Invalid &&
398 CK == OpenACCClauseKind::Invalid) ||
399 (DK == OpenACCDirectiveKind::Invalid &&
400 CK != OpenACCClauseKind::Invalid) ||
401 (DK == OpenACCDirectiveKind::Invalid &&
402 CK == OpenACCClauseKind::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 }
433 SemaBase::SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
434 QualType T) override {
435 return S.Diag(Loc, DiagID: diag::err_acc_int_expr_requires_integer)
436 << getDiagKind() << ClauseKind << DirectiveKind << T;
437 }
438
439 SemaBase::SemaDiagnosticBuilder
440 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override {
441 return S.Diag(Loc, DiagID: diag::err_acc_int_expr_incomplete_class_type)
442 << T << IntExpr->getSourceRange();
443 }
444
445 SemaBase::SemaDiagnosticBuilder
446 diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T,
447 QualType ConvTy) override {
448 return S.Diag(Loc, DiagID: 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(Loc: Conv->getLocation(), DiagID: diag::note_acc_int_expr_conversion)
456 << ConvTy->isEnumeralType() << ConvTy;
457 }
458
459 SemaBase::SemaDiagnosticBuilder
460 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override {
461 return S.Diag(Loc, DiagID: diag::err_acc_int_expr_multiple_conversions) << T;
462 }
463
464 SemaBase::SemaDiagnosticBuilder
465 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
466 return S.Diag(Loc: Conv->getLocation(), DiagID: diag::note_acc_int_expr_conversion)
467 << ConvTy->isEnumeralType() << ConvTy;
468 }
469
470 SemaBase::SemaDiagnosticBuilder
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, FromE: IntExpr, Converter&: 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
494bool SemaOpenACC::CheckVarIsPointerType(OpenACCClauseKind ClauseKind,
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
504 if (isa<ArraySectionExpr>(Val: VarExpr->IgnoreParenImpCasts()) ||
505 VarExpr->hasPlaceholderType(K: BuiltinType::ArraySection)) {
506 Diag(Loc: VarExpr->getExprLoc(), DiagID: diag::err_array_section_use) << /*OpenACC=*/0;
507 Diag(Loc: VarExpr->getExprLoc(), DiagID: diag::note_acc_expected_pointer_var);
508 return true;
509 }
510
511 QualType Ty = VarExpr->getType();
512 Ty = Ty.getNonReferenceType().getUnqualifiedType();
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(Loc: VarExpr->getExprLoc(), DiagID: diag::err_acc_var_not_pointer_type)
520 << ClauseKind << Ty;
521 return false;
522}
523
524void SemaOpenACC::ActOnStartParseVar(OpenACCDirectiveKind DK,
525 OpenACCClauseKind CK) {
526 if (DK == OpenACCDirectiveKind::Cache) {
527 CacheInfo.ParsingCacheVarList = true;
528 CacheInfo.IsInvalidCacheRef = false;
529 }
530}
531
532void SemaOpenACC::ActOnInvalidParseVar() {
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
539ExprResult SemaOpenACC::ActOnCacheVar(Expr *VarExpr) {
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
551 if (!isa<ArraySectionExpr, ArraySubscriptExpr>(Val: CurVarExpr)) {
552 Diag(Loc: VarExpr->getExprLoc(), DiagID: 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.
558 while (isa<ArraySectionExpr, ArraySubscriptExpr>(Val: CurVarExpr)) {
559 if (auto *SubScrpt = dyn_cast<ArraySubscriptExpr>(Val: CurVarExpr))
560 CurVarExpr = SubScrpt->getBase()->IgnoreParenImpCasts();
561 else
562 CurVarExpr =
563 cast<ArraySectionExpr>(Val: CurVarExpr)->getBase()->IgnoreParenImpCasts();
564 }
565
566 // References to a VarDecl are fine.
567 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: CurVarExpr)) {
568 if (isa<VarDecl, NonTypeTemplateParmDecl>(
569 Val: DRE->getFoundDecl()->getCanonicalDecl()))
570 return WasParsingInvalidCacheRef ? ExprEmpty() : VarExpr;
571 }
572
573 if (const auto *ME = dyn_cast<MemberExpr>(Val: CurVarExpr)) {
574 if (isa<FieldDecl>(Val: 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.
581 if (isa<DependentScopeDeclRefExpr, CXXDependentScopeMemberExpr>(Val: CurVarExpr))
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>(Val: CurVarExpr))
587 return ExprError();
588
589 Diag(Loc: VarExpr->getExprLoc(), DiagID: diag::err_acc_not_a_var_ref_cache);
590 return ExprError();
591}
592
593void SemaOpenACC::CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D) {
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, DiagID: 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 &&
640 CK != OpenACCClauseKind::FirstPrivate &&
641 CK != OpenACCClauseKind::Reduction)
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(Loc: InnerLoc, DiagID: clang::diag::warn_acc_var_referenced_non_const_array)
657 << InnerTy << CK;
658 return VarExpr;
659 }
660
661 return CheckVarType(S, CK, VarExpr, InnerLoc, InnerTy: ArrTy->getElementType());
662 }
663
664 if (S.SemaRef.RequireCompleteType(Loc: InnerLoc, T: InnerTy,
665 Kind: Sema::CompleteTypeKind::Normal,
666 DiagID: 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(Range: RD->ctors(), P: [](const CXXConstructorDecl *CD) {
679 return CD->isDefaultConstructor() && !CD->isDeleted();
680 }) != RD->ctors().end();
681 if (!HasNonDeletedDefaultCtor && !RD->needsImplicitDefaultConstructor()) {
682 S.Diag(Loc: InnerLoc, DiagID: 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 D: RD, SM: CXXSpecialMemberKind::CopyConstructor, /*ConstArg=*/true,
690 /*VolatileArg=*/false, /*RValueThis=*/false, /*ConstThis=*/false,
691 /*VolatileThis=*/false);
692
693 if (SMOR.getKind() != Sema::SpecialMemberOverloadResult::Success ||
694 SMOR.getMethod()->isDeleted()) {
695 S.Diag(Loc: InnerLoc, DiagID: 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(Loc: InnerLoc, DiagID: 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, InnerLoc: InnerExpr->getBeginLoc(),
722 InnerTy: InnerExpr->getType());
723}
724} // namespace
725
726ExprResult SemaOpenACC::ActOnVar(OpenACCDirectiveKind DK, OpenACCClauseKind CK,
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.
733 if (DK == OpenACCDirectiveKind::Cache)
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 ||
744 DK == OpenACCDirectiveKind::Declare)) {
745 if (isa<ArraySubscriptExpr>(Val: CurVarExpr)) {
746 Diag(Loc: VarExpr->getExprLoc(),
747 DiagID: diag::err_acc_not_a_var_ref_use_device_declare)
748 << (DK == OpenACCDirectiveKind::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>(Val: CurVarExpr))
754 Diag(Loc: VarExpr->getExprLoc(),
755 DiagID: diag::ext_acc_array_section_use_device_declare)
756 << (DK == OpenACCDirectiveKind::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.
761 while (isa<ArraySectionExpr, ArraySubscriptExpr>(Val: CurVarExpr)) {
762 if (auto *SubScrpt = dyn_cast<ArraySubscriptExpr>(Val: CurVarExpr))
763 CurVarExpr = SubScrpt->getBase()->IgnoreParenImpCasts();
764 else
765 CurVarExpr =
766 cast<ArraySectionExpr>(Val: CurVarExpr)->getBase()->IgnoreParenImpCasts();
767 }
768
769 // References to a VarDecl are fine.
770 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: CurVarExpr)) {
771 if (isa<VarDecl, NonTypeTemplateParmDecl>(
772 Val: DRE->getFoundDecl()->getCanonicalDecl()))
773 return CheckVarType(S&: *this, CK, VarExpr, InnerExpr: 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>(Val: CurVarExpr)) {
783 if (isa<FieldDecl>(Val: ME->getMemberDecl()->getCanonicalDecl())) {
784 if (DK == OpenACCDirectiveKind::Declare ||
785 CK == OpenACCClauseKind::Reduction ||
786 CK == OpenACCClauseKind::UseDevice) {
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>(Val: ME->getBase());
791 if (This && This->isImplicit())
792 return CheckVarType(S&: *this, CK, VarExpr, InnerExpr: CurVarExpr);
793 } else {
794 return CheckVarType(S&: *this, CK, VarExpr, InnerExpr: 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'
801 if (CK != OpenACCClauseKind::UseDevice &&
802 DK != OpenACCDirectiveKind::Declare && isa<CXXThisExpr>(Val: CurVarExpr))
803 return CheckVarType(S&: *this, CK, VarExpr, InnerExpr: CurVarExpr);
804
805 // Nothing really we can do here, as these are dependent. So just return they
806 // are valid.
807 if (isa<DependentScopeDeclRefExpr>(Val: CurVarExpr) ||
808 (CK != OpenACCClauseKind::Reduction &&
809 isa<CXXDependentScopeMemberExpr>(Val: CurVarExpr)))
810 return CheckVarType(S&: *this, CK, VarExpr, InnerExpr: 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>(Val: CurVarExpr))
815 return ExprError();
816
817 if (DK == OpenACCDirectiveKind::Declare)
818 Diag(Loc: VarExpr->getExprLoc(), DiagID: diag::err_acc_not_a_var_ref_use_device_declare)
819 << /*declare*/ 1;
820 else if (CK == OpenACCClauseKind::UseDevice)
821 Diag(Loc: VarExpr->getExprLoc(), DiagID: diag::err_acc_not_a_var_ref_use_device_declare)
822 << /*use_device*/ 0;
823 else
824 Diag(Loc: VarExpr->getExprLoc(), DiagID: diag::err_acc_not_a_var_ref)
825 << (CK != OpenACCClauseKind::Reduction);
826 return ExprError();
827}
828
829ExprResult SemaOpenACC::ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc,
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(K: BuiltinType::ArraySection)) {
839 ExprResult Result = SemaRef.CheckPlaceholderExpr(E: Base);
840 if (Result.isInvalid())
841 return ExprError();
842 Base = Result.get();
843 }
844 if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
845 ExprResult Result = SemaRef.CheckPlaceholderExpr(E: LowerBound);
846 if (Result.isInvalid())
847 return ExprError();
848 Result = SemaRef.DefaultLvalueConversion(E: 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(E: Length);
855 if (Result.isInvalid())
856 return ExprError();
857 Result = SemaRef.DefaultLvalueConversion(E: 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.
865 QualType OriginalBaseTy = ArraySectionExpr::getBaseOriginalType(Base);
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(Loc: Base->getExprLoc(), DiagID: diag::err_acc_typecheck_subarray_value)
876 << Base->getSourceRange());
877 }
878
879 if (ResultTy->isFunctionType()) {
880 Diag(Loc: Base->getExprLoc(), DiagID: diag::err_acc_subarray_function_type)
881 << ResultTy << Base->getSourceRange();
882 return ExprError();
883 }
884
885 if (SemaRef.RequireCompleteType(Loc: Base->getExprLoc(), T: ResultTy,
886 DiagID: diag::err_acc_subarray_incomplete_type,
887 Args: Base))
888 return ExprError();
889
890 if (!Base->hasPlaceholderType(K: BuiltinType::ArraySection)) {
891 ExprResult Result = SemaRef.DefaultFunctionArrayLvalueConversion(E: 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(Begin: E->getBeginLoc(), End: E->getEndLoc(), SubExprs: E, T: 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 =
907 ActOnIntExpr(DK: OpenACCDirectiveKind::Invalid, CK: OpenACCClauseKind::Invalid,
908 Loc: LowerBound->getExprLoc(), IntExpr: LowerBound);
909
910 if (LBRes.isUsable())
911 LBRes = SemaRef.DefaultLvalueConversion(E: LBRes.get());
912 LowerBound =
913 LBRes.isUsable() ? LBRes.get() : GetRecovery(LowerBound, Context.IntTy);
914 }
915
916 if (Length && !Length->isTypeDependent()) {
917 ExprResult LenRes =
918 ActOnIntExpr(DK: OpenACCDirectiveKind::Invalid, CK: OpenACCClauseKind::Invalid,
919 Loc: Length->getExprLoc(), IntExpr: Length);
920
921 if (LenRes.isUsable())
922 LenRes = SemaRef.DefaultLvalueConversion(E: 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(Loc: DiagLoc, DiagID: 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 Begin: DiagLoc, End: SourceLocation(), SubExprs: ArrayRef<Expr *>(), T: 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(T: 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
960 Expr::EvalResult Res;
961 if (!E->EvaluateAsInt(Result&: Res, Ctx: 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(Loc: LowerBound->getExprLoc(), DiagID: diag::err_acc_subarray_negative)
973 << /*LowerBound=*/0 << toString(I: *LowerBoundValue, /*Radix=*/10);
974 LowerBoundValue.reset();
975 LowerBound = GetRecovery(LowerBound, LowerBound->getType());
976 } else if (BaseSize.has_value() &&
977 llvm::APSInt::compareValues(I1: *LowerBoundValue, I2: *BaseSize) >= 0) {
978 // Lower bound (start index) must be less than the size of the array.
979 Diag(Loc: LowerBound->getExprLoc(), DiagID: diag::err_acc_subarray_out_of_range)
980 << /*LowerBound=*/0 << toString(I: *LowerBoundValue, /*Radix=*/10)
981 << toString(I: *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(Loc: Length->getExprLoc(), DiagID: diag::err_acc_subarray_negative)
991 << /*Length=*/1 << toString(I: *LengthValue, /*Radix=*/10);
992 LengthValue.reset();
993 Length = GetRecovery(Length, Length->getType());
994 } else if (BaseSize.has_value() &&
995 llvm::APSInt::compareValues(I1: *LengthValue, I2: *BaseSize) > 0) {
996 // Length must be lessthan or EQUAL to the size of the array.
997 Diag(Loc: Length->getExprLoc(), DiagID: diag::err_acc_subarray_out_of_range)
998 << /*Length=*/1 << toString(I: *LengthValue, /*Radix=*/10)
999 << toString(I: *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(a: LHS.getBitWidth(), b: RHS.getBitWidth()) + 1;
1013 return llvm::APSInt(LHS.sext(width: Width) + RHS.sext(width: 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(I1: AddAPSInt(*LowerBoundValue, *LengthValue),
1021 I2: *BaseSize) > 0) {
1022 Diag(Loc: Base->getExprLoc(),
1023 DiagID: diag::err_acc_subarray_base_plus_length_out_of_range)
1024 << toString(I: *LowerBoundValue, /*Radix=*/10)
1025 << toString(I: *LengthValue, /*Radix=*/10)
1026 << toString(I: *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
1046void SemaOpenACC::ActOnWhileStmt(SourceLocation WhileLoc) {
1047 if (!getLangOpts().OpenACC)
1048 return;
1049
1050 if (!LoopInfo.TopLevelLoopSeen)
1051 return;
1052
1053 if (CollapseInfo.CurCollapseCount && *CollapseInfo.CurCollapseCount > 0) {
1054 Diag(Loc: WhileLoc, DiagID: diag::err_acc_invalid_in_loop)
1055 << /*while loop*/ 1 << CollapseInfo.DirectiveKind
1056 << OpenACCClauseKind::Collapse;
1057 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
1058 Diag(Loc: CollapseInfo.ActiveCollapse->getBeginLoc(),
1059 DiagID: diag::note_acc_active_clause_here)
1060 << OpenACCClauseKind::Collapse;
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(Loc: WhileLoc, DiagID: diag::err_acc_invalid_in_loop)
1069 << /*while loop*/ 1 << TileInfo.DirectiveKind
1070 << OpenACCClauseKind::Tile;
1071 assert(TileInfo.ActiveTile && "tile count without object?");
1072 Diag(Loc: TileInfo.ActiveTile->getBeginLoc(), DiagID: diag::note_acc_active_clause_here)
1073 << OpenACCClauseKind::Tile;
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
1081void SemaOpenACC::ActOnDoStmt(SourceLocation DoLoc) {
1082 if (!getLangOpts().OpenACC)
1083 return;
1084
1085 if (!LoopInfo.TopLevelLoopSeen)
1086 return;
1087
1088 if (CollapseInfo.CurCollapseCount && *CollapseInfo.CurCollapseCount > 0) {
1089 Diag(Loc: DoLoc, DiagID: diag::err_acc_invalid_in_loop)
1090 << /*do loop*/ 2 << CollapseInfo.DirectiveKind
1091 << OpenACCClauseKind::Collapse;
1092 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
1093 Diag(Loc: CollapseInfo.ActiveCollapse->getBeginLoc(),
1094 DiagID: diag::note_acc_active_clause_here)
1095 << OpenACCClauseKind::Collapse;
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(Loc: DoLoc, DiagID: diag::err_acc_invalid_in_loop)
1104 << /*do loop*/ 2 << TileInfo.DirectiveKind << OpenACCClauseKind::Tile;
1105 assert(TileInfo.ActiveTile && "tile count without object?");
1106 Diag(Loc: TileInfo.ActiveTile->getBeginLoc(), DiagID: diag::note_acc_active_clause_here)
1107 << OpenACCClauseKind::Tile;
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(Loc: ForLoc, DiagID: diag::err_acc_clause_multiple_loops)
1133 << CollapseInfo.DirectiveKind << OpenACCClauseKind::Collapse;
1134 assert(CollapseInfo.ActiveCollapse && "No collapse object?");
1135 Diag(Loc: CollapseInfo.ActiveCollapse->getBeginLoc(),
1136 DiagID: diag::note_acc_active_clause_here)
1137 << OpenACCClauseKind::Collapse;
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(Loc: ForLoc, DiagID: diag::err_acc_clause_multiple_loops)
1154 << TileInfo.DirectiveKind << OpenACCClauseKind::Tile;
1155 assert(TileInfo.ActiveTile && "No tile object?");
1156 Diag(Loc: TileInfo.ActiveTile->getBeginLoc(),
1157 DiagID: diag::note_acc_active_clause_here)
1158 << OpenACCClauseKind::Tile;
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(Range: RD->decls(), Pred: llvm::IsaPred<TypedefNameDecl>)) {
1199 const auto *TDND = cast<TypedefNameDecl>(Val: 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>(Val: 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>(Val: E))
1248 return DRE->getDecl();
1249
1250 if (const auto *ME = dyn_cast<MemberExpr>(Val: E))
1251 if (isa<CXXThisExpr>(Val: 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>(v&: 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>(Val: UninstRangeStmt->getSingleDecl());
1273 QualType VarType = InitVar->getType().getNonReferenceType();
1274
1275 if (!isValidLoopVariableType(LoopVarTy: 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>(Val: RangeStmt->getSingleDecl());
1283 QualType VarType = InitVar->getType().getNonReferenceType();
1284
1285 if (!isValidLoopVariableType(LoopVarTy: VarType)) {
1286 SemaRef.Diag(Loc: InitVar->getBeginLoc(), DiagID: diag::err_acc_loop_variable_type)
1287 << SemaRef.LoopWithoutSeqInfo.Kind << VarType;
1288 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1289 DiagID: 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(Loc: ForLoc, DiagID: diag::err_acc_loop_variable)
1302 << SemaRef.LoopWithoutSeqInfo.Kind;
1303 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1304 DiagID: 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(Loc: InitStmt->getBeginLoc(), DiagID: diag::err_acc_loop_variable)
1312 << SemaRef.LoopWithoutSeqInfo.Kind;
1313 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1314 DiagID: diag::note_acc_construct_here)
1315 << SemaRef.LoopWithoutSeqInfo.Kind;
1316 }
1317 return true;
1318 };
1319
1320 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(Val: InitStmt))
1321 InitStmt = ExprTemp->getSubExpr();
1322 if (const auto *E = dyn_cast<Expr>(Val: InitStmt))
1323 InitStmt = E->IgnoreParenImpCasts();
1324
1325 InitVar = nullptr;
1326 if (const auto *BO = dyn_cast<BinaryOperator>(Val: 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>(Val: LHS))
1334 InitVar = DRE->getDecl();
1335 } else if (const auto *DS = dyn_cast<DeclStmt>(Val: InitStmt)) {
1336 // Allow T t = <whatever>
1337 if (!DS->isSingleDecl())
1338 return DiagLoopVar();
1339 InitVar = dyn_cast<ValueDecl>(Val: DS->getSingleDecl());
1340
1341 // Ensure we have an initializer, unless this is a record/dependent type.
1342 if (InitVar) {
1343 if (!isa<VarDecl>(Val: InitVar))
1344 return DiagLoopVar();
1345
1346 if (!InitVar->getType()->isRecordType() &&
1347 !InitVar->getType()->isDependentType() &&
1348 !cast<VarDecl>(Val: InitVar)->hasInit())
1349 return DiagLoopVar();
1350 }
1351 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(Val: 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(Arg: 0)->IgnoreParenImpCasts();
1359 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS)) {
1360 InitVar = DRE->getDecl();
1361 } else if (auto *ME = dyn_cast<MemberExpr>(Val: LHS)) {
1362 if (isa<CXXThisExpr>(Val: 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>(Val: 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(LoopVarTy: VarType)) {
1376 if (Diag) {
1377 SemaRef.Diag(Loc: InitVar->getBeginLoc(), DiagID: diag::err_acc_loop_variable_type)
1378 << SemaRef.LoopWithoutSeqInfo.Kind << VarType;
1379 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1380 DiagID: 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(Loc: ForLoc, DiagID: diag::err_acc_loop_terminating_condition)
1396 << SemaRef.LoopWithoutSeqInfo.Kind;
1397 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1398 DiagID: 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(Loc: CondStmt->getBeginLoc(),
1407 DiagID: diag::err_acc_loop_terminating_condition)
1408 << SemaRef.LoopWithoutSeqInfo.Kind;
1409 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1410 DiagID: diag::note_acc_construct_here)
1411 << SemaRef.LoopWithoutSeqInfo.Kind;
1412 }
1413 return true;
1414 };
1415
1416 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(Val: CondStmt))
1417 CondStmt = ExprTemp->getSubExpr();
1418 if (const auto *E = dyn_cast<Expr>(Val: CondStmt))
1419 CondStmt = E->IgnoreParenImpCasts();
1420
1421 const ValueDecl *CondVar = nullptr;
1422 if (const auto *BO = dyn_cast<BinaryOperator>(Val: 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(E: BO->getLHS());
1439 if (!CondVar ||
1440 (InitVar && CondVar->getCanonicalDecl() != InitVar->getCanonicalDecl()))
1441 CondVar = getDeclFromExpr(E: BO->getRHS());
1442
1443 } else if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(Val: 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(E: CE->getArg(Arg: 0));
1455 if (!CondVar ||
1456 (InitVar &&
1457 CondVar->getCanonicalDecl() != InitVar->getCanonicalDecl() &&
1458 CE->getNumArgs() > 1))
1459 CondVar = getDeclFromExpr(E: CE->getArg(Arg: 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(E: InnerLHS);
1494 const ValueDecl *RHSDecl = getDeclFromExpr(E: 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>(Val: 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>(Val: 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(Arg: 0), CE->getArg(Arg: 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(Loc: ForLoc, DiagID: diag::err_acc_loop_not_monotonic)
1539 << SemaRef.LoopWithoutSeqInfo.Kind;
1540 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1541 DiagID: 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(Loc: IncStmt->getBeginLoc(), DiagID: diag::err_acc_loop_not_monotonic)
1549 << SemaRef.LoopWithoutSeqInfo.Kind;
1550 SemaRef.Diag(Loc: SemaRef.LoopWithoutSeqInfo.Loc,
1551 DiagID: diag::note_acc_construct_here)
1552 << SemaRef.LoopWithoutSeqInfo.Kind;
1553 }
1554 return true;
1555 };
1556
1557 if (const auto *ExprTemp = dyn_cast<ExprWithCleanups>(Val: IncStmt))
1558 IncStmt = ExprTemp->getSubExpr();
1559 if (const auto *E = dyn_cast<Expr>(Val: 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>(Val: IncStmt)) {
1565 // Allow increment/decrement ops.
1566 if (!UO->isIncrementDecrementOp())
1567 return DiagIncVar();
1568 IncVar = getDeclFromExpr(E: UO->getSubExpr());
1569 } else if (const auto *BO = dyn_cast<BinaryOperator>(Val: 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, RHS: BO->getRHS()))
1580 return DiagIncVar();
1581 break;
1582 }
1583 IncVar = getDeclFromExpr(E: BO->getLHS());
1584 } else if (const auto *CE = dyn_cast<CXXOperatorCallExpr>(Val: 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, RHS: CE->getArg(Arg: 1)))
1601 return DiagIncVar();
1602 break;
1603 }
1604
1605 IncVar = getDeclFromExpr(E: CE->getArg(Arg: 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>(v&: 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(InitStmt: CFI.Current.Init, InitVar&: CurInitVar, /*Diag=*/true);
1630 checkForCond(CondStmt: CFI.Current.Condition, InitVar: CurInitVar, /*Diag=*/true);
1631 checkForInc(IncStmt: CFI.Current.Increment, InitVar: CurInitVar, /*DIag=*/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(InitStmt: CFI.Uninst.Init, InitVar&: 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>(Val: CFI.Uninst.Init))
1652 if (const VarDecl *VD = dyn_cast_if_present<VarDecl>(
1653 Val: DS->isSingleDecl() ? DS->getSingleDecl() : nullptr))
1654 OldVDTy = VD->getType();
1655 if (const auto *DS = dyn_cast<DeclStmt>(Val: CFI.Current.Init))
1656 if (const VarDecl *VD = dyn_cast_if_present<VarDecl>(
1657 Val: DS->isSingleDecl() ? DS->getSingleDecl() : nullptr))
1658 NewVDTy = VD->getType();
1659
1660 if (OldVDTy.isNull() || NewVDTy.isNull())
1661 return true;
1662
1663 return OldVDTy->isInstantiationDependentType() !=
1664 NewVDTy->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(InitStmt: CFI.Current.Init, InitVar&: 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(CondStmt: CFI.Uninst.Condition, InitVar: UninstInitVar, /*Diag=*/false))
1677 checkForCond(CondStmt: CFI.Current.Condition, InitVar: CurInitVar, /*Diag=*/true);
1678 if (CFI.Uninst.Increment != CFI.Current.Increment &&
1679 !checkForInc(IncStmt: CFI.Uninst.Increment, InitVar: UninstInitVar, /*Diag=*/false))
1680 checkForInc(IncStmt: CFI.Current.Increment, InitVar: 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>(v: Info))
1713 return checkRangeFor();
1714
1715 return checkFor();
1716}
1717
1718void SemaOpenACC::ActOnForStmtBegin(SourceLocation ForLoc, const Stmt *OldFirst,
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, C&: FSBC);
1734}
1735
1736void SemaOpenACC::ActOnForStmtBegin(SourceLocation ForLoc, const Stmt *First,
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, C&: FSBC);
1749}
1750
1751void SemaOpenACC::ActOnRangeForStmtBegin(SourceLocation ForLoc,
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>(Val: OldRangeFor),
1759 cast_if_present<CXXForRangeStmt>(Val: 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, C&: FSBC);
1766}
1767
1768void SemaOpenACC::ActOnRangeForStmtBegin(SourceLocation ForLoc,
1769 const Stmt *RangeFor) {
1770 if (!getLangOpts().OpenACC || RangeFor == nullptr)
1771 return;
1772
1773 ForStmtBeginChecker FSBC = {*this, ForLoc,
1774 cast_if_present<CXXForRangeStmt>(Val: 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, C&: 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 ||
1791 isa<ForStmt, NullStmt, ForStmt, CXXForRangeStmt, WhileStmt, DoStmt>(
1792 Val: CurStmt))
1793 return SourceLocation{};
1794
1795 // Any other construct is an error anyway, so it has already been diagnosed.
1796 if (isa<OpenACCConstructStmt>(Val: 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>(Val: CurStmt)) {
1802 for (const auto *ChildStmt : CS->children()) {
1803 SourceLocation ChildStmtLoc = FindInterveningCodeInLoop(CurStmt: 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
1814void SemaOpenACC::ActOnForStmtEnd(SourceLocation ForLoc, StmtResult Body) {
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(CurStmt: Body.get());
1831
1832 if (OtherStmtLoc.isValid() && IsActiveCollapse) {
1833 Diag(Loc: OtherStmtLoc, DiagID: diag::err_acc_intervening_code)
1834 << OpenACCClauseKind::Collapse << CollapseInfo.DirectiveKind;
1835 Diag(Loc: CollapseInfo.ActiveCollapse->getBeginLoc(),
1836 DiagID: diag::note_acc_active_clause_here)
1837 << OpenACCClauseKind::Collapse;
1838 }
1839
1840 if (OtherStmtLoc.isValid() && IsActiveTile) {
1841 Diag(Loc: OtherStmtLoc, DiagID: diag::err_acc_intervening_code)
1842 << OpenACCClauseKind::Tile << TileInfo.DirectiveKind;
1843 Diag(Loc: TileInfo.ActiveTile->getBeginLoc(),
1844 DiagID: diag::note_acc_active_clause_here)
1845 << OpenACCClauseKind::Tile;
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>(Val: RoutineName)) {
1858 // There is nothing we can do here, this isn't a function we can count on.
1859 return nullptr;
1860 } else if (isa<DependentScopeDeclRefExpr, CXXDependentScopeMemberExpr>(
1861 Val: 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>(Val: RoutineName)) {
1865 ValueDecl *VD = DRE->getDecl();
1866
1867 if (auto *FD = dyn_cast<FunctionDecl>(Val: VD))
1868 return FD;
1869
1870 // Allow lambdas.
1871 if (auto *VarD = dyn_cast<VarDecl>(Val: 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>(Val: RoutineName)) {
1886 return nullptr;
1887 }
1888 }
1889 return nullptr;
1890}
1891} // namespace
1892
1893ExprResult SemaOpenACC::ActOnRoutineName(Expr *RoutineName) {
1894 assert(RoutineName && "Routine name cannot be null here");
1895 RoutineName = RoutineName->IgnoreParenImpCasts();
1896
1897 if (isa<RecoveryExpr>(Val: RoutineName)) {
1898 // This has already been diagnosed, so we can skip it.
1899 return ExprError();
1900 } else if (isa<DependentScopeDeclRefExpr, CXXDependentScopeMemberExpr>(
1901 Val: 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>(Val: RoutineName)) {
1906 const ValueDecl *VD = DRE->getDecl();
1907
1908 if (isa<FunctionDecl>(Val: VD))
1909 return RoutineName;
1910
1911 // Allow lambdas.
1912 if (const auto *VarD = dyn_cast<VarDecl>(Val: VD)) {
1913 QualType VarDTy = VarD->getType();
1914 if (!VarDTy.isNull()) {
1915 if (const auto *RD = VarDTy->getAsCXXRecordDecl()) {
1916 if (RD->isGenericLambda()) {
1917 Diag(Loc: RoutineName->getBeginLoc(), DiagID: 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(Loc: RoutineName->getBeginLoc(), DiagID: diag::err_acc_routine_not_func)
1932 << RoutineName;
1933 return ExprError();
1934 } else if (isa<OverloadExpr>(Val: 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(Loc: RoutineName->getBeginLoc(), DiagID: diag::err_acc_routine_overload_set)
1940 << RoutineName;
1941 return ExprError();
1942 }
1943
1944 Diag(Loc: RoutineName->getBeginLoc(), DiagID: diag::err_acc_routine_not_func)
1945 << RoutineName;
1946 return ExprError();
1947}
1948void SemaOpenACC::ActOnVariableDeclarator(VarDecl *VD) {
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>(Val: 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()) {
1965 if (isa<OpenACCRoutineDeclAttr, OpenACCRoutineAnnotAttr>(Val: A)) {
1966 Diag(Loc: VD->getBeginLoc(), DiagID: diag::err_acc_magic_static_in_routine);
1967 Diag(Loc: A->getLocation(), DiagID: diag::note_acc_construct_here)
1968 << OpenACCDirectiveKind::Routine;
1969 return;
1970 }
1971 }
1972
1973 MagicStaticLocs.insert(KV: {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(RoutineName: 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
2011 long NDLine = SemaRef.SourceMgr.getSpellingLineNumber(Loc: ND->getBeginLoc());
2012 long LastLine =
2013 SemaRef.SourceMgr.getSpellingLineNumber(Loc: LastRoutineDecl->getBeginLoc());
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(Loc: LastRoutineDecl->getFunctionReference()->getBeginLoc(),
2025 DiagID: diag::warn_acc_confusing_routine_name);
2026 Diag(Loc: RoutineTarget->getBeginLoc(), DiagID: diag::note_previous_decl) << ND;
2027}
2028
2029void SemaOpenACC::ActOnVariableInit(VarDecl *VD, QualType InitType) {
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.
2036 if (VD->getLexicalDeclContext()->isDependentContext())
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(ND: VD);
2045}
2046
2047void SemaOpenACC::ActOnFunctionDeclarator(FunctionDecl *FD) {
2048 if (!FD || !getLangOpts().OpenACC)
2049 return;
2050 CheckLastRoutineDeclNameConflict(ND: FD);
2051}
2052
2053bool SemaOpenACC::ActOnStartStmtDirective(
2054 OpenACCDirectiveKind K, SourceLocation StartLoc,
2055 ArrayRef<const OpenACCClause *> Clauses) {
2056
2057 // Declaration directives an appear in a statement location, so call into that
2058 // function here.
2059 if (K == OpenACCDirectiveKind::Declare || K == OpenACCDirectiveKind::Routine)
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(Loc: StartLoc, DiagID: diag::err_acc_invalid_in_loop)
2072 << /*OpenACC Construct*/ 0 << CollapseInfo.DirectiveKind
2073 << OpenACCClauseKind::Collapse << K;
2074 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
2075 Diag(Loc: CollapseInfo.ActiveCollapse->getBeginLoc(),
2076 DiagID: diag::note_acc_active_clause_here)
2077 << OpenACCClauseKind::Collapse;
2078 }
2079 if (TileInfo.CurTileCount && *TileInfo.CurTileCount > 0) {
2080 Diag(Loc: StartLoc, DiagID: diag::err_acc_invalid_in_loop)
2081 << /*OpenACC Construct*/ 0 << TileInfo.DirectiveKind
2082 << OpenACCClauseKind::Tile << K;
2083 assert(TileInfo.ActiveTile && "Tile count without object?");
2084 Diag(Loc: TileInfo.ActiveTile->getBeginLoc(), DiagID: diag::note_acc_active_clause_here)
2085 << OpenACCClauseKind::Tile;
2086 }
2087
2088 if (DiagnoseRequiredClauses(DK: K, DirLoc: StartLoc, Clauses))
2089 return true;
2090 return diagnoseConstructAppertainment(S&: *this, K, StartLoc, /*IsStmt=*/true);
2091}
2092
2093StmtResult SemaOpenACC::ActOnEndStmtDirective(
2094 OpenACCDirectiveKind K, SourceLocation StartLoc, SourceLocation DirLoc,
2095 SourceLocation LParenLoc, SourceLocation MiscLoc, ArrayRef<Expr *> Exprs,
2096 OpenACCAtomicKind AtomicKind, SourceLocation RParenLoc,
2097 SourceLocation EndLoc, ArrayRef<OpenACCClause *> Clauses,
2098 StmtResult AssocStmt) {
2099 switch (K) {
2100 case OpenACCDirectiveKind::Invalid:
2101 return StmtError();
2102 case OpenACCDirectiveKind::Parallel:
2103 case OpenACCDirectiveKind::Serial:
2104 case OpenACCDirectiveKind::Kernels: {
2105 return OpenACCComputeConstruct::Create(
2106 C: getASTContext(), K, BeginLoc: StartLoc, DirectiveLoc: DirLoc, EndLoc, Clauses,
2107 StructuredBlock: AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2108 }
2109 case OpenACCDirectiveKind::ParallelLoop:
2110 case OpenACCDirectiveKind::SerialLoop:
2111 case OpenACCDirectiveKind::KernelsLoop: {
2112 return OpenACCCombinedConstruct::Create(
2113 C: getASTContext(), K, Start: StartLoc, DirectiveLoc: DirLoc, End: EndLoc, Clauses,
2114 StructuredBlock: AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2115 }
2116 case OpenACCDirectiveKind::Loop: {
2117 return OpenACCLoopConstruct::Create(
2118 C: getASTContext(), ParentKind: ActiveComputeConstructInfo.Kind, BeginLoc: StartLoc, DirLoc,
2119 EndLoc, Clauses, Loop: AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2120 }
2121 case OpenACCDirectiveKind::Data: {
2122 return OpenACCDataConstruct::Create(
2123 C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc, End: EndLoc, Clauses,
2124 StructuredBlock: AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2125 }
2126 case OpenACCDirectiveKind::EnterData: {
2127 return OpenACCEnterDataConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2128 End: EndLoc, Clauses);
2129 }
2130 case OpenACCDirectiveKind::ExitData: {
2131 return OpenACCExitDataConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2132 End: EndLoc, Clauses);
2133 }
2134 case OpenACCDirectiveKind::HostData: {
2135 return OpenACCHostDataConstruct::Create(
2136 C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc, End: EndLoc, Clauses,
2137 StructuredBlock: AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2138 }
2139 case OpenACCDirectiveKind::Wait: {
2140 return OpenACCWaitConstruct::Create(
2141 C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc, LParenLoc, DevNumExpr: Exprs.front(), QueuesLoc: MiscLoc,
2142 QueueIdExprs: Exprs.drop_front(), RParenLoc, End: EndLoc, Clauses);
2143 }
2144 case OpenACCDirectiveKind::Init: {
2145 return OpenACCInitConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2146 End: EndLoc, Clauses);
2147 }
2148 case OpenACCDirectiveKind::Shutdown: {
2149 return OpenACCShutdownConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2150 End: EndLoc, Clauses);
2151 }
2152 case OpenACCDirectiveKind::Set: {
2153 return OpenACCSetConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2154 End: EndLoc, Clauses);
2155 }
2156 case OpenACCDirectiveKind::Update: {
2157 return OpenACCUpdateConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2158 End: EndLoc, Clauses);
2159 }
2160 case OpenACCDirectiveKind::Atomic: {
2161 return OpenACCAtomicConstruct::Create(
2162 C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc, AtKind: AtomicKind, End: EndLoc, Clauses,
2163 AssociatedStmt: AssocStmt.isUsable() ? AssocStmt.get() : nullptr);
2164 }
2165 case OpenACCDirectiveKind::Cache: {
2166 assert(Clauses.empty() && "Cache doesn't allow clauses");
2167 return OpenACCCacheConstruct::Create(C: getASTContext(), Start: StartLoc, DirectiveLoc: DirLoc,
2168 LParenLoc, ReadOnlyLoc: MiscLoc, VarList: Exprs, RParenLoc,
2169 End: EndLoc);
2170 }
2171 case OpenACCDirectiveKind::Routine:
2172 llvm_unreachable("routine shouldn't handled here");
2173 case OpenACCDirectiveKind::Declare: {
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(Decl: DeclGroupPtrTy::make(P: DR), StartLoc, EndLoc);
2180 }
2181 }
2182 llvm_unreachable("Unhandled case in directive handling?");
2183}
2184
2185StmtResult SemaOpenACC::ActOnAssociatedStmt(
2186 SourceLocation DirectiveLoc, OpenACCDirectiveKind K,
2187 OpenACCAtomicKind AtKind, ArrayRef<const OpenACCClause *> Clauses,
2188 StmtResult AssocStmt) {
2189 switch (K) {
2190 default:
2191 llvm_unreachable("Unimplemented associated statement application");
2192 case OpenACCDirectiveKind::EnterData:
2193 case OpenACCDirectiveKind::ExitData:
2194 case OpenACCDirectiveKind::Wait:
2195 case OpenACCDirectiveKind::Init:
2196 case OpenACCDirectiveKind::Shutdown:
2197 case OpenACCDirectiveKind::Set:
2198 case OpenACCDirectiveKind::Cache:
2199 llvm_unreachable(
2200 "these don't have associated statements, so shouldn't get here");
2201 case OpenACCDirectiveKind::Atomic:
2202 return CheckAtomicAssociatedStmt(AtomicDirLoc: DirectiveLoc, AtKind, AssocStmt);
2203 case OpenACCDirectiveKind::Parallel:
2204 case OpenACCDirectiveKind::Serial:
2205 case OpenACCDirectiveKind::Kernels:
2206 case OpenACCDirectiveKind::Data:
2207 case OpenACCDirectiveKind::HostData:
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;
2218 case OpenACCDirectiveKind::Loop:
2219 case OpenACCDirectiveKind::ParallelLoop:
2220 case OpenACCDirectiveKind::SerialLoop:
2221 case OpenACCDirectiveKind::KernelsLoop:
2222 if (!AssocStmt.isUsable())
2223 return StmtError();
2224
2225 if (!isa<CXXForRangeStmt, ForStmt>(Val: AssocStmt.get())) {
2226 Diag(Loc: AssocStmt.get()->getBeginLoc(), DiagID: diag::err_acc_loop_not_for_loop)
2227 << K;
2228 Diag(Loc: DirectiveLoc, DiagID: diag::note_acc_construct_here) << K;
2229 return StmtError();
2230 }
2231
2232 if (!CollapseInfo.CollapseDepthSatisfied || !TileInfo.TileDepthSatisfied) {
2233 if (!CollapseInfo.CollapseDepthSatisfied) {
2234 Diag(Loc: DirectiveLoc, DiagID: diag::err_acc_insufficient_loops)
2235 << OpenACCClauseKind::Collapse;
2236 assert(CollapseInfo.ActiveCollapse && "Collapse count without object?");
2237 Diag(Loc: CollapseInfo.ActiveCollapse->getBeginLoc(),
2238 DiagID: diag::note_acc_active_clause_here)
2239 << OpenACCClauseKind::Collapse;
2240 }
2241
2242 if (!TileInfo.TileDepthSatisfied) {
2243 Diag(Loc: DirectiveLoc, DiagID: diag::err_acc_insufficient_loops)
2244 << OpenACCClauseKind::Tile;
2245 assert(TileInfo.ActiveTile && "Collapse count without object?");
2246 Diag(Loc: TileInfo.ActiveTile->getBeginLoc(),
2247 DiagID: diag::note_acc_active_clause_here)
2248 << OpenACCClauseKind::Tile;
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,
2265 ArrayRef<const OpenACCClause *> Clauses) {
2266 auto RequiredPred = llvm::IsaPred<OpenACCGangClause, OpenACCWorkerClause,
2267 OpenACCVectorClause, OpenACCSeqClause>;
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(Range&: Clauses, P: 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(first: Clauses.begin(), last: FirstDeviceType, pred: 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(Loc: DirectiveLoc, DiagID: diag::err_acc_construct_one_clause_of)
2289 << OpenACCDirectiveKind::Routine
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(first: std::next(x: PrevDeviceType), last: Clauses.end(),
2299 pred: llvm::IsaPred<OpenACCDeviceTypeClause>);
2300
2301 ClauseItr = std::find_if(first: PrevDeviceType, last: NextDeviceType, pred: RequiredPred);
2302
2303 if (ClauseItr == NextDeviceType)
2304 return SemaRef.Diag(Loc: (*PrevDeviceType)->getBeginLoc(),
2305 DiagID: diag::err_acc_clause_routine_one_of_in_region);
2306
2307 PrevDeviceType = NextDeviceType;
2308 }
2309
2310 return false;
2311}
2312} // namespace
2313
2314bool SemaOpenACC::ActOnStartDeclDirective(
2315 OpenACCDirectiveKind K, SourceLocation StartLoc,
2316 ArrayRef<const OpenACCClause *> Clauses) {
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(DK: K, DirLoc: StartLoc, Clauses))
2324 return true;
2325 if (K == OpenACCDirectiveKind::Routine &&
2326 CheckValidRoutineGangWorkerVectorSeqClauses(SemaRef&: *this, DirectiveLoc: StartLoc, Clauses))
2327 return true;
2328
2329 return diagnoseConstructAppertainment(S&: *this, K, StartLoc, /*IsStmt=*/false);
2330}
2331
2332DeclGroupRef SemaOpenACC::ActOnEndDeclDirective(
2333 OpenACCDirectiveKind K, SourceLocation StartLoc, SourceLocation DirLoc,
2334 SourceLocation LParenLoc, SourceLocation RParenLoc, SourceLocation EndLoc,
2335 ArrayRef<OpenACCClause *> Clauses) {
2336 switch (K) {
2337 default:
2338 case OpenACCDirectiveKind::Invalid:
2339 return DeclGroupRef{};
2340 case OpenACCDirectiveKind::Declare: {
2341 // OpenACC3.3 2.13: At least one clause must appear on a declare directive.
2342 if (Clauses.empty()) {
2343 Diag(Loc: EndLoc, DiagID: 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 Ctx&: getASTContext(), DC: getCurContext(), StartLoc, DirLoc, EndLoc, Clauses);
2352 DeclareDecl->setAccess(AS_public);
2353 getCurContext()->addDecl(D: DeclareDecl);
2354 return DeclGroupRef{DeclareDecl};
2355 }
2356 case OpenACCDirectiveKind::Routine:
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>(Val: D))
2371 return FD;
2372
2373 // Function templates are functions, so attach to the templated decl.
2374 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
2375 return FTD->getTemplatedDecl();
2376
2377 if (auto *FD = dyn_cast<FieldDecl>(Val: 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>(Val: 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(Ctx&: SemaRef.getASTContext(), Range: DirLoc);
2416 A->Clauses.assign(in_start: Clauses.begin(), in_end: Clauses.end());
2417 AddTo->addAttr(A);
2418}
2419} // namespace
2420
2421// Variant that adds attributes, because this is the unnamed case.
2422void SemaOpenACC::CheckRoutineDecl(SourceLocation DirLoc,
2423 ArrayRef<const OpenACCClause *> Clauses,
2424 Decl *NextParsedDecl) {
2425
2426 FunctionDecl *NextParsedFDecl = LegalizeNextParsedDecl(D: NextParsedDecl);
2427
2428 if (!NextParsedFDecl) {
2429 // If we don't have a valid 'next thing', just diagnose.
2430 SemaRef.Diag(Loc: DirLoc, DiagID: 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(Val: NextParsedFDecl->getCanonicalDecl());
2438 Itr != MagicStaticLocs.end()) {
2439 Diag(Loc: Itr->second, DiagID: diag::err_acc_magic_static_in_routine);
2440 Diag(Loc: DirLoc, DiagID: diag::note_acc_construct_here)
2441 << OpenACCDirectiveKind::Routine;
2442
2443 return;
2444 }
2445
2446 auto BindItr = llvm::find_if(Range&: Clauses, P: 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>(Val: A)) {
2453 auto OtherBindItr =
2454 llvm::find_if(Range&: RA->Clauses, P: llvm::IsaPred<OpenACCBindClause>);
2455 if (OtherBindItr != RA->Clauses.end() &&
2456 (*cast<OpenACCBindClause>(Val: *BindItr)) !=
2457 (*cast<OpenACCBindClause>(Val: *OtherBindItr))) {
2458 Diag(Loc: (*BindItr)->getBeginLoc(), DiagID: diag::err_acc_duplicate_unnamed_bind);
2459 Diag(Loc: (*OtherBindItr)->getEndLoc(),
2460 DiagID: 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>(Val: A);
2473 RA && RA->getRange().getEnd().isValid()) {
2474 Diag(Loc: (*BindItr)->getBeginLoc(), DiagID: diag::err_acc_duplicate_bind);
2475 Diag(Loc: RA->getRange().getEnd(), DiagID: diag::note_acc_previous_clause_here)
2476 << "bind";
2477 return;
2478 }
2479 }
2480 }
2481
2482 CreateRoutineDeclAttr(SemaRef&: *this, DirLoc, Clauses, AddTo: NextParsedFDecl);
2483}
2484
2485// Variant that adds a decl, because this is the named case.
2486OpenACCRoutineDecl *SemaOpenACC::CheckRoutineDecl(
2487 SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc,
2488 Expr *FuncRef, SourceLocation RParenLoc,
2489 ArrayRef<const OpenACCClause *> Clauses, SourceLocation EndLoc) {
2490 assert(LParenLoc.isValid());
2491
2492 FunctionDecl *FD = nullptr;
2493 if ((FD = getFunctionFromRoutineName(RoutineName: 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(Val: FD->getCanonicalDecl());
2498 Itr != MagicStaticLocs.end()) {
2499 Diag(Loc: Itr->second, DiagID: diag::err_acc_magic_static_in_routine);
2500 Diag(Loc: DirLoc, DiagID: diag::note_acc_construct_here)
2501 << OpenACCDirectiveKind::Routine;
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(Range&: Clauses, P: 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>(Val: A)) {
2518 auto OtherBindItr =
2519 llvm::find_if(Range&: RA->Clauses, P: llvm::IsaPred<OpenACCBindClause>);
2520 if (OtherBindItr != RA->Clauses.end()) {
2521 Diag(Loc: (*BindItr)->getBeginLoc(), DiagID: diag::err_acc_duplicate_bind);
2522 Diag(Loc: (*OtherBindItr)->getEndLoc(),
2523 DiagID: diag::note_acc_previous_clause_here)
2524 << (*BindItr)->getClauseKind();
2525 return nullptr;
2526 }
2527 }
2528
2529 if (auto *RA = dyn_cast<OpenACCRoutineAnnotAttr>(Val: A);
2530 RA && RA->getRange().getEnd().isValid()) {
2531 Diag(Loc: (*BindItr)->getBeginLoc(), DiagID: diag::err_acc_duplicate_bind);
2532 Diag(Loc: RA->getRange().getEnd(), DiagID: 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(Ctx&: getASTContext(),
2542 Range: {DirLoc, BindLoc});
2543 FD->addAttr(A: 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(A: RAA->clone(C&: getASTContext()));
2548 }
2549
2550 LastRoutineDecl = OpenACCRoutineDecl::Create(
2551 Ctx&: getASTContext(), DC: getCurContext(), StartLoc, DirLoc, LParenLoc, FuncRef,
2552 RParenLoc, EndLoc, Clauses);
2553 LastRoutineDecl->setAccess(AS_public);
2554 getCurContext()->addDecl(D: 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(Args&: FD, Args&: LastRoutineDecl);
2561 }
2562 return LastRoutineDecl;
2563}
2564
2565void SemaOpenACC::ActOnEndOfTranslationUnit(TranslationUnitDecl *TU) {
2566 for (auto [FD, RoutineDecl] : RoutineRefList)
2567 SemaRef.Consumer.HandleOpenACCRoutineReference(FD, RD: RoutineDecl);
2568}
2569
2570DeclGroupRef SemaOpenACC::ActOnEndRoutineDeclDirective(
2571 SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc,
2572 Expr *ReferencedFunc, SourceLocation RParenLoc,
2573 ArrayRef<const OpenACCClause *> Clauses, SourceLocation EndLoc,
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, NextParsedDecl: NextLineDecl);
2584
2585 return NextDecl.get();
2586 }
2587
2588 return DeclGroupRef{CheckRoutineDecl(
2589 StartLoc, DirLoc, LParenLoc, FuncRef: ReferencedFunc, RParenLoc, Clauses, EndLoc)};
2590}
2591
2592StmtResult SemaOpenACC::ActOnEndRoutineStmtDirective(
2593 SourceLocation StartLoc, SourceLocation DirLoc, SourceLocation LParenLoc,
2594 Expr *ReferencedFunc, SourceLocation RParenLoc,
2595 ArrayRef<const OpenACCClause *> Clauses, SourceLocation EndLoc,
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>(Val: NextStmt); DS && DS->isSingleDecl())
2604 NextLineDecl = DS->getSingleDecl();
2605
2606 CheckRoutineDecl(DirLoc, Clauses, NextParsedDecl: NextLineDecl);
2607 return NextStmt;
2608 }
2609
2610 DeclGroupRef DR{CheckRoutineDecl(StartLoc, DirLoc, LParenLoc, FuncRef: ReferencedFunc,
2611 RParenLoc, Clauses, EndLoc)};
2612 return SemaRef.ActOnDeclStmt(Decl: DeclGroupPtrTy::make(P: DR), StartLoc, EndLoc);
2613}
2614
2615OpenACCRoutineDeclAttr *
2616SemaOpenACC::mergeRoutineDeclAttr(const OpenACCRoutineDeclAttr &Old) {
2617 OpenACCRoutineDeclAttr *New =
2618 OpenACCRoutineDeclAttr::Create(Ctx&: getASTContext(), Range: 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}
2624ExprResult
2625SemaOpenACC::BuildOpenACCAsteriskSizeExpr(SourceLocation AsteriskLoc) {
2626 return OpenACCAsteriskSizeExpr::Create(C: getASTContext(), Loc: AsteriskLoc);
2627}
2628
2629ExprResult
2630SemaOpenACC::ActOnOpenACCAsteriskSizeExpr(SourceLocation AsteriskLoc) {
2631 return BuildOpenACCAsteriskSizeExpr(AsteriskLoc);
2632}
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(Sem: Context.getFloatTypeSemantics(T: Ty));
2642 case InitKind::One:
2643 return llvm::APFloat::getOne(Sem: Context.getFloatTypeSemantics(T: Ty));
2644 case InitKind::AllOnes:
2645 return llvm::APFloat::getAllOnesValue(Semantics: Context.getFloatTypeSemantics(T: Ty));
2646 case InitKind::Least:
2647 return llvm::APFloat::getLargest(Sem: Context.getFloatTypeSemantics(T: Ty),
2648 /*Negative=*/true);
2649 case InitKind::Largest:
2650 return llvm::APFloat::getLargest(Sem: Context.getFloatTypeSemantics(T: 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(T: Ty), 0);
2661 case InitKind::One:
2662 return llvm::APInt(Context.getIntWidth(T: Ty), 1);
2663 case InitKind::AllOnes:
2664 return llvm::APInt::getAllOnes(numBits: Context.getIntWidth(T: Ty));
2665 case InitKind::Least:
2666 if (Ty->isSignedIntegerOrEnumerationType())
2667 return llvm::APInt::getSignedMinValue(numBits: Context.getIntWidth(T: Ty));
2668 return llvm::APInt::getMinValue(numBits: Context.getIntWidth(T: Ty));
2669 case InitKind::Largest:
2670 if (Ty->isSignedIntegerOrEnumerationType())
2671 return llvm::APInt::getSignedMaxValue(numBits: Context.getIntWidth(T: Ty));
2672 return llvm::APInt::getMaxValue(numBits: Context.getIntWidth(T: 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 Ty: F->getType(), IK))
2700 Exprs.push_back(Elt: NewExpr);
2701 else
2702 return nullptr;
2703 }
2704 } else if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T: Ty)) {
2705 for (uint64_t Idx = 0; Idx < AT->getZExtSize(); ++Idx) {
2706 if (Expr *NewExpr = GenerateReductionInitRecipeExpr(
2707 Context, ExprRange, Ty: AT->getElementType(), IK))
2708 Exprs.push_back(Elt: 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(Elt: FloatingLiteral::Create(
2735 C: Context, V: getInitFloatValue(Context, IK: InitKind::Zero, Ty: EltTy),
2736 /*isExact=*/isexact: true, Type: EltTy, L: ExprRange.getBegin()));
2737 Exprs.push_back(Elt: FloatingLiteral::Create(
2738 C: Context, V: getInitFloatValue(Context, IK: InitKind::Zero, Ty: EltTy),
2739 /*isExact=*/isexact: true, Type: EltTy, L: ExprRange.getBegin()));
2740 } else {
2741 Exprs.push_back(Elt: IntegerLiteral::Create(
2742 C: Context, V: getInitIntValue(Context, IK: InitKind::Zero, Ty: EltTy), type: EltTy,
2743 l: ExprRange.getBegin()));
2744 Exprs.push_back(Elt: IntegerLiteral::Create(
2745 C: Context, V: getInitIntValue(Context, IK: InitKind::Zero, Ty: EltTy), type: EltTy,
2746 l: ExprRange.getBegin()));
2747 }
2748
2749 } else if (Ty->isFloatingType()) {
2750 Exprs.push_back(
2751 Elt: FloatingLiteral::Create(C: Context, V: getInitFloatValue(Context, IK, Ty),
2752 /*isExact=*/isexact: true, Type: Ty, L: ExprRange.getBegin()));
2753 } else if (Ty->isBooleanType()) {
2754 Exprs.push_back(Elt: CXXBoolLiteralExpr::Create(C: Context,
2755 Val: (IK == InitKind::One ||
2756 IK == InitKind::AllOnes ||
2757 IK == InitKind::Largest),
2758 Ty, Loc: ExprRange.getBegin()));
2759 } else if (Ty->isNullPtrType()) {
2760 Exprs.push_back(Elt: new (Context)
2761 CXXNullPtrLiteralExpr(Ty, ExprRange.getBegin()));
2762 } else {
2763 Exprs.push_back(Elt: IntegerLiteral::Create(
2764 C: Context, V: getInitIntValue(Context, IK, Ty), type: Ty, l: 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(C&: Ctx, DC, StartLoc: BeginLoc, IdLoc: BeginLoc, Id: VarName, T: VarTy,
2779 TInfo: Ctx.getTrivialTypeSourceInfo(T: VarTy), S: SC_Auto);
2780 VD->markUsed(C&: 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, Init: InitExpr);
2791 InitializationSequence InitSeq(S, Entity, Kind, InitExpr,
2792 /*TopLevelOfInitList=*/false,
2793 /*TreatUnavailableAsInvalid=*/false);
2794
2795 return InitSeq.Perform(S, Entity, Kind, Args: InitExpr, ResultType: &VarTy);
2796}
2797
2798} // namespace
2799
2800OpenACCPrivateRecipe SemaOpenACC::CreatePrivateInitRecipe(const Expr *VarExpr) {
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())
2804 return OpenACCPrivateRecipe::Empty();
2805
2806 QualType VarTy =
2807 VarExpr->getType().getNonReferenceType().getUnqualifiedType();
2808
2809 // Array sections are special, and we have to treat them that way.
2810 if (const auto *ASE =
2811 dyn_cast<ArraySectionExpr>(Val: VarExpr->IgnoreParenImpCasts()))
2812 VarTy = ASE->getElementType();
2813
2814 VarDecl *AllocaDecl = CreateAllocaDecl(
2815 Ctx&: getASTContext(), DC: SemaRef.getCurContext(), BeginLoc: VarExpr->getBeginLoc(),
2816 VarName: &getASTContext().Idents.get(Name: "openacc.private.init"), VarTy);
2817
2818 Sema::TentativeAnalysisScope Trap{SemaRef};
2819 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: AllocaDecl);
2820 InitializationKind Kind =
2821 InitializationKind::CreateDefault(InitLoc: AllocaDecl->getLocation());
2822 InitializationSequence InitSeq(SemaRef.SemaRef, Entity, Kind, {});
2823 ExprResult Init = InitSeq.Perform(S&: SemaRef.SemaRef, Entity, Kind, Args: {});
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
2835OpenACCFirstPrivateRecipe
2836SemaOpenACC::CreateFirstPrivateInitRecipe(const Expr *VarExpr) {
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())
2840 return OpenACCFirstPrivateRecipe::Empty();
2841
2842 QualType VarTy =
2843 VarExpr->getType().getNonReferenceType().getUnqualifiedType();
2844
2845 // Array sections are special, and we have to treat them that way.
2846 if (const auto *ASE =
2847 dyn_cast<ArraySectionExpr>(Val: VarExpr->IgnoreParenImpCasts()))
2848 VarTy = ASE->getElementType();
2849
2850 VarDecl *AllocaDecl = CreateAllocaDecl(
2851 Ctx&: getASTContext(), DC: SemaRef.getCurContext(), BeginLoc: VarExpr->getBeginLoc(),
2852 VarName: &getASTContext().Idents.get(Name: "openacc.firstprivate.init"), VarTy);
2853
2854 VarDecl *Temporary = CreateAllocaDecl(
2855 Ctx&: getASTContext(), DC: SemaRef.getCurContext(), BeginLoc: VarExpr->getBeginLoc(),
2856 VarName: &getASTContext().Idents.get(Name: "openacc.temp"), VarTy);
2857
2858 auto *TemporaryDRE = DeclRefExpr::Create(
2859 Context: getASTContext(), QualifierLoc: NestedNameSpecifierLoc{}, TemplateKWLoc: SourceLocation{}, D: Temporary,
2860 /*ReferstoEnclosingVariableOrCapture=*/RefersToEnclosingVariableOrCapture: false,
2861 NameInfo: DeclarationNameInfo{DeclarationName{Temporary->getDeclName()},
2862 VarExpr->getBeginLoc()},
2863 T: VarTy, VK: clang::VK_LValue, FoundD: Temporary, TemplateArgs: nullptr, NOUR: NOUR_None);
2864
2865 Sema::TentativeAnalysisScope Trap{SemaRef};
2866 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: AllocaDecl);
2867
2868 const auto *ArrTy = getASTContext().getAsConstantArrayType(T: VarTy);
2869 if (!ArrTy) {
2870 ExprResult Init = FinishValueInit(
2871 S&: SemaRef.SemaRef, Entity, Loc: VarExpr->getBeginLoc(), VarTy, InitExpr: 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.
2885 llvm::SmallVector<Expr *> Args;
2886 // Decay to pointer for the array subscript expression.
2887 auto *CastToPtr = ImplicitCastExpr::Create(
2888 Context: getASTContext(), T: getASTContext().getPointerType(T: ArrTy->getElementType()),
2889 Kind: CK_ArrayToPointerDecay, Operand: TemporaryDRE, /*BasePath=*/nullptr,
2890 Cat: clang::VK_LValue, FPO: FPOptionsOverride{});
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 C: getASTContext(),
2898 V: llvm::APInt(getASTContext().getTypeSize(T: getASTContext().getSizeType()),
2899 I),
2900 type: getASTContext().getSizeType(), l: 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 =
2908 InitializedEntity::InitializeElement(Context&: getASTContext(), Index: I, Parent: Entity);
2909 InitializationKind CopyKind =
2910 InitializationKind::CreateCopy(InitLoc: VarExpr->getBeginLoc(), EqualLoc: {});
2911 InitializationSequence CopySeq(SemaRef.SemaRef, CopyEntity, CopyKind,
2912 Subscript,
2913 /*TopLevelOfInitList=*/true);
2914 ExprResult ElemRes =
2915 CopySeq.Perform(S&: SemaRef.SemaRef, Entity: CopyEntity, Kind: CopyKind, Args: Subscript);
2916 Args.push_back(Elt: 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(S&: SemaRef.SemaRef, Entity,
2925 Loc: 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
2937OpenACCReductionRecipeWithStorage SemaOpenACC::CreateReductionInitRecipe(
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())
2942 return OpenACCReductionRecipeWithStorage::Empty();
2943
2944 QualType VarTy =
2945 VarExpr->getType().getNonReferenceType().getUnqualifiedType();
2946
2947 // Array sections are special, and we have to treat them that way.
2948 if (const auto *ASE =
2949 dyn_cast<ArraySectionExpr>(Val: VarExpr->IgnoreParenImpCasts()))
2950 VarTy = ASE->getElementType();
2951
2952 llvm::SmallVector<OpenACCReductionRecipe::CombinerRecipe, 1> CombinerRecipes;
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(loc: VarExpr->getBeginLoc(), ReductionOperator,
2958 VarTy, CombinerRecipes))
2959 return OpenACCReductionRecipeWithStorage::Empty();
2960
2961 VarDecl *AllocaDecl = CreateAllocaDecl(
2962 Ctx&: getASTContext(), DC: SemaRef.getCurContext(), BeginLoc: VarExpr->getBeginLoc(),
2963 VarName: &getASTContext().Idents.get(Name: "openacc.reduction.init"), VarTy);
2964
2965 Sema::TentativeAnalysisScope Trap{SemaRef};
2966 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var: AllocaDecl);
2967
2968 InitKind IK = InitKind::Invalid;
2969 switch (ReductionOperator) {
2970 case OpenACCReductionOperator::Invalid:
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;
2976 case OpenACCReductionOperator::Max:
2977 IK = InitKind::Least;
2978 break;
2979 case OpenACCReductionOperator::Min:
2980 IK = InitKind::Largest;
2981 break;
2982 case OpenACCReductionOperator::BitwiseAnd:
2983 IK = InitKind::AllOnes;
2984 break;
2985 case OpenACCReductionOperator::Multiplication:
2986 case OpenACCReductionOperator::And:
2987 IK = InitKind::One;
2988 break;
2989 case OpenACCReductionOperator::Addition:
2990 case OpenACCReductionOperator::BitwiseOr:
2991 case OpenACCReductionOperator::BitwiseXOr:
2992 case OpenACCReductionOperator::Or:
2993 IK = InitKind::Zero;
2994 break;
2995 }
2996
2997 Expr *InitExpr = GenerateReductionInitRecipeExpr(
2998 Context&: getASTContext(), ExprRange: VarExpr->getSourceRange(), Ty: VarTy, IK);
2999
3000 ExprResult Init = FinishValueInit(S&: SemaRef.SemaRef, Entity,
3001 Loc: 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,
3016 llvm::SmallVectorImpl<OpenACCReductionRecipe::CombinerRecipe>
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) {
3026 case OpenACCReductionOperator::Invalid:
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(Elt: {.LHS: nullptr, .RHS: nullptr, .Op: nullptr});
3031 return false;
3032 case OpenACCReductionOperator::Addition:
3033 BinOp = BinaryOperatorKind::BO_AddAssign;
3034 break;
3035 case OpenACCReductionOperator::Multiplication:
3036 BinOp = BinaryOperatorKind::BO_MulAssign;
3037 break;
3038 case OpenACCReductionOperator::BitwiseAnd:
3039 BinOp = BinaryOperatorKind::BO_AndAssign;
3040 break;
3041 case OpenACCReductionOperator::BitwiseOr:
3042 BinOp = BinaryOperatorKind::BO_OrAssign;
3043 break;
3044 case OpenACCReductionOperator::BitwiseXOr:
3045 BinOp = BinaryOperatorKind::BO_XorAssign;
3046 break;
3047
3048 case OpenACCReductionOperator::Max:
3049 case OpenACCReductionOperator::Min:
3050 BinOp = BinaryOperatorKind::BO_LT;
3051 break;
3052 case OpenACCReductionOperator::And:
3053 BinOp = BinaryOperatorKind::BO_LAnd;
3054 break;
3055 case OpenACCReductionOperator::Or:
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(T: 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(S: SemaRef.getCurScope(), OpLoc: Loc, Opc: BinOp, LHSExpr: LHSDRE, RHSExpr: RHSDRE,
3078 /*ForFoldExpr=*/ForFoldExpression: false);
3079 switch (ReductionOperator) {
3080 case OpenACCReductionOperator::Addition:
3081 case OpenACCReductionOperator::Multiplication:
3082 case OpenACCReductionOperator::BitwiseAnd:
3083 case OpenACCReductionOperator::BitwiseOr:
3084 case OpenACCReductionOperator::BitwiseXOr:
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};
3089 case OpenACCReductionOperator::Max:
3090 case OpenACCReductionOperator::Min: {
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(QuestionLoc: Loc, ColonLoc: Loc, CondExpr: BinOpRes.get(), LHSExpr: LHSDRE,
3104 RHSExpr: RHSDRE);
3105 else
3106 CondRes = SemaRef.ActOnConditionalOp(QuestionLoc: Loc, ColonLoc: Loc, CondExpr: BinOpRes.get(), LHSExpr: RHSDRE,
3107 RHSExpr: LHSDRE);
3108
3109 if (!CondRes.isUsable())
3110 return {CondRes, CombinerFailureKind::Conditional};
3111
3112 // Build assignment.
3113 ExprResult Assignment = SemaRef.BuildBinOp(S: SemaRef.getCurScope(), OpLoc: Loc,
3114 Opc: BinaryOperatorKind::BO_Assign,
3115 LHSExpr: LHSDRE, RHSExpr: CondRes.get(),
3116 /*ForFoldExpr=*/ForFoldExpression: false);
3117 return {Assignment, Assignment.isUsable()
3118 ? CombinerFailureKind::None
3119 : CombinerFailureKind::Assignment};
3120 }
3121 case OpenACCReductionOperator::And:
3122 case OpenACCReductionOperator::Or: {
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(S: SemaRef.getCurScope(), OpLoc: Loc,
3130 Opc: BinaryOperatorKind::BO_Assign,
3131 LHSExpr: LHSDRE, RHSExpr: BinOpRes.get(),
3132 /*ForFoldExpr=*/ForFoldExpression: false);
3133 return {Assignment, Assignment.isUsable()
3134 ? CombinerFailureKind::None
3135 : CombinerFailureKind::Assignment};
3136 }
3137 case OpenACCReductionOperator::Invalid:
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 Ctx&: getASTContext(), DC: SemaRef.getCurContext(), BeginLoc: Loc,
3165 VarName: &getASTContext().Idents.get(Name: "openacc.reduction.combiner.lhs"), VarTy: Ty);
3166 auto *LHSDRE = DeclRefExpr::Create(
3167 Context: getASTContext(), QualifierLoc: NestedNameSpecifierLoc{}, TemplateKWLoc: SourceLocation{}, D: LHSDecl,
3168 /*ReferstoEnclosingVariableOrCapture=*/RefersToEnclosingVariableOrCapture: false,
3169 NameInfo: DeclarationNameInfo{DeclarationName{LHSDecl->getDeclName()},
3170 LHSDecl->getBeginLoc()},
3171 T: Ty, VK: clang::VK_LValue, FoundD: LHSDecl, TemplateArgs: nullptr, NOUR: NOUR_None);
3172 VarDecl *RHSDecl = CreateAllocaDecl(
3173 Ctx&: getASTContext(), DC: SemaRef.getCurContext(), BeginLoc: Loc,
3174 VarName: &getASTContext().Idents.get(Name: "openacc.reduction.combiner.lhs"), VarTy: Ty);
3175 auto *RHSDRE = DeclRefExpr::Create(
3176 Context: getASTContext(), QualifierLoc: NestedNameSpecifierLoc{}, TemplateKWLoc: SourceLocation{}, D: RHSDecl,
3177 /*ReferstoEnclosingVariableOrCapture=*/RefersToEnclosingVariableOrCapture: false,
3178 NameInfo: DeclarationNameInfo{DeclarationName{RHSDecl->getDeclName()},
3179 RHSDecl->getBeginLoc()},
3180 T: Ty, VK: clang::VK_LValue, FoundD: RHSDecl, TemplateArgs: nullptr, NOUR: NOUR_None);
3181
3182 std::pair<ExprResult, CombinerFailureKind> BinOpResult =
3183 tryCombiner(LHSDRE, RHSDRE, /*IncludeTrap=*/true);
3184
3185 return {.FailKind: BinOpResult.second, .LHS: LHSDecl, .LHSDRE: LHSDRE, .RHS: RHSDecl, .RHSDRE: RHSDRE,
3186 .Op: 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(Elt: {.LHS: nullptr, .RHS: nullptr, .Op: nullptr});
3197 return false;
3198 } else if (!TopLevelCombinerInfo.Op->containsErrors()) {
3199 // Else, we succeeded, we can just return this combiner.
3200 CombinerRecipes.push_back(Elt: {.LHS: TopLevelCombinerInfo.LHS,
3201 .RHS: TopLevelCombinerInfo.RHS,
3202 .Op: TopLevelCombinerInfo.Op});
3203 return false;
3204 }
3205 }
3206
3207 auto EmitFailureNote = [&](CombinerFailureKind CFK) {
3208 if (CFK == CombinerFailureKind::BinOp)
3209 return Diag(Loc, DiagID: diag::note_acc_reduction_combiner_forming)
3210 << CFK << BinaryOperator::getOpcodeStr(Op: BinOp);
3211 return Diag(Loc, DiagID: 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, DiagID: 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, DiagID: diag::err_acc_reduction_recipe_no_op) << FD->getType();
3231 Diag(Loc: FD->getBeginLoc(), DiagID: 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(Elt: {.LHS: nullptr, .RHS: nullptr, .Op: nullptr});
3242 } else {
3243 CombinerRecipes.push_back(
3244 Elt: {.LHS: FieldCombinerInfo.LHS, .RHS: FieldCombinerInfo.RHS, .Op: FieldCombinerInfo.Op});
3245 }
3246 }
3247
3248 return false;
3249}
3250