blob: 9232ab9d6e81501c94bb13c62041c0c52de929c4 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
142 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 bool NowaitRegion = false;
144 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000145 bool LoopStart = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000146 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000147 /// Reference to the taskgroup task_reduction reference expression.
148 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000149 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000150 /// List of globals marked as declare target link in this target region
151 /// (isOpenMPTargetExecutionDirective(Directive) == true).
152 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000153 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000154 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000155 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
156 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000157 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158 };
159
Alexey Bataeve3727102018-04-18 15:57:46 +0000160 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000162 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000163 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000164 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
165 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000166 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000167 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000168 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000169 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000171 /// true if all the vaiables in the target executable directives must be
172 /// captured by reference.
173 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000174 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000175
Alexey Bataeve3727102018-04-18 15:57:46 +0000176 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000181 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000182
Alexey Bataev4b465392017-04-26 15:06:24 +0000183 bool isStackEmpty() const {
184 return Stack.empty() ||
185 Stack.back().second != CurrentNonCapturingFunctionScope ||
186 Stack.back().first.empty();
187 }
188
Kelvin Li1408f912018-09-26 04:28:39 +0000189 /// Vector of previously declared requires directives
190 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000191 /// omp_allocator_handle_t type.
192 QualType OMPAllocatorHandleT;
193 /// Expression for the predefined allocators.
194 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
195 nullptr};
Kelvin Li1408f912018-09-26 04:28:39 +0000196
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000198 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000199
Alexey Bataev27ef9512019-03-20 20:14:22 +0000200 /// Sets omp_allocator_handle_t type.
201 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
202 /// Gets omp_allocator_handle_t type.
203 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
204 /// Sets the given default allocator.
205 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
206 Expr *Allocator) {
207 OMPPredefinedAllocators[AllocatorKind] = Allocator;
208 }
209 /// Returns the specified default allocator.
210 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
211 return OMPPredefinedAllocators[AllocatorKind];
212 }
213
Alexey Bataevaac108a2015-06-23 04:51:00 +0000214 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000215 OpenMPClauseKind getClauseParsingMode() const {
216 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
217 return ClauseKindMode;
218 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000219 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000221 bool isForceVarCapturing() const { return ForceCapturing; }
222 void setForceVarCapturing(bool V) { ForceCapturing = V; }
223
Alexey Bataev60705422018-10-30 15:50:12 +0000224 void setForceCaptureByReferenceInTargetExecutable(bool V) {
225 ForceCaptureByReferenceInTargetExecutable = V;
226 }
227 bool isForceCaptureByReferenceInTargetExecutable() const {
228 return ForceCaptureByReferenceInTargetExecutable;
229 }
230
Alexey Bataev758e55e2013-09-06 18:03:48 +0000231 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000232 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000233 if (Stack.empty() ||
234 Stack.back().second != CurrentNonCapturingFunctionScope)
235 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
236 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
237 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000238 }
239
240 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000241 assert(!Stack.back().first.empty() &&
242 "Data-sharing attributes stack is empty!");
243 Stack.back().first.pop_back();
244 }
245
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000246 /// Marks that we're started loop parsing.
247 void loopInit() {
248 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
249 "Expected loop-based directive.");
250 Stack.back().first.back().LoopStart = true;
251 }
252 /// Start capturing of the variables in the loop context.
253 void loopStart() {
254 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
255 "Expected loop-based directive.");
256 Stack.back().first.back().LoopStart = false;
257 }
258 /// true, if variables are captured, false otherwise.
259 bool isLoopStarted() const {
260 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
261 "Expected loop-based directive.");
262 return !Stack.back().first.back().LoopStart;
263 }
264 /// Marks (or clears) declaration as possibly loop counter.
265 void resetPossibleLoopCounter(const Decl *D = nullptr) {
266 Stack.back().first.back().PossiblyLoopCounter =
267 D ? D->getCanonicalDecl() : D;
268 }
269 /// Gets the possible loop counter decl.
270 const Decl *getPossiblyLoopCunter() const {
271 return Stack.back().first.back().PossiblyLoopCounter;
272 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000273 /// Start new OpenMP region stack in new non-capturing function.
274 void pushFunction() {
275 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
276 assert(!isa<CapturingScopeInfo>(CurFnScope));
277 CurrentNonCapturingFunctionScope = CurFnScope;
278 }
279 /// Pop region stack for non-capturing function.
280 void popFunction(const FunctionScopeInfo *OldFSI) {
281 if (!Stack.empty() && Stack.back().second == OldFSI) {
282 assert(Stack.back().first.empty());
283 Stack.pop_back();
284 }
285 CurrentNonCapturingFunctionScope = nullptr;
286 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
287 if (!isa<CapturingScopeInfo>(FSI)) {
288 CurrentNonCapturingFunctionScope = FSI;
289 break;
290 }
291 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000292 }
293
Alexey Bataeve3727102018-04-18 15:57:46 +0000294 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000295 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000296 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000297 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000298 getCriticalWithHint(const DeclarationNameInfo &Name) const {
299 auto I = Criticals.find(Name.getAsString());
300 if (I != Criticals.end())
301 return I->second;
302 return std::make_pair(nullptr, llvm::APSInt());
303 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000305 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000306 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000307 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000308
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000309 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000310 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000311 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000312 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000313 /// \return The index of the loop control variable in the list of associated
314 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000315 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000316 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000317 /// parent region.
318 /// \return The index of the loop control variable in the list of associated
319 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000320 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000322 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000323 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000324
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000325 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000326 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000327 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000328
Alexey Bataevfa312f32017-07-21 18:48:21 +0000329 /// Adds additional information for the reduction items with the reduction id
330 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000331 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000332 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000333 /// Adds additional information for the reduction items with the reduction id
334 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000335 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000336 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000337 /// Returns the location and reduction operation from the innermost parent
338 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000339 const DSAVarData
340 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
341 BinaryOperatorKind &BOK,
342 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000343 /// Returns the location and reduction operation from the innermost parent
344 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000345 const DSAVarData
346 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
347 const Expr *&ReductionRef,
348 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000349 /// Return reduction reference expression for the current taskgroup.
350 Expr *getTaskgroupReductionRef() const {
351 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
352 "taskgroup reference expression requested for non taskgroup "
353 "directive.");
354 return Stack.back().first.back().TaskgroupReductionRef;
355 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000356 /// Checks if the given \p VD declaration is actually a taskgroup reduction
357 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000358 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000359 return Stack.back().first[Level].TaskgroupReductionRef &&
360 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
361 ->getDecl() == VD;
362 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000363
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000364 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000365 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000366 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000367 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000368 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000370 /// match specified \a CPred predicate in any directive which matches \a DPred
371 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000372 const DSAVarData
373 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
374 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
375 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000376 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000377 /// match specified \a CPred predicate in any innermost directive which
378 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000379 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000380 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000381 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
382 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000383 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000385 /// attributes which match specified \a CPred predicate at the specified
386 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000387 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000388 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000389 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000390
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000391 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000392 /// specified \a DPred predicate.
393 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000394 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000395 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000396
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000397 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000398 bool hasDirective(
399 const llvm::function_ref<bool(
400 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
401 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000402 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000403
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000405 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000407 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000408 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000409 OpenMPDirectiveKind getDirective(unsigned Level) const {
410 assert(!isStackEmpty() && "No directive at specified level.");
411 return Stack.back().first[Level].Directive;
412 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000413 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000414 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000415 if (isStackEmpty() || Stack.back().first.size() == 1)
416 return OMPD_unknown;
417 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000418 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000419
Kelvin Li1408f912018-09-26 04:28:39 +0000420 /// Add requires decl to internal vector
421 void addRequiresDecl(OMPRequiresDecl *RD) {
422 RequiresDecls.push_back(RD);
423 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000424
Kelvin Li1408f912018-09-26 04:28:39 +0000425 /// Checks for a duplicate clause amongst previously declared requires
426 /// directives
427 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
428 bool IsDuplicate = false;
429 for (OMPClause *CNew : ClauseList) {
430 for (const OMPRequiresDecl *D : RequiresDecls) {
431 for (const OMPClause *CPrev : D->clauselists()) {
432 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
433 SemaRef.Diag(CNew->getBeginLoc(),
434 diag::err_omp_requires_clause_redeclaration)
435 << getOpenMPClauseName(CNew->getClauseKind());
436 SemaRef.Diag(CPrev->getBeginLoc(),
437 diag::note_omp_requires_previous_clause)
438 << getOpenMPClauseName(CPrev->getClauseKind());
439 IsDuplicate = true;
440 }
441 }
442 }
443 }
444 return IsDuplicate;
445 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000446
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000448 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000449 assert(!isStackEmpty());
450 Stack.back().first.back().DefaultAttr = DSA_none;
451 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000452 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000453 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000454 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000455 assert(!isStackEmpty());
456 Stack.back().first.back().DefaultAttr = DSA_shared;
457 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000458 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000459 /// Set default data mapping attribute to 'tofrom:scalar'.
460 void setDefaultDMAToFromScalar(SourceLocation Loc) {
461 assert(!isStackEmpty());
462 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
463 Stack.back().first.back().DefaultMapAttrLoc = Loc;
464 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000465
466 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000467 return isStackEmpty() ? DSA_unspecified
468 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000469 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000471 return isStackEmpty() ? SourceLocation()
472 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000473 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000474 DefaultMapAttributes getDefaultDMA() const {
475 return isStackEmpty() ? DMA_unspecified
476 : Stack.back().first.back().DefaultMapAttr;
477 }
478 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
479 return Stack.back().first[Level].DefaultMapAttr;
480 }
481 SourceLocation getDefaultDMALocation() const {
482 return isStackEmpty() ? SourceLocation()
483 : Stack.back().first.back().DefaultMapAttrLoc;
484 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000487 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000488 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000489 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000490 }
491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000492 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000493 void setOrderedRegion(bool IsOrdered, const Expr *Param,
494 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000495 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000496 if (IsOrdered)
497 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
498 else
499 Stack.back().first.back().OrderedRegion.reset();
500 }
501 /// Returns true, if region is ordered (has associated 'ordered' clause),
502 /// false - otherwise.
503 bool isOrderedRegion() const {
504 if (isStackEmpty())
505 return false;
506 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
507 }
508 /// Returns optional parameter for the ordered region.
509 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
510 if (isStackEmpty() ||
511 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
512 return std::make_pair(nullptr, nullptr);
513 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000514 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000516 /// 'ordered' clause), false - otherwise.
517 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000518 if (isStackEmpty() || Stack.back().first.size() == 1)
519 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000520 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000521 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000522 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000523 std::pair<const Expr *, OMPOrderedClause *>
524 getParentOrderedRegionParam() const {
525 if (isStackEmpty() || Stack.back().first.size() == 1 ||
526 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
527 return std::make_pair(nullptr, nullptr);
528 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000529 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000530 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000531 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000532 assert(!isStackEmpty());
533 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000534 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000535 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000536 /// 'nowait' clause), false - otherwise.
537 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000538 if (isStackEmpty() || Stack.back().first.size() == 1)
539 return false;
540 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000541 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000543 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000544 if (!isStackEmpty() && Stack.back().first.size() > 1) {
545 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
546 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
547 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000548 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000549 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000550 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000551 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000552 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000553
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000554 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000555 void setAssociatedLoops(unsigned Val) {
556 assert(!isStackEmpty());
557 Stack.back().first.back().AssociatedLoops = Val;
558 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000559 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000564 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000565 /// region.
566 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000567 if (!isStackEmpty() && Stack.back().first.size() > 1) {
568 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
569 TeamsRegionLoc;
570 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000571 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000572 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000573 bool hasInnerTeamsRegion() const {
574 return getInnerTeamsRegionLoc().isValid();
575 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000576 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000577 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000578 return isStackEmpty() ? SourceLocation()
579 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000580 }
581
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000582 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000583 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000584 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000585 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000586 return isStackEmpty() ? SourceLocation()
587 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000588 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000589
Samuel Antao4c8035b2016-12-12 18:00:20 +0000590 /// Do the check specified in \a Check to all component lists and return true
591 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000592 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000593 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000594 const llvm::function_ref<
595 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000596 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000597 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000598 if (isStackEmpty())
599 return false;
600 auto SI = Stack.back().first.rbegin();
601 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000602
603 if (SI == SE)
604 return false;
605
Alexey Bataeve3727102018-04-18 15:57:46 +0000606 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000607 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000608 else
609 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000610
611 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000612 auto MI = SI->MappedExprComponents.find(VD);
613 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000614 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
615 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000616 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000617 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000618 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000619 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000620 }
621
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000622 /// Do the check specified in \a Check to all component lists at a given level
623 /// and return true if any issue is found.
624 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000625 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000626 const llvm::function_ref<
627 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000628 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000629 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000630 if (isStackEmpty())
631 return false;
632
633 auto StartI = Stack.back().first.begin();
634 auto EndI = Stack.back().first.end();
635 if (std::distance(StartI, EndI) <= (int)Level)
636 return false;
637 std::advance(StartI, Level);
638
639 auto MI = StartI->MappedExprComponents.find(VD);
640 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000641 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
642 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000643 if (Check(L, MI->second.Kind))
644 return true;
645 return false;
646 }
647
Samuel Antao4c8035b2016-12-12 18:00:20 +0000648 /// Create a new mappable expression component list associated with a given
649 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000650 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000652 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
653 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000654 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000655 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000656 MappedExprComponentTy &MEC =
657 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000658 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000659 MEC.Components.resize(MEC.Components.size() + 1);
660 MEC.Components.back().append(Components.begin(), Components.end());
661 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000662 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000663
664 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000665 assert(!isStackEmpty());
666 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000667 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000668 void addDoacrossDependClause(OMPDependClause *C,
669 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000670 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000671 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000672 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000673 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000674 }
675 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
676 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000677 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000678 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000679 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000680 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000681 return llvm::make_range(Ref.begin(), Ref.end());
682 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000683 return llvm::make_range(StackElem.DoacrossDepends.end(),
684 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000685 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000686
687 // Store types of classes which have been explicitly mapped
688 void addMappedClassesQualTypes(QualType QT) {
689 SharingMapTy &StackElem = Stack.back().first.back();
690 StackElem.MappedClassesQualTypes.insert(QT);
691 }
692
693 // Return set of mapped classes types
694 bool isClassPreviouslyMapped(QualType QT) const {
695 const SharingMapTy &StackElem = Stack.back().first.back();
696 return StackElem.MappedClassesQualTypes.count(QT) != 0;
697 }
698
Alexey Bataeva495c642019-03-11 19:51:42 +0000699 /// Adds global declare target to the parent target region.
700 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
701 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
702 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
703 "Expected declare target link global.");
704 if (isStackEmpty())
705 return;
706 auto It = Stack.back().first.rbegin();
707 while (It != Stack.back().first.rend() &&
708 !isOpenMPTargetExecutionDirective(It->Directive))
709 ++It;
710 if (It != Stack.back().first.rend()) {
711 assert(isOpenMPTargetExecutionDirective(It->Directive) &&
712 "Expected target executable directive.");
713 It->DeclareTargetLinkVarDecls.push_back(E);
714 }
715 }
716
717 /// Returns the list of globals with declare target link if current directive
718 /// is target.
719 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
720 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
721 "Expected target executable directive.");
722 return Stack.back().first.back().DeclareTargetLinkVarDecls;
723 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000724};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000725
726bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
727 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
728}
729
730bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
731 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000732}
Alexey Bataeve3727102018-04-18 15:57:46 +0000733
Alexey Bataeved09d242014-05-28 05:53:51 +0000734} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735
Alexey Bataeve3727102018-04-18 15:57:46 +0000736static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000737 if (const auto *FE = dyn_cast<FullExpr>(E))
738 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000739
Alexey Bataeve3727102018-04-18 15:57:46 +0000740 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000741 E = MTE->GetTemporaryExpr();
742
Alexey Bataeve3727102018-04-18 15:57:46 +0000743 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000744 E = Binder->getSubExpr();
745
Alexey Bataeve3727102018-04-18 15:57:46 +0000746 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000747 E = ICE->getSubExprAsWritten();
748 return E->IgnoreParens();
749}
750
Alexey Bataeve3727102018-04-18 15:57:46 +0000751static Expr *getExprAsWritten(Expr *E) {
752 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
753}
754
755static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
756 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
757 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000758 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000759 const auto *VD = dyn_cast<VarDecl>(D);
760 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000761 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000762 VD = VD->getCanonicalDecl();
763 D = VD;
764 } else {
765 assert(FD);
766 FD = FD->getCanonicalDecl();
767 D = FD;
768 }
769 return D;
770}
771
Alexey Bataeve3727102018-04-18 15:57:46 +0000772static ValueDecl *getCanonicalDecl(ValueDecl *D) {
773 return const_cast<ValueDecl *>(
774 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
775}
776
777DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
778 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000779 D = getCanonicalDecl(D);
780 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000782 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000783 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000784 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
785 // in a region but not in construct]
786 // File-scope or namespace-scope variables referenced in called routines
787 // in the region are shared unless they appear in a threadprivate
788 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000789 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000790 DVar.CKind = OMPC_shared;
791
792 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
793 // in a region but not in construct]
794 // Variables with static storage duration that are declared in called
795 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000796 if (VD && VD->hasGlobalStorage())
797 DVar.CKind = OMPC_shared;
798
799 // Non-static data members are shared by default.
800 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000801 DVar.CKind = OMPC_shared;
802
Alexey Bataev758e55e2013-09-06 18:03:48 +0000803 return DVar;
804 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000805
Alexey Bataevec3da872014-01-31 05:15:34 +0000806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
807 // in a Construct, C/C++, predetermined, p.1]
808 // Variables with automatic storage duration that are declared in a scope
809 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000810 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
811 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000812 DVar.CKind = OMPC_private;
813 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000814 }
815
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000816 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000817 // Explicitly specified attributes and local variables with predetermined
818 // attributes.
819 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000820 const DSAInfo &Data = Iter->SharingMap.lookup(D);
821 DVar.RefExpr = Data.RefExpr.getPointer();
822 DVar.PrivateCopy = Data.PrivateCopy;
823 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000824 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000825 return DVar;
826 }
827
828 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
829 // in a Construct, C/C++, implicitly determined, p.1]
830 // In a parallel or task construct, the data-sharing attributes of these
831 // variables are determined by the default clause, if present.
832 switch (Iter->DefaultAttr) {
833 case DSA_shared:
834 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000835 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836 return DVar;
837 case DSA_none:
838 return DVar;
839 case DSA_unspecified:
840 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
841 // in a Construct, implicitly determined, p.2]
842 // In a parallel construct, if no default clause is present, these
843 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000844 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000845 if (isOpenMPParallelDirective(DVar.DKind) ||
846 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000847 DVar.CKind = OMPC_shared;
848 return DVar;
849 }
850
851 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
852 // in a Construct, implicitly determined, p.4]
853 // In a task construct, if no default clause is present, a variable that in
854 // the enclosing context is determined to be shared by all implicit tasks
855 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000856 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000857 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000858 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000859 do {
860 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000861 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000862 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000863 // In a task construct, if no default clause is present, a variable
864 // whose data-sharing attribute is not determined by the rules above is
865 // firstprivate.
866 DVarTemp = getDSA(I, D);
867 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000868 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000869 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000870 return DVar;
871 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000872 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000873 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000874 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000875 return DVar;
876 }
877 }
878 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
879 // in a Construct, implicitly determined, p.3]
880 // For constructs other than task, if no default clause is present, these
881 // variables inherit their data-sharing attributes from the enclosing
882 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000883 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000884}
885
Alexey Bataeve3727102018-04-18 15:57:46 +0000886const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
887 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000888 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000889 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000890 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000891 auto It = StackElem.AlignedMap.find(D);
892 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000893 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000894 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000895 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000896 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000897 assert(It->second && "Unexpected nullptr expr in the aligned map");
898 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000899}
900
Alexey Bataeve3727102018-04-18 15:57:46 +0000901void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000902 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000903 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000904 SharingMapTy &StackElem = Stack.back().first.back();
905 StackElem.LCVMap.try_emplace(
906 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000907}
908
Alexey Bataeve3727102018-04-18 15:57:46 +0000909const DSAStackTy::LCDeclInfo
910DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000911 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000912 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000914 auto It = StackElem.LCVMap.find(D);
915 if (It != StackElem.LCVMap.end())
916 return It->second;
917 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000918}
919
Alexey Bataeve3727102018-04-18 15:57:46 +0000920const DSAStackTy::LCDeclInfo
921DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000922 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
923 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000924 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000925 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000926 auto It = StackElem.LCVMap.find(D);
927 if (It != StackElem.LCVMap.end())
928 return It->second;
929 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000930}
931
Alexey Bataeve3727102018-04-18 15:57:46 +0000932const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000933 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
934 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000935 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000936 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000937 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000939 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000940 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000941 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000942}
943
Alexey Bataeve3727102018-04-18 15:57:46 +0000944void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000945 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000946 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000947 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000948 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000949 Data.Attributes = A;
950 Data.RefExpr.setPointer(E);
951 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000952 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000953 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000954 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000955 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
956 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
957 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
958 (isLoopControlVariable(D).first && A == OMPC_private));
959 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
960 Data.RefExpr.setInt(/*IntVal=*/true);
961 return;
962 }
963 const bool IsLastprivate =
964 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
965 Data.Attributes = A;
966 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
967 Data.PrivateCopy = PrivateCopy;
968 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000969 DSAInfo &Data =
970 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000971 Data.Attributes = A;
972 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
973 Data.PrivateCopy = nullptr;
974 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 }
976}
977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000978/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000979static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000980 StringRef Name, const AttrVec *Attrs = nullptr,
981 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000982 DeclContext *DC = SemaRef.CurContext;
983 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
984 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000985 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000986 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
987 if (Attrs) {
988 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
989 I != E; ++I)
990 Decl->addAttr(*I);
991 }
992 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000993 if (OrigRef) {
994 Decl->addAttr(
995 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
996 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000997 return Decl;
998}
999
1000static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1001 SourceLocation Loc,
1002 bool RefersToCapture = false) {
1003 D->setReferenced();
1004 D->markUsed(S.Context);
1005 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1006 SourceLocation(), D, RefersToCapture, Loc, Ty,
1007 VK_LValue);
1008}
1009
Alexey Bataeve3727102018-04-18 15:57:46 +00001010void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001011 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012 D = getCanonicalDecl(D);
1013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001014 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001015 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001016 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001017 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001019 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001020 "Additional reduction info may be specified only once for reduction "
1021 "items.");
1022 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001023 Expr *&TaskgroupReductionRef =
1024 Stack.back().first.back().TaskgroupReductionRef;
1025 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001026 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1027 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001028 TaskgroupReductionRef =
1029 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001030 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001031}
1032
Alexey Bataeve3727102018-04-18 15:57:46 +00001033void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001034 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001035 D = getCanonicalDecl(D);
1036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001037 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001038 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001039 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001040 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001042 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001043 "Additional reduction info may be specified only once for reduction "
1044 "items.");
1045 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001046 Expr *&TaskgroupReductionRef =
1047 Stack.back().first.back().TaskgroupReductionRef;
1048 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001049 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1050 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001051 TaskgroupReductionRef =
1052 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001053 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001054}
1055
Alexey Bataeve3727102018-04-18 15:57:46 +00001056const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1057 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1058 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001059 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001060 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1061 if (Stack.back().first.empty())
1062 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001063 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1064 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001066 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001067 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001068 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001069 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001070 if (!ReductionData.ReductionOp ||
1071 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001072 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001073 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001074 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001075 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1076 "expression for the descriptor is not "
1077 "set.");
1078 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001079 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1080 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001081 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001082 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001083}
1084
Alexey Bataeve3727102018-04-18 15:57:46 +00001085const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1086 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1087 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001088 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001089 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1090 if (Stack.back().first.empty())
1091 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001092 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1093 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001094 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001095 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001096 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001097 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001098 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001099 if (!ReductionData.ReductionOp ||
1100 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001101 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001102 SR = ReductionData.ReductionRange;
1103 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001104 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1105 "expression for the descriptor is not "
1106 "set.");
1107 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001108 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1109 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001110 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001111 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001112}
1113
Alexey Bataeve3727102018-04-18 15:57:46 +00001114bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001115 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001116 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001117 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001118 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001119 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001120 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001121 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001122 if (I == E)
1123 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001124 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001125 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001126 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001127 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001128 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001129 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001130 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001131}
1132
Joel E. Dennyd2649292019-01-04 22:11:56 +00001133static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1134 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001135 bool *IsClassType = nullptr) {
1136 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001137 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001138 bool IsConstant = Type.isConstant(Context);
1139 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001140 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1141 ? Type->getAsCXXRecordDecl()
1142 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001143 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1144 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1145 RD = CTD->getTemplatedDecl();
1146 if (IsClassType)
1147 *IsClassType = RD;
1148 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1149 RD->hasDefinition() && RD->hasMutableFields());
1150}
1151
Joel E. Dennyd2649292019-01-04 22:11:56 +00001152static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1153 QualType Type, OpenMPClauseKind CKind,
1154 SourceLocation ELoc,
1155 bool AcceptIfMutable = true,
1156 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001157 ASTContext &Context = SemaRef.getASTContext();
1158 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001159 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1160 unsigned Diag = ListItemNotVar
1161 ? diag::err_omp_const_list_item
1162 : IsClassType ? diag::err_omp_const_not_mutable_variable
1163 : diag::err_omp_const_variable;
1164 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1165 if (!ListItemNotVar && D) {
1166 const VarDecl *VD = dyn_cast<VarDecl>(D);
1167 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1168 VarDecl::DeclarationOnly;
1169 SemaRef.Diag(D->getLocation(),
1170 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1171 << D;
1172 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001173 return true;
1174 }
1175 return false;
1176}
1177
Alexey Bataeve3727102018-04-18 15:57:46 +00001178const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1179 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001180 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001181 DSAVarData DVar;
1182
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001183 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001184 auto TI = Threadprivates.find(D);
1185 if (TI != Threadprivates.end()) {
1186 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001187 DVar.CKind = OMPC_threadprivate;
1188 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001189 }
1190 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001191 DVar.RefExpr = buildDeclRefExpr(
1192 SemaRef, VD, D->getType().getNonReferenceType(),
1193 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1194 DVar.CKind = OMPC_threadprivate;
1195 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001196 return DVar;
1197 }
1198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1199 // in a Construct, C/C++, predetermined, p.1]
1200 // Variables appearing in threadprivate directives are threadprivate.
1201 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1202 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1203 SemaRef.getLangOpts().OpenMPUseTLS &&
1204 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1205 (VD && VD->getStorageClass() == SC_Register &&
1206 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1207 DVar.RefExpr = buildDeclRefExpr(
1208 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1209 DVar.CKind = OMPC_threadprivate;
1210 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1211 return DVar;
1212 }
1213 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1214 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1215 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001216 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001217 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1218 [](const SharingMapTy &Data) {
1219 return isOpenMPTargetExecutionDirective(Data.Directive);
1220 });
1221 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001222 iterator ParentIterTarget = std::next(IterTarget, 1);
1223 for (iterator Iter = Stack.back().first.rbegin();
1224 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001225 if (isOpenMPLocal(VD, Iter)) {
1226 DVar.RefExpr =
1227 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1228 D->getLocation());
1229 DVar.CKind = OMPC_threadprivate;
1230 return DVar;
1231 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001232 }
1233 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1234 auto DSAIter = IterTarget->SharingMap.find(D);
1235 if (DSAIter != IterTarget->SharingMap.end() &&
1236 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1237 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1238 DVar.CKind = OMPC_threadprivate;
1239 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001240 }
1241 iterator End = Stack.back().first.rend();
1242 if (!SemaRef.isOpenMPCapturedByRef(
1243 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001244 DVar.RefExpr =
1245 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1246 IterTarget->ConstructLoc);
1247 DVar.CKind = OMPC_threadprivate;
1248 return DVar;
1249 }
1250 }
1251 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001252 }
1253
Alexey Bataev4b465392017-04-26 15:06:24 +00001254 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001255 // Not in OpenMP execution region and top scope was already checked.
1256 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001257
Alexey Bataev758e55e2013-09-06 18:03:48 +00001258 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001259 // in a Construct, C/C++, predetermined, p.4]
1260 // Static data members are shared.
1261 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1262 // in a Construct, C/C++, predetermined, p.7]
1263 // Variables with static storage duration that are declared in a scope
1264 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001265 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001266 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001267 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001268 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001269 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001270
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001271 DVar.CKind = OMPC_shared;
1272 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001273 }
1274
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001275 // The predetermined shared attribute for const-qualified types having no
1276 // mutable members was removed after OpenMP 3.1.
1277 if (SemaRef.LangOpts.OpenMP <= 31) {
1278 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1279 // in a Construct, C/C++, predetermined, p.6]
1280 // Variables with const qualified type having no mutable member are
1281 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001282 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001283 // Variables with const-qualified type having no mutable member may be
1284 // listed in a firstprivate clause, even if they are static data members.
1285 DSAVarData DVarTemp = hasInnermostDSA(
1286 D,
1287 [](OpenMPClauseKind C) {
1288 return C == OMPC_firstprivate || C == OMPC_shared;
1289 },
1290 MatchesAlways, FromParent);
1291 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1292 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001293
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001294 DVar.CKind = OMPC_shared;
1295 return DVar;
1296 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001297 }
1298
Alexey Bataev758e55e2013-09-06 18:03:48 +00001299 // Explicitly specified attributes and local variables with predetermined
1300 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001301 iterator I = Stack.back().first.rbegin();
1302 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001303 if (FromParent && I != EndI)
1304 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001305 auto It = I->SharingMap.find(D);
1306 if (It != I->SharingMap.end()) {
1307 const DSAInfo &Data = It->getSecond();
1308 DVar.RefExpr = Data.RefExpr.getPointer();
1309 DVar.PrivateCopy = Data.PrivateCopy;
1310 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001311 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001312 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001313 }
1314
1315 return DVar;
1316}
1317
Alexey Bataeve3727102018-04-18 15:57:46 +00001318const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1319 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001320 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001322 return getDSA(I, D);
1323 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001324 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001325 iterator StartI = Stack.back().first.rbegin();
1326 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001327 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001328 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001329 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001330}
1331
Alexey Bataeve3727102018-04-18 15:57:46 +00001332const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001333DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001334 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1335 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001336 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001337 if (isStackEmpty())
1338 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001339 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001340 iterator I = Stack.back().first.rbegin();
1341 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001342 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001343 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001344 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001345 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001346 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001347 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001348 DSAVarData DVar = getDSA(NewI, D);
1349 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001350 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001351 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001352 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001353}
1354
Alexey Bataeve3727102018-04-18 15:57:46 +00001355const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001356 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1357 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001358 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001359 if (isStackEmpty())
1360 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001361 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001362 iterator StartI = Stack.back().first.rbegin();
1363 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001364 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001365 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001366 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001367 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001368 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001369 DSAVarData DVar = getDSA(NewI, D);
1370 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001371}
1372
Alexey Bataevaac108a2015-06-23 04:51:00 +00001373bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001374 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1375 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001376 if (isStackEmpty())
1377 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001378 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001379 auto StartI = Stack.back().first.begin();
1380 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001381 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001382 return false;
1383 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001384 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001385 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001386 I->getSecond().RefExpr.getPointer() &&
1387 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001388 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1389 return true;
1390 // Check predetermined rules for the loop control variables.
1391 auto LI = StartI->LCVMap.find(D);
1392 if (LI != StartI->LCVMap.end())
1393 return CPred(OMPC_private);
1394 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001395}
1396
Samuel Antao4be30e92015-10-02 17:14:03 +00001397bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001398 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1399 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001400 if (isStackEmpty())
1401 return false;
1402 auto StartI = Stack.back().first.begin();
1403 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001404 if (std::distance(StartI, EndI) <= (int)Level)
1405 return false;
1406 std::advance(StartI, Level);
1407 return DPred(StartI->Directive);
1408}
1409
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001410bool DSAStackTy::hasDirective(
1411 const llvm::function_ref<bool(OpenMPDirectiveKind,
1412 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001413 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001414 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001415 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001416 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001417 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001418 auto StartI = std::next(Stack.back().first.rbegin());
1419 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001420 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001421 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001422 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1423 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1424 return true;
1425 }
1426 return false;
1427}
1428
Alexey Bataev758e55e2013-09-06 18:03:48 +00001429void Sema::InitDataSharingAttributesStack() {
1430 VarDataSharingAttributesStack = new DSAStackTy(*this);
1431}
1432
1433#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1434
Alexey Bataev4b465392017-04-26 15:06:24 +00001435void Sema::pushOpenMPFunctionRegion() {
1436 DSAStack->pushFunction();
1437}
1438
1439void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1440 DSAStack->popFunction(OldFSI);
1441}
1442
Alexey Bataevc416e642019-02-08 18:02:25 +00001443static bool isOpenMPDeviceDelayedContext(Sema &S) {
1444 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1445 "Expected OpenMP device compilation.");
1446 return !S.isInOpenMPTargetExecutionDirective() &&
1447 !S.isInOpenMPDeclareTargetContext();
1448}
1449
1450/// Do we know that we will eventually codegen the given function?
1451static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1452 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1453 "Expected OpenMP device compilation.");
1454 // Templates are emitted when they're instantiated.
1455 if (FD->isDependentContext())
1456 return false;
1457
1458 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1459 FD->getCanonicalDecl()))
1460 return true;
1461
1462 // Otherwise, the function is known-emitted if it's in our set of
1463 // known-emitted functions.
1464 return S.DeviceKnownEmittedFns.count(FD) > 0;
1465}
1466
1467Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1468 unsigned DiagID) {
1469 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1470 "Expected OpenMP device compilation.");
1471 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1472 !isKnownEmitted(*this, getCurFunctionDecl()))
1473 ? DeviceDiagBuilder::K_Deferred
1474 : DeviceDiagBuilder::K_Immediate,
1475 Loc, DiagID, getCurFunctionDecl(), *this);
1476}
1477
1478void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1479 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1480 "Expected OpenMP device compilation.");
1481 assert(Callee && "Callee may not be null.");
1482 FunctionDecl *Caller = getCurFunctionDecl();
1483
1484 // If the caller is known-emitted, mark the callee as known-emitted.
1485 // Otherwise, mark the call in our call graph so we can traverse it later.
1486 if (!isOpenMPDeviceDelayedContext(*this) ||
1487 (Caller && isKnownEmitted(*this, Caller)))
1488 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1489 else if (Caller)
1490 DeviceCallGraph[Caller].insert({Callee, Loc});
1491}
1492
Alexey Bataev123ad192019-02-27 20:29:45 +00001493void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1494 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1495 "OpenMP device compilation mode is expected.");
1496 QualType Ty = E->getType();
1497 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1498 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1499 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1500 !Context.getTargetInfo().hasInt128Type()))
1501 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1502 << Ty << E->getSourceRange();
1503}
1504
Alexey Bataeve3727102018-04-18 15:57:46 +00001505bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001506 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1507
Alexey Bataeve3727102018-04-18 15:57:46 +00001508 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001509 bool IsByRef = true;
1510
1511 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001512 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001513 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001514
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001515 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001516 // This table summarizes how a given variable should be passed to the device
1517 // given its type and the clauses where it appears. This table is based on
1518 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1519 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1520 //
1521 // =========================================================================
1522 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1523 // | |(tofrom:scalar)| | pvt | | | |
1524 // =========================================================================
1525 // | scl | | | | - | | bycopy|
1526 // | scl | | - | x | - | - | bycopy|
1527 // | scl | | x | - | - | - | null |
1528 // | scl | x | | | - | | byref |
1529 // | scl | x | - | x | - | - | bycopy|
1530 // | scl | x | x | - | - | - | null |
1531 // | scl | | - | - | - | x | byref |
1532 // | scl | x | - | - | - | x | byref |
1533 //
1534 // | agg | n.a. | | | - | | byref |
1535 // | agg | n.a. | - | x | - | - | byref |
1536 // | agg | n.a. | x | - | - | - | null |
1537 // | agg | n.a. | - | - | - | x | byref |
1538 // | agg | n.a. | - | - | - | x[] | byref |
1539 //
1540 // | ptr | n.a. | | | - | | bycopy|
1541 // | ptr | n.a. | - | x | - | - | bycopy|
1542 // | ptr | n.a. | x | - | - | - | null |
1543 // | ptr | n.a. | - | - | - | x | byref |
1544 // | ptr | n.a. | - | - | - | x[] | bycopy|
1545 // | ptr | n.a. | - | - | x | | bycopy|
1546 // | ptr | n.a. | - | - | x | x | bycopy|
1547 // | ptr | n.a. | - | - | x | x[] | bycopy|
1548 // =========================================================================
1549 // Legend:
1550 // scl - scalar
1551 // ptr - pointer
1552 // agg - aggregate
1553 // x - applies
1554 // - - invalid in this combination
1555 // [] - mapped with an array section
1556 // byref - should be mapped by reference
1557 // byval - should be mapped by value
1558 // null - initialize a local variable to null on the device
1559 //
1560 // Observations:
1561 // - All scalar declarations that show up in a map clause have to be passed
1562 // by reference, because they may have been mapped in the enclosing data
1563 // environment.
1564 // - If the scalar value does not fit the size of uintptr, it has to be
1565 // passed by reference, regardless the result in the table above.
1566 // - For pointers mapped by value that have either an implicit map or an
1567 // array section, the runtime library may pass the NULL value to the
1568 // device instead of the value passed to it by the compiler.
1569
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001570 if (Ty->isReferenceType())
1571 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001572
1573 // Locate map clauses and see if the variable being captured is referred to
1574 // in any of those clauses. Here we only care about variables, not fields,
1575 // because fields are part of aggregates.
1576 bool IsVariableUsedInMapClause = false;
1577 bool IsVariableAssociatedWithSection = false;
1578
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001579 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001580 D, Level,
1581 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1582 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001583 MapExprComponents,
1584 OpenMPClauseKind WhereFoundClauseKind) {
1585 // Only the map clause information influences how a variable is
1586 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001587 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001588 if (WhereFoundClauseKind != OMPC_map)
1589 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001590
1591 auto EI = MapExprComponents.rbegin();
1592 auto EE = MapExprComponents.rend();
1593
1594 assert(EI != EE && "Invalid map expression!");
1595
1596 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1597 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1598
1599 ++EI;
1600 if (EI == EE)
1601 return false;
1602
1603 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1604 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1605 isa<MemberExpr>(EI->getAssociatedExpression())) {
1606 IsVariableAssociatedWithSection = true;
1607 // There is nothing more we need to know about this variable.
1608 return true;
1609 }
1610
1611 // Keep looking for more map info.
1612 return false;
1613 });
1614
1615 if (IsVariableUsedInMapClause) {
1616 // If variable is identified in a map clause it is always captured by
1617 // reference except if it is a pointer that is dereferenced somehow.
1618 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1619 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001620 // By default, all the data that has a scalar type is mapped by copy
1621 // (except for reduction variables).
1622 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001623 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1624 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001625 !Ty->isScalarType() ||
1626 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1627 DSAStack->hasExplicitDSA(
1628 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001629 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001630 }
1631
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001632 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001633 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001634 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1635 !Ty->isAnyPointerType()) ||
1636 !DSAStack->hasExplicitDSA(
1637 D,
1638 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1639 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001640 // If the variable is artificial and must be captured by value - try to
1641 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001642 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1643 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001644 }
1645
Samuel Antao86ace552016-04-27 22:40:57 +00001646 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001647 // and alignment, because the runtime library only deals with uintptr types.
1648 // If it does not fit the uintptr size, we need to pass the data by reference
1649 // instead.
1650 if (!IsByRef &&
1651 (Ctx.getTypeSizeInChars(Ty) >
1652 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001653 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001654 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001655 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001656
1657 return IsByRef;
1658}
1659
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001660unsigned Sema::getOpenMPNestingLevel() const {
1661 assert(getLangOpts().OpenMP);
1662 return DSAStack->getNestingLevel();
1663}
1664
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001665bool Sema::isInOpenMPTargetExecutionDirective() const {
1666 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1667 !DSAStack->isClauseParsingMode()) ||
1668 DSAStack->hasDirective(
1669 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1670 SourceLocation) -> bool {
1671 return isOpenMPTargetExecutionDirective(K);
1672 },
1673 false);
1674}
1675
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001676VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001677 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001678 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001679
1680 // If we are attempting to capture a global variable in a directive with
1681 // 'target' we return true so that this global is also mapped to the device.
1682 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001683 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001684 if (VD && !VD->hasLocalStorage()) {
1685 if (isInOpenMPDeclareTargetContext() &&
1686 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1687 // Try to mark variable as declare target if it is used in capturing
1688 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001689 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001690 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001691 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001692 } else if (isInOpenMPTargetExecutionDirective()) {
1693 // If the declaration is enclosed in a 'declare target' directive,
1694 // then it should not be captured.
1695 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001696 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001697 return nullptr;
1698 return VD;
1699 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001700 }
Alexey Bataev60705422018-10-30 15:50:12 +00001701 // Capture variables captured by reference in lambdas for target-based
1702 // directives.
1703 if (VD && !DSAStack->isClauseParsingMode()) {
1704 if (const auto *RD = VD->getType()
1705 .getCanonicalType()
1706 .getNonReferenceType()
1707 ->getAsCXXRecordDecl()) {
1708 bool SavedForceCaptureByReferenceInTargetExecutable =
1709 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1710 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001711 if (RD->isLambda()) {
1712 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1713 FieldDecl *ThisCapture;
1714 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001715 for (const LambdaCapture &LC : RD->captures()) {
1716 if (LC.getCaptureKind() == LCK_ByRef) {
1717 VarDecl *VD = LC.getCapturedVar();
1718 DeclContext *VDC = VD->getDeclContext();
1719 if (!VDC->Encloses(CurContext))
1720 continue;
1721 DSAStackTy::DSAVarData DVarPrivate =
1722 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1723 // Do not capture already captured variables.
1724 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1725 DVarPrivate.CKind == OMPC_unknown &&
1726 !DSAStack->checkMappableExprComponentListsForDecl(
1727 D, /*CurrentRegionOnly=*/true,
1728 [](OMPClauseMappableExprCommon::
1729 MappableExprComponentListRef,
1730 OpenMPClauseKind) { return true; }))
1731 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1732 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001733 QualType ThisTy = getCurrentThisType();
1734 if (!ThisTy.isNull() &&
1735 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1736 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001737 }
1738 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001739 }
Alexey Bataev60705422018-10-30 15:50:12 +00001740 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1741 SavedForceCaptureByReferenceInTargetExecutable);
1742 }
1743 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001744
Alexey Bataev48977c32015-08-04 08:10:48 +00001745 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1746 (!DSAStack->isClauseParsingMode() ||
1747 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001748 auto &&Info = DSAStack->isLoopControlVariable(D);
1749 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001750 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001751 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001752 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001753 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001754 DSAStackTy::DSAVarData DVarPrivate =
1755 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001756 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001757 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001758 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1759 [](OpenMPDirectiveKind) { return true; },
1760 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001761 if (DVarPrivate.CKind != OMPC_unknown)
1762 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001763 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001764 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001765}
1766
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001767void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1768 unsigned Level) const {
1769 SmallVector<OpenMPDirectiveKind, 4> Regions;
1770 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1771 FunctionScopesIndex -= Regions.size();
1772}
1773
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001774void Sema::startOpenMPLoop() {
1775 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1776 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1777 DSAStack->loopInit();
1778}
1779
Alexey Bataeve3727102018-04-18 15:57:46 +00001780bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001781 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001782 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1783 if (DSAStack->getAssociatedLoops() > 0 &&
1784 !DSAStack->isLoopStarted()) {
1785 DSAStack->resetPossibleLoopCounter(D);
1786 DSAStack->loopStart();
1787 return true;
1788 }
1789 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1790 DSAStack->isLoopControlVariable(D).first) &&
1791 !DSAStack->hasExplicitDSA(
1792 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1793 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1794 return true;
1795 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001796 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001797 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001798 (DSAStack->isClauseParsingMode() &&
1799 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001800 // Consider taskgroup reduction descriptor variable a private to avoid
1801 // possible capture in the region.
1802 (DSAStack->hasExplicitDirective(
1803 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1804 Level) &&
1805 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001806}
1807
Alexey Bataeve3727102018-04-18 15:57:46 +00001808void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1809 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001810 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1811 D = getCanonicalDecl(D);
1812 OpenMPClauseKind OMPC = OMPC_unknown;
1813 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1814 const unsigned NewLevel = I - 1;
1815 if (DSAStack->hasExplicitDSA(D,
1816 [&OMPC](const OpenMPClauseKind K) {
1817 if (isOpenMPPrivate(K)) {
1818 OMPC = K;
1819 return true;
1820 }
1821 return false;
1822 },
1823 NewLevel))
1824 break;
1825 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1826 D, NewLevel,
1827 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1828 OpenMPClauseKind) { return true; })) {
1829 OMPC = OMPC_map;
1830 break;
1831 }
1832 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1833 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001834 OMPC = OMPC_map;
1835 if (D->getType()->isScalarType() &&
1836 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1837 DefaultMapAttributes::DMA_tofrom_scalar)
1838 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001839 break;
1840 }
1841 }
1842 if (OMPC != OMPC_unknown)
1843 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1844}
1845
Alexey Bataeve3727102018-04-18 15:57:46 +00001846bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1847 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001848 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1849 // Return true if the current level is no longer enclosed in a target region.
1850
Alexey Bataeve3727102018-04-18 15:57:46 +00001851 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001852 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001853 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1854 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001855}
1856
Alexey Bataeved09d242014-05-28 05:53:51 +00001857void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001858
1859void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1860 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001861 Scope *CurScope, SourceLocation Loc) {
1862 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001863 PushExpressionEvaluationContext(
1864 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001865}
1866
Alexey Bataevaac108a2015-06-23 04:51:00 +00001867void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1868 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001869}
1870
Alexey Bataevaac108a2015-06-23 04:51:00 +00001871void Sema::EndOpenMPClause() {
1872 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001873}
1874
Alexey Bataev758e55e2013-09-06 18:03:48 +00001875void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001876 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1877 // A variable of class type (or array thereof) that appears in a lastprivate
1878 // clause requires an accessible, unambiguous default constructor for the
1879 // class type, unless the list item is also specified in a firstprivate
1880 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001881 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1882 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001883 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1884 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001885 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001886 if (DE->isValueDependent() || DE->isTypeDependent()) {
1887 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001888 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001889 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001890 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001891 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001892 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001893 const DSAStackTy::DSAVarData DVar =
1894 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001895 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001896 // Generate helper private variable and initialize it with the
1897 // default value. The address of the original variable is replaced
1898 // by the address of the new private variable in CodeGen. This new
1899 // variable is not added to IdResolver, so the code in the OpenMP
1900 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001901 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001902 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001903 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001904 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001905 if (VDPrivate->isInvalidDecl())
1906 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001907 PrivateCopies.push_back(buildDeclRefExpr(
1908 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001909 } else {
1910 // The variable is also a firstprivate, so initialization sequence
1911 // for private copy is generated already.
1912 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001913 }
1914 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001915 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001916 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001917 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001918 }
1919 }
1920 }
1921
Alexey Bataev758e55e2013-09-06 18:03:48 +00001922 DSAStack->pop();
1923 DiscardCleanupsInEvaluationContext();
1924 PopExpressionEvaluationContext();
1925}
1926
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001927static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1928 Expr *NumIterations, Sema &SemaRef,
1929 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001930
Alexey Bataeva769e072013-03-22 06:34:35 +00001931namespace {
1932
Alexey Bataeve3727102018-04-18 15:57:46 +00001933class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001934private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001935 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001936
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001937public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001938 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001939 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001940 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001941 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001942 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001943 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1944 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001945 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001946 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001947 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001948};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001949
Alexey Bataeve3727102018-04-18 15:57:46 +00001950class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001951private:
1952 Sema &SemaRef;
1953
1954public:
1955 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1956 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1957 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001958 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1959 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001960 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1961 SemaRef.getCurScope());
1962 }
1963 return false;
1964 }
1965};
1966
Alexey Bataeved09d242014-05-28 05:53:51 +00001967} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001968
1969ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1970 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001971 const DeclarationNameInfo &Id,
1972 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001973 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1974 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1975
1976 if (Lookup.isAmbiguous())
1977 return ExprError();
1978
1979 VarDecl *VD;
1980 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001981 if (TypoCorrection Corrected = CorrectTypo(
1982 Id, LookupOrdinaryName, CurScope, nullptr,
1983 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001984 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001985 PDiag(Lookup.empty()
1986 ? diag::err_undeclared_var_use_suggest
1987 : diag::err_omp_expected_var_arg_suggest)
1988 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001989 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001990 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001991 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1992 : diag::err_omp_expected_var_arg)
1993 << Id.getName();
1994 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001995 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001996 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1997 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1998 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1999 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002000 }
2001 Lookup.suppressDiagnostics();
2002
2003 // OpenMP [2.9.2, Syntax, C/C++]
2004 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002005 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002006 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002007 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002008 bool IsDecl =
2009 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002010 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002011 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2012 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002013 return ExprError();
2014 }
2015
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002016 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002017 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002018 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2019 // A threadprivate directive for file-scope variables must appear outside
2020 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002021 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2022 !getCurLexicalContext()->isTranslationUnit()) {
2023 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002024 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002025 bool IsDecl =
2026 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2027 Diag(VD->getLocation(),
2028 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2029 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002030 return ExprError();
2031 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002032 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2033 // A threadprivate directive for static class member variables must appear
2034 // in the class definition, in the same scope in which the member
2035 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002036 if (CanonicalVD->isStaticDataMember() &&
2037 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2038 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002039 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002040 bool IsDecl =
2041 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2042 Diag(VD->getLocation(),
2043 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2044 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002045 return ExprError();
2046 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002047 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2048 // A threadprivate directive for namespace-scope variables must appear
2049 // outside any definition or declaration other than the namespace
2050 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002051 if (CanonicalVD->getDeclContext()->isNamespace() &&
2052 (!getCurLexicalContext()->isFileContext() ||
2053 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2054 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002055 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002056 bool IsDecl =
2057 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2058 Diag(VD->getLocation(),
2059 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2060 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002061 return ExprError();
2062 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002063 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2064 // A threadprivate directive for static block-scope variables must appear
2065 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002066 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002067 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002068 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002069 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002070 bool IsDecl =
2071 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2072 Diag(VD->getLocation(),
2073 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2074 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002075 return ExprError();
2076 }
2077
2078 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2079 // A threadprivate directive must lexically precede all references to any
2080 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002081 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2082 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002083 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002084 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002085 return ExprError();
2086 }
2087
2088 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002089 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2090 SourceLocation(), VD,
2091 /*RefersToEnclosingVariableOrCapture=*/false,
2092 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002093}
2094
Alexey Bataeved09d242014-05-28 05:53:51 +00002095Sema::DeclGroupPtrTy
2096Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2097 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002098 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002099 CurContext->addDecl(D);
2100 return DeclGroupPtrTy::make(DeclGroupRef(D));
2101 }
David Blaikie0403cb12016-01-15 23:43:25 +00002102 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002103}
2104
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002105namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002106class LocalVarRefChecker final
2107 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002108 Sema &SemaRef;
2109
2110public:
2111 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002112 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002113 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002114 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002115 diag::err_omp_local_var_in_threadprivate_init)
2116 << E->getSourceRange();
2117 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2118 << VD << VD->getSourceRange();
2119 return true;
2120 }
2121 }
2122 return false;
2123 }
2124 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002125 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002126 if (Child && Visit(Child))
2127 return true;
2128 }
2129 return false;
2130 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002131 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002132};
2133} // namespace
2134
Alexey Bataeved09d242014-05-28 05:53:51 +00002135OMPThreadPrivateDecl *
2136Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002137 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002138 for (Expr *RefExpr : VarList) {
2139 auto *DE = cast<DeclRefExpr>(RefExpr);
2140 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002141 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002142
Alexey Bataev376b4a42016-02-09 09:41:09 +00002143 // Mark variable as used.
2144 VD->setReferenced();
2145 VD->markUsed(Context);
2146
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002147 QualType QType = VD->getType();
2148 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2149 // It will be analyzed later.
2150 Vars.push_back(DE);
2151 continue;
2152 }
2153
Alexey Bataeva769e072013-03-22 06:34:35 +00002154 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2155 // A threadprivate variable must not have an incomplete type.
2156 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002157 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002158 continue;
2159 }
2160
2161 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2162 // A threadprivate variable must not have a reference type.
2163 if (VD->getType()->isReferenceType()) {
2164 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002165 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2166 bool IsDecl =
2167 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2168 Diag(VD->getLocation(),
2169 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2170 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002171 continue;
2172 }
2173
Samuel Antaof8b50122015-07-13 22:54:53 +00002174 // Check if this is a TLS variable. If TLS is not being supported, produce
2175 // the corresponding diagnostic.
2176 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2177 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2178 getLangOpts().OpenMPUseTLS &&
2179 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002180 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2181 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002182 Diag(ILoc, diag::err_omp_var_thread_local)
2183 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002184 bool IsDecl =
2185 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2186 Diag(VD->getLocation(),
2187 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2188 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002189 continue;
2190 }
2191
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002192 // Check if initial value of threadprivate variable reference variable with
2193 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002194 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002195 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002196 if (Checker.Visit(Init))
2197 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002198 }
2199
Alexey Bataeved09d242014-05-28 05:53:51 +00002200 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002201 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002202 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2203 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002204 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002205 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002206 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002207 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002208 if (!Vars.empty()) {
2209 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2210 Vars);
2211 D->setAccess(AS_public);
2212 }
2213 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002214}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002215
Alexey Bataev27ef9512019-03-20 20:14:22 +00002216static OMPAllocateDeclAttr::AllocatorTypeTy
2217getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2218 if (!Allocator)
2219 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2220 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2221 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002222 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002223 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002224 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2225 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2226 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2227 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2228 Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002229 const Expr *AE = Allocator->IgnoreParenImpCasts();
2230 llvm::FoldingSetNodeID AEId, DAEId;
2231 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2232 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2233 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002234 AllocatorKindRes = AllocatorKind;
2235 break;
2236 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002237 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002238 return AllocatorKindRes;
2239}
2240
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002241Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2242 SourceLocation Loc, ArrayRef<Expr *> VarList,
2243 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2244 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2245 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002246 if (Clauses.empty()) {
2247 if (LangOpts.OpenMPIsDevice)
2248 targetDiag(Loc, diag::err_expected_allocator_clause);
2249 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002250 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002251 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002252 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2253 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002254 SmallVector<Expr *, 8> Vars;
2255 for (Expr *RefExpr : VarList) {
2256 auto *DE = cast<DeclRefExpr>(RefExpr);
2257 auto *VD = cast<VarDecl>(DE->getDecl());
2258
2259 // Check if this is a TLS variable or global register.
2260 if (VD->getTLSKind() != VarDecl::TLS_None ||
2261 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2262 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2263 !VD->isLocalVarDecl()))
2264 continue;
2265 // Do not apply for parameters.
2266 if (isa<ParmVarDecl>(VD))
2267 continue;
2268
Alexey Bataev282555a2019-03-19 20:33:44 +00002269 // If the used several times in the allocate directive, the same allocator
2270 // must be used.
2271 if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2272 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002273 Expr *PrevAllocator = A->getAllocator();
2274 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2275 getAllocatorKind(*this, DSAStack, PrevAllocator);
2276 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2277 if (AllocatorsMatch && Allocator && PrevAllocator) {
Alexey Bataev282555a2019-03-19 20:33:44 +00002278 const Expr *AE = Allocator->IgnoreParenImpCasts();
2279 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2280 llvm::FoldingSetNodeID AEId, PAEId;
2281 AE->Profile(AEId, Context, /*Canonical=*/true);
2282 PAE->Profile(PAEId, Context, /*Canonical=*/true);
2283 AllocatorsMatch = AEId == PAEId;
Alexey Bataev282555a2019-03-19 20:33:44 +00002284 }
2285 if (!AllocatorsMatch) {
2286 SmallString<256> AllocatorBuffer;
2287 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2288 if (Allocator)
2289 Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2290 SmallString<256> PrevAllocatorBuffer;
2291 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2292 if (PrevAllocator)
2293 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2294 getPrintingPolicy());
2295
2296 SourceLocation AllocatorLoc =
2297 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2298 SourceRange AllocatorRange =
2299 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2300 SourceLocation PrevAllocatorLoc =
2301 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2302 SourceRange PrevAllocatorRange =
2303 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2304 Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2305 << (Allocator ? 1 : 0) << AllocatorStream.str()
2306 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2307 << AllocatorRange;
2308 Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2309 << PrevAllocatorRange;
2310 continue;
2311 }
2312 }
2313
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002314 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2315 // If a list item has a static storage type, the allocator expression in the
2316 // allocator clause must be a constant expression that evaluates to one of
2317 // the predefined memory allocator values.
2318 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002319 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002320 Diag(Allocator->getExprLoc(),
2321 diag::err_omp_expected_predefined_allocator)
2322 << Allocator->getSourceRange();
2323 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2324 VarDecl::DeclarationOnly;
2325 Diag(VD->getLocation(),
2326 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2327 << VD;
2328 continue;
2329 }
2330 }
2331
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002332 Vars.push_back(RefExpr);
Alexey Bataev282555a2019-03-19 20:33:44 +00002333 if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2334 !Allocator->isValueDependent() &&
2335 !Allocator->isInstantiationDependent() &&
2336 !Allocator->containsUnexpandedParameterPack())) &&
2337 !VD->hasAttr<OMPAllocateDeclAttr>()) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002338 Attr *A = OMPAllocateDeclAttr::CreateImplicit(
2339 Context, AllocatorKind, Allocator, DE->getSourceRange());
Alexey Bataev282555a2019-03-19 20:33:44 +00002340 VD->addAttr(A);
2341 if (ASTMutationListener *ML = Context.getASTMutationListener())
2342 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2343 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002344 }
2345 if (Vars.empty())
2346 return nullptr;
2347 if (!Owner)
2348 Owner = getCurLexicalContext();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002349 OMPAllocateDecl *D =
2350 OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002351 D->setAccess(AS_public);
2352 Owner->addDecl(D);
2353 return DeclGroupPtrTy::make(DeclGroupRef(D));
2354}
2355
2356Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002357Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2358 ArrayRef<OMPClause *> ClauseList) {
2359 OMPRequiresDecl *D = nullptr;
2360 if (!CurContext->isFileContext()) {
2361 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2362 } else {
2363 D = CheckOMPRequiresDecl(Loc, ClauseList);
2364 if (D) {
2365 CurContext->addDecl(D);
2366 DSAStack->addRequiresDecl(D);
2367 }
2368 }
2369 return DeclGroupPtrTy::make(DeclGroupRef(D));
2370}
2371
2372OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2373 ArrayRef<OMPClause *> ClauseList) {
2374 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2375 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2376 ClauseList);
2377 return nullptr;
2378}
2379
Alexey Bataeve3727102018-04-18 15:57:46 +00002380static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2381 const ValueDecl *D,
2382 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002383 bool IsLoopIterVar = false) {
2384 if (DVar.RefExpr) {
2385 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2386 << getOpenMPClauseName(DVar.CKind);
2387 return;
2388 }
2389 enum {
2390 PDSA_StaticMemberShared,
2391 PDSA_StaticLocalVarShared,
2392 PDSA_LoopIterVarPrivate,
2393 PDSA_LoopIterVarLinear,
2394 PDSA_LoopIterVarLastprivate,
2395 PDSA_ConstVarShared,
2396 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002397 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002398 PDSA_LocalVarPrivate,
2399 PDSA_Implicit
2400 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002401 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002402 auto ReportLoc = D->getLocation();
2403 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002404 if (IsLoopIterVar) {
2405 if (DVar.CKind == OMPC_private)
2406 Reason = PDSA_LoopIterVarPrivate;
2407 else if (DVar.CKind == OMPC_lastprivate)
2408 Reason = PDSA_LoopIterVarLastprivate;
2409 else
2410 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002411 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2412 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002413 Reason = PDSA_TaskVarFirstprivate;
2414 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002415 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002416 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002417 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002418 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002419 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002420 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002421 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002422 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002423 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002424 ReportHint = true;
2425 Reason = PDSA_LocalVarPrivate;
2426 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002427 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002428 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002429 << Reason << ReportHint
2430 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2431 } else if (DVar.ImplicitDSALoc.isValid()) {
2432 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2433 << getOpenMPClauseName(DVar.CKind);
2434 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002435}
2436
Alexey Bataev758e55e2013-09-06 18:03:48 +00002437namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002438class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002439 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002440 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002441 bool ErrorFound = false;
2442 CapturedStmt *CS = nullptr;
2443 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2444 llvm::SmallVector<Expr *, 4> ImplicitMap;
2445 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2446 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002447
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002448 void VisitSubCaptures(OMPExecutableDirective *S) {
2449 // Check implicitly captured variables.
2450 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2451 return;
2452 for (const CapturedStmt::Capture &Cap :
2453 S->getInnermostCapturedStmt()->captures()) {
2454 if (!Cap.capturesVariable())
2455 continue;
2456 VarDecl *VD = Cap.getCapturedVar();
2457 // Do not try to map the variable if it or its sub-component was mapped
2458 // already.
2459 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2460 Stack->checkMappableExprComponentListsForDecl(
2461 VD, /*CurrentRegionOnly=*/true,
2462 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2463 OpenMPClauseKind) { return true; }))
2464 continue;
2465 DeclRefExpr *DRE = buildDeclRefExpr(
2466 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2467 Cap.getLocation(), /*RefersToCapture=*/true);
2468 Visit(DRE);
2469 }
2470 }
2471
Alexey Bataev758e55e2013-09-06 18:03:48 +00002472public:
2473 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002474 if (E->isTypeDependent() || E->isValueDependent() ||
2475 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2476 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002477 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002478 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002479 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002480 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002481 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002482
Alexey Bataeve3727102018-04-18 15:57:46 +00002483 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002484 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002485 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002486 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002487
Alexey Bataevafe50572017-10-06 17:00:28 +00002488 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002489 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002490 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002491 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2492 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002493 return;
2494
Alexey Bataeve3727102018-04-18 15:57:46 +00002495 SourceLocation ELoc = E->getExprLoc();
2496 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002497 // The default(none) clause requires that each variable that is referenced
2498 // in the construct, and does not have a predetermined data-sharing
2499 // attribute, must have its data-sharing attribute explicitly determined
2500 // by being listed in a data-sharing attribute clause.
2501 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002502 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002503 VarsWithInheritedDSA.count(VD) == 0) {
2504 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002505 return;
2506 }
2507
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002508 if (isOpenMPTargetExecutionDirective(DKind) &&
2509 !Stack->isLoopControlVariable(VD).first) {
2510 if (!Stack->checkMappableExprComponentListsForDecl(
2511 VD, /*CurrentRegionOnly=*/true,
2512 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2513 StackComponents,
2514 OpenMPClauseKind) {
2515 // Variable is used if it has been marked as an array, array
2516 // section or the variable iself.
2517 return StackComponents.size() == 1 ||
2518 std::all_of(
2519 std::next(StackComponents.rbegin()),
2520 StackComponents.rend(),
2521 [](const OMPClauseMappableExprCommon::
2522 MappableComponent &MC) {
2523 return MC.getAssociatedDeclaration() ==
2524 nullptr &&
2525 (isa<OMPArraySectionExpr>(
2526 MC.getAssociatedExpression()) ||
2527 isa<ArraySubscriptExpr>(
2528 MC.getAssociatedExpression()));
2529 });
2530 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002531 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002532 // By default lambdas are captured as firstprivates.
2533 if (const auto *RD =
2534 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002535 IsFirstprivate = RD->isLambda();
2536 IsFirstprivate =
2537 IsFirstprivate ||
2538 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002539 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002540 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002541 ImplicitFirstprivate.emplace_back(E);
2542 else
2543 ImplicitMap.emplace_back(E);
2544 return;
2545 }
2546 }
2547
Alexey Bataev758e55e2013-09-06 18:03:48 +00002548 // OpenMP [2.9.3.6, Restrictions, p.2]
2549 // A list item that appears in a reduction clause of the innermost
2550 // enclosing worksharing or parallel construct may not be accessed in an
2551 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002552 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002553 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2554 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002555 return isOpenMPParallelDirective(K) ||
2556 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2557 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002558 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002559 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002560 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002561 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002562 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002563 return;
2564 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002565
2566 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002567 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002568 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002569 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002570 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002571 return;
2572 }
2573
2574 // Store implicitly used globals with declare target link for parent
2575 // target.
2576 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2577 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2578 Stack->addToParentTargetRegionLinkGlobals(E);
2579 return;
2580 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002581 }
2582 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002583 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002584 if (E->isTypeDependent() || E->isValueDependent() ||
2585 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2586 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002587 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002588 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002589 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002590 if (!FD)
2591 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002592 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002593 // Check if the variable has explicit DSA set and stop analysis if it
2594 // so.
2595 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2596 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002597
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002598 if (isOpenMPTargetExecutionDirective(DKind) &&
2599 !Stack->isLoopControlVariable(FD).first &&
2600 !Stack->checkMappableExprComponentListsForDecl(
2601 FD, /*CurrentRegionOnly=*/true,
2602 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2603 StackComponents,
2604 OpenMPClauseKind) {
2605 return isa<CXXThisExpr>(
2606 cast<MemberExpr>(
2607 StackComponents.back().getAssociatedExpression())
2608 ->getBase()
2609 ->IgnoreParens());
2610 })) {
2611 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2612 // A bit-field cannot appear in a map clause.
2613 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002614 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002615 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002616
2617 // Check to see if the member expression is referencing a class that
2618 // has already been explicitly mapped
2619 if (Stack->isClassPreviouslyMapped(TE->getType()))
2620 return;
2621
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002622 ImplicitMap.emplace_back(E);
2623 return;
2624 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002625
Alexey Bataeve3727102018-04-18 15:57:46 +00002626 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002627 // OpenMP [2.9.3.6, Restrictions, p.2]
2628 // A list item that appears in a reduction clause of the innermost
2629 // enclosing worksharing or parallel construct may not be accessed in
2630 // an explicit task.
2631 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002632 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2633 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002634 return isOpenMPParallelDirective(K) ||
2635 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2636 },
2637 /*FromParent=*/true);
2638 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2639 ErrorFound = true;
2640 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002641 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002642 return;
2643 }
2644
2645 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002646 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002647 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002648 !Stack->isLoopControlVariable(FD).first) {
2649 // Check if there is a captured expression for the current field in the
2650 // region. Do not mark it as firstprivate unless there is no captured
2651 // expression.
2652 // TODO: try to make it firstprivate.
2653 if (DVar.CKind != OMPC_unknown)
2654 ImplicitFirstprivate.push_back(E);
2655 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002656 return;
2657 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002658 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002659 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002660 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002661 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002662 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002663 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002664 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2665 if (!Stack->checkMappableExprComponentListsForDecl(
2666 VD, /*CurrentRegionOnly=*/true,
2667 [&CurComponents](
2668 OMPClauseMappableExprCommon::MappableExprComponentListRef
2669 StackComponents,
2670 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002671 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002672 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002673 for (const auto &SC : llvm::reverse(StackComponents)) {
2674 // Do both expressions have the same kind?
2675 if (CCI->getAssociatedExpression()->getStmtClass() !=
2676 SC.getAssociatedExpression()->getStmtClass())
2677 if (!(isa<OMPArraySectionExpr>(
2678 SC.getAssociatedExpression()) &&
2679 isa<ArraySubscriptExpr>(
2680 CCI->getAssociatedExpression())))
2681 return false;
2682
Alexey Bataeve3727102018-04-18 15:57:46 +00002683 const Decl *CCD = CCI->getAssociatedDeclaration();
2684 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002685 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2686 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2687 if (SCD != CCD)
2688 return false;
2689 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002690 if (CCI == CCE)
2691 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002692 }
2693 return true;
2694 })) {
2695 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002696 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002697 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002698 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002699 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002700 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002701 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002702 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002703 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002704 // for task|target directives.
2705 // Skip analysis of arguments of implicitly defined map clause for target
2706 // directives.
2707 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2708 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002709 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002710 if (CC)
2711 Visit(CC);
2712 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002713 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002714 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002715 // Check implicitly captured variables.
2716 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002717 }
2718 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002719 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002720 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002721 // Check implicitly captured variables in the task-based directives to
2722 // check if they must be firstprivatized.
2723 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002724 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002725 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002726 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002727
Alexey Bataeve3727102018-04-18 15:57:46 +00002728 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002729 ArrayRef<Expr *> getImplicitFirstprivate() const {
2730 return ImplicitFirstprivate;
2731 }
2732 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002733 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002734 return VarsWithInheritedDSA;
2735 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002736
Alexey Bataev7ff55242014-06-19 09:13:45 +00002737 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002738 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2739 // Process declare target link variables for the target directives.
2740 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2741 for (DeclRefExpr *E : Stack->getLinkGlobals())
2742 Visit(E);
2743 }
2744 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002745};
Alexey Bataeved09d242014-05-28 05:53:51 +00002746} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002747
Alexey Bataevbae9a792014-06-27 10:37:06 +00002748void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002749 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002750 case OMPD_parallel:
2751 case OMPD_parallel_for:
2752 case OMPD_parallel_for_simd:
2753 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002754 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002755 case OMPD_teams_distribute:
2756 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002757 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002758 QualType KmpInt32PtrTy =
2759 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002760 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002761 std::make_pair(".global_tid.", KmpInt32PtrTy),
2762 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2763 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002764 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002765 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2766 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002767 break;
2768 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002769 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002770 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002771 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002772 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002773 case OMPD_target_teams_distribute:
2774 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002775 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2776 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2777 QualType KmpInt32PtrTy =
2778 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2779 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002780 FunctionProtoType::ExtProtoInfo EPI;
2781 EPI.Variadic = true;
2782 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2783 Sema::CapturedParamNameType Params[] = {
2784 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002785 std::make_pair(".part_id.", KmpInt32PtrTy),
2786 std::make_pair(".privates.", VoidPtrTy),
2787 std::make_pair(
2788 ".copy_fn.",
2789 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002790 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2791 std::make_pair(StringRef(), QualType()) // __context with shared vars
2792 };
2793 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2794 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002795 // Mark this captured region as inlined, because we don't use outlined
2796 // function directly.
2797 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2798 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002799 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002800 Sema::CapturedParamNameType ParamsTarget[] = {
2801 std::make_pair(StringRef(), QualType()) // __context with shared vars
2802 };
2803 // Start a captured region for 'target' with no implicit parameters.
2804 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2805 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002806 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002807 std::make_pair(".global_tid.", KmpInt32PtrTy),
2808 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2809 std::make_pair(StringRef(), QualType()) // __context with shared vars
2810 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002811 // Start a captured region for 'teams' or 'parallel'. Both regions have
2812 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002813 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002814 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002815 break;
2816 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002817 case OMPD_target:
2818 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002819 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2820 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2821 QualType KmpInt32PtrTy =
2822 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2823 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002824 FunctionProtoType::ExtProtoInfo EPI;
2825 EPI.Variadic = true;
2826 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2827 Sema::CapturedParamNameType Params[] = {
2828 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002829 std::make_pair(".part_id.", KmpInt32PtrTy),
2830 std::make_pair(".privates.", VoidPtrTy),
2831 std::make_pair(
2832 ".copy_fn.",
2833 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002834 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2835 std::make_pair(StringRef(), QualType()) // __context with shared vars
2836 };
2837 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2838 Params);
2839 // Mark this captured region as inlined, because we don't use outlined
2840 // function directly.
2841 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2842 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002843 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2845 std::make_pair(StringRef(), QualType()));
2846 break;
2847 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002848 case OMPD_simd:
2849 case OMPD_for:
2850 case OMPD_for_simd:
2851 case OMPD_sections:
2852 case OMPD_section:
2853 case OMPD_single:
2854 case OMPD_master:
2855 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002856 case OMPD_taskgroup:
2857 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002858 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002859 case OMPD_ordered:
2860 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002861 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002862 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002863 std::make_pair(StringRef(), QualType()) // __context with shared vars
2864 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002865 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2866 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002867 break;
2868 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002869 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002870 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2871 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2872 QualType KmpInt32PtrTy =
2873 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2874 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002875 FunctionProtoType::ExtProtoInfo EPI;
2876 EPI.Variadic = true;
2877 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002878 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002879 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002880 std::make_pair(".part_id.", KmpInt32PtrTy),
2881 std::make_pair(".privates.", VoidPtrTy),
2882 std::make_pair(
2883 ".copy_fn.",
2884 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002885 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002886 std::make_pair(StringRef(), QualType()) // __context with shared vars
2887 };
2888 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2889 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002890 // Mark this captured region as inlined, because we don't use outlined
2891 // function directly.
2892 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2893 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002894 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002895 break;
2896 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002897 case OMPD_taskloop:
2898 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002899 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002900 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2901 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002902 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002903 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2904 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002905 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002906 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2907 .withConst();
2908 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2909 QualType KmpInt32PtrTy =
2910 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2911 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002912 FunctionProtoType::ExtProtoInfo EPI;
2913 EPI.Variadic = true;
2914 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002915 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002916 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002917 std::make_pair(".part_id.", KmpInt32PtrTy),
2918 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002919 std::make_pair(
2920 ".copy_fn.",
2921 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2922 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2923 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002924 std::make_pair(".ub.", KmpUInt64Ty),
2925 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002926 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002927 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002928 std::make_pair(StringRef(), QualType()) // __context with shared vars
2929 };
2930 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2931 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002932 // Mark this captured region as inlined, because we don't use outlined
2933 // function directly.
2934 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2935 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002936 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002937 break;
2938 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002939 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002940 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002941 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002942 QualType KmpInt32PtrTy =
2943 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2944 Sema::CapturedParamNameType Params[] = {
2945 std::make_pair(".global_tid.", KmpInt32PtrTy),
2946 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002947 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2948 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002949 std::make_pair(StringRef(), QualType()) // __context with shared vars
2950 };
2951 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2952 Params);
2953 break;
2954 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002955 case OMPD_target_teams_distribute_parallel_for:
2956 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002957 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002958 QualType KmpInt32PtrTy =
2959 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002960 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002961
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002962 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002963 FunctionProtoType::ExtProtoInfo EPI;
2964 EPI.Variadic = true;
2965 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2966 Sema::CapturedParamNameType Params[] = {
2967 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002968 std::make_pair(".part_id.", KmpInt32PtrTy),
2969 std::make_pair(".privates.", VoidPtrTy),
2970 std::make_pair(
2971 ".copy_fn.",
2972 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002973 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2974 std::make_pair(StringRef(), QualType()) // __context with shared vars
2975 };
2976 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2977 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002978 // Mark this captured region as inlined, because we don't use outlined
2979 // function directly.
2980 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2981 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002982 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002983 Sema::CapturedParamNameType ParamsTarget[] = {
2984 std::make_pair(StringRef(), QualType()) // __context with shared vars
2985 };
2986 // Start a captured region for 'target' with no implicit parameters.
2987 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2988 ParamsTarget);
2989
2990 Sema::CapturedParamNameType ParamsTeams[] = {
2991 std::make_pair(".global_tid.", KmpInt32PtrTy),
2992 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2993 std::make_pair(StringRef(), QualType()) // __context with shared vars
2994 };
2995 // Start a captured region for 'target' with no implicit parameters.
2996 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2997 ParamsTeams);
2998
2999 Sema::CapturedParamNameType ParamsParallel[] = {
3000 std::make_pair(".global_tid.", KmpInt32PtrTy),
3001 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003002 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3003 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003004 std::make_pair(StringRef(), QualType()) // __context with shared vars
3005 };
3006 // Start a captured region for 'teams' or 'parallel'. Both regions have
3007 // the same implicit parameters.
3008 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3009 ParamsParallel);
3010 break;
3011 }
3012
Alexey Bataev46506272017-12-05 17:41:34 +00003013 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003014 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003015 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003016 QualType KmpInt32PtrTy =
3017 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3018
3019 Sema::CapturedParamNameType ParamsTeams[] = {
3020 std::make_pair(".global_tid.", KmpInt32PtrTy),
3021 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3022 std::make_pair(StringRef(), QualType()) // __context with shared vars
3023 };
3024 // Start a captured region for 'target' with no implicit parameters.
3025 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3026 ParamsTeams);
3027
3028 Sema::CapturedParamNameType ParamsParallel[] = {
3029 std::make_pair(".global_tid.", KmpInt32PtrTy),
3030 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003031 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3032 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003033 std::make_pair(StringRef(), QualType()) // __context with shared vars
3034 };
3035 // Start a captured region for 'teams' or 'parallel'. Both regions have
3036 // the same implicit parameters.
3037 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3038 ParamsParallel);
3039 break;
3040 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003041 case OMPD_target_update:
3042 case OMPD_target_enter_data:
3043 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003044 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3045 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3046 QualType KmpInt32PtrTy =
3047 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3048 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003049 FunctionProtoType::ExtProtoInfo EPI;
3050 EPI.Variadic = true;
3051 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3052 Sema::CapturedParamNameType Params[] = {
3053 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003054 std::make_pair(".part_id.", KmpInt32PtrTy),
3055 std::make_pair(".privates.", VoidPtrTy),
3056 std::make_pair(
3057 ".copy_fn.",
3058 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003059 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3060 std::make_pair(StringRef(), QualType()) // __context with shared vars
3061 };
3062 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3063 Params);
3064 // Mark this captured region as inlined, because we don't use outlined
3065 // function directly.
3066 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3067 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003068 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003069 break;
3070 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003071 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003072 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003073 case OMPD_taskyield:
3074 case OMPD_barrier:
3075 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003076 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003077 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003078 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003079 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003080 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003081 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003082 case OMPD_declare_target:
3083 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003084 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003085 llvm_unreachable("OpenMP Directive is not allowed");
3086 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003087 llvm_unreachable("Unknown OpenMP directive");
3088 }
3089}
3090
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003091int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3092 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3093 getOpenMPCaptureRegions(CaptureRegions, DKind);
3094 return CaptureRegions.size();
3095}
3096
Alexey Bataev3392d762016-02-16 11:18:12 +00003097static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003098 Expr *CaptureExpr, bool WithInit,
3099 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003100 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003101 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003102 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003103 QualType Ty = Init->getType();
3104 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003105 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003106 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003107 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003108 Ty = C.getPointerType(Ty);
3109 ExprResult Res =
3110 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3111 if (!Res.isUsable())
3112 return nullptr;
3113 Init = Res.get();
3114 }
Alexey Bataev61205072016-03-02 04:57:40 +00003115 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003116 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003117 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003118 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003119 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003120 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003121 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003122 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003123 return CED;
3124}
3125
Alexey Bataev61205072016-03-02 04:57:40 +00003126static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3127 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003128 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003129 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003130 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003131 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003132 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3133 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003134 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003135 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003136}
3137
Alexey Bataev5a3af132016-03-29 08:58:54 +00003138static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003139 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003140 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003141 OMPCapturedExprDecl *CD = buildCaptureDecl(
3142 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3143 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003144 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3145 CaptureExpr->getExprLoc());
3146 }
3147 ExprResult Res = Ref;
3148 if (!S.getLangOpts().CPlusPlus &&
3149 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003150 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003151 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003152 if (!Res.isUsable())
3153 return ExprError();
3154 }
3155 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003156}
3157
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003158namespace {
3159// OpenMP directives parsed in this section are represented as a
3160// CapturedStatement with an associated statement. If a syntax error
3161// is detected during the parsing of the associated statement, the
3162// compiler must abort processing and close the CapturedStatement.
3163//
3164// Combined directives such as 'target parallel' have more than one
3165// nested CapturedStatements. This RAII ensures that we unwind out
3166// of all the nested CapturedStatements when an error is found.
3167class CaptureRegionUnwinderRAII {
3168private:
3169 Sema &S;
3170 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003171 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003172
3173public:
3174 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3175 OpenMPDirectiveKind DKind)
3176 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3177 ~CaptureRegionUnwinderRAII() {
3178 if (ErrorFound) {
3179 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3180 while (--ThisCaptureLevel >= 0)
3181 S.ActOnCapturedRegionError();
3182 }
3183 }
3184};
3185} // namespace
3186
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003187StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3188 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003189 bool ErrorFound = false;
3190 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3191 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003192 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003193 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003194 return StmtError();
3195 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003196
Alexey Bataev2ba67042017-11-28 21:11:44 +00003197 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3198 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003199 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003200 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003201 SmallVector<const OMPLinearClause *, 4> LCs;
3202 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003203 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003204 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003205 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3206 Clause->getClauseKind() == OMPC_in_reduction) {
3207 // Capture taskgroup task_reduction descriptors inside the tasking regions
3208 // with the corresponding in_reduction items.
3209 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003210 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003211 if (E)
3212 MarkDeclarationsReferencedInExpr(E);
3213 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003214 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003215 Clause->getClauseKind() == OMPC_copyprivate ||
3216 (getLangOpts().OpenMPUseTLS &&
3217 getASTContext().getTargetInfo().isTLSSupported() &&
3218 Clause->getClauseKind() == OMPC_copyin)) {
3219 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003220 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003221 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003222 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003223 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003224 }
3225 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003226 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003227 } else if (CaptureRegions.size() > 1 ||
3228 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003229 if (auto *C = OMPClauseWithPreInit::get(Clause))
3230 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003231 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003232 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003233 MarkDeclarationsReferencedInExpr(E);
3234 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003235 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003236 if (Clause->getClauseKind() == OMPC_schedule)
3237 SC = cast<OMPScheduleClause>(Clause);
3238 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003239 OC = cast<OMPOrderedClause>(Clause);
3240 else if (Clause->getClauseKind() == OMPC_linear)
3241 LCs.push_back(cast<OMPLinearClause>(Clause));
3242 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003243 // OpenMP, 2.7.1 Loop Construct, Restrictions
3244 // The nonmonotonic modifier cannot be specified if an ordered clause is
3245 // specified.
3246 if (SC &&
3247 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3248 SC->getSecondScheduleModifier() ==
3249 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3250 OC) {
3251 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3252 ? SC->getFirstScheduleModifierLoc()
3253 : SC->getSecondScheduleModifierLoc(),
3254 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003255 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003256 ErrorFound = true;
3257 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003258 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003259 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003260 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003261 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003262 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003263 ErrorFound = true;
3264 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003265 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3266 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3267 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003268 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003269 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3270 ErrorFound = true;
3271 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003272 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003273 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003274 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003275 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003276 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003277 // Mark all variables in private list clauses as used in inner region.
3278 // Required for proper codegen of combined directives.
3279 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003280 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003281 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003282 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3283 // Find the particular capture region for the clause if the
3284 // directive is a combined one with multiple capture regions.
3285 // If the directive is not a combined one, the capture region
3286 // associated with the clause is OMPD_unknown and is generated
3287 // only once.
3288 if (CaptureRegion == ThisCaptureRegion ||
3289 CaptureRegion == OMPD_unknown) {
3290 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003291 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003292 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3293 }
3294 }
3295 }
3296 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003297 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003298 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003299 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003300}
3301
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003302static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3303 OpenMPDirectiveKind CancelRegion,
3304 SourceLocation StartLoc) {
3305 // CancelRegion is only needed for cancel and cancellation_point.
3306 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3307 return false;
3308
3309 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3310 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3311 return false;
3312
3313 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3314 << getOpenMPDirectiveName(CancelRegion);
3315 return true;
3316}
3317
Alexey Bataeve3727102018-04-18 15:57:46 +00003318static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003319 OpenMPDirectiveKind CurrentRegion,
3320 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003321 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003322 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003323 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003324 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3325 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003326 bool NestingProhibited = false;
3327 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003328 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003329 enum {
3330 NoRecommend,
3331 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003332 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003333 ShouldBeInTargetRegion,
3334 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003335 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003336 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003337 // OpenMP [2.16, Nesting of Regions]
3338 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003339 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003340 // An ordered construct with the simd clause is the only OpenMP
3341 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003342 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003343 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3344 // message.
3345 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3346 ? diag::err_omp_prohibited_region_simd
3347 : diag::warn_omp_nesting_simd);
3348 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003349 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003350 if (ParentRegion == OMPD_atomic) {
3351 // OpenMP [2.16, Nesting of Regions]
3352 // OpenMP constructs may not be nested inside an atomic region.
3353 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3354 return true;
3355 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003356 if (CurrentRegion == OMPD_section) {
3357 // OpenMP [2.7.2, sections Construct, Restrictions]
3358 // Orphaned section directives are prohibited. That is, the section
3359 // directives must appear within the sections construct and must not be
3360 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003361 if (ParentRegion != OMPD_sections &&
3362 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003363 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3364 << (ParentRegion != OMPD_unknown)
3365 << getOpenMPDirectiveName(ParentRegion);
3366 return true;
3367 }
3368 return false;
3369 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003370 // Allow some constructs (except teams and cancellation constructs) to be
3371 // orphaned (they could be used in functions, called from OpenMP regions
3372 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003373 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003374 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3375 CurrentRegion != OMPD_cancellation_point &&
3376 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003377 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003378 if (CurrentRegion == OMPD_cancellation_point ||
3379 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003380 // OpenMP [2.16, Nesting of Regions]
3381 // A cancellation point construct for which construct-type-clause is
3382 // taskgroup must be nested inside a task construct. A cancellation
3383 // point construct for which construct-type-clause is not taskgroup must
3384 // be closely nested inside an OpenMP construct that matches the type
3385 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003386 // A cancel construct for which construct-type-clause is taskgroup must be
3387 // nested inside a task construct. A cancel construct for which
3388 // construct-type-clause is not taskgroup must be closely nested inside an
3389 // OpenMP construct that matches the type specified in
3390 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003391 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003392 !((CancelRegion == OMPD_parallel &&
3393 (ParentRegion == OMPD_parallel ||
3394 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003395 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003396 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003397 ParentRegion == OMPD_target_parallel_for ||
3398 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003399 ParentRegion == OMPD_teams_distribute_parallel_for ||
3400 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003401 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3402 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003403 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3404 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003405 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003406 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003407 // OpenMP [2.16, Nesting of Regions]
3408 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003409 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003410 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003411 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003412 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3413 // OpenMP [2.16, Nesting of Regions]
3414 // A critical region may not be nested (closely or otherwise) inside a
3415 // critical region with the same name. Note that this restriction is not
3416 // sufficient to prevent deadlock.
3417 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003418 bool DeadLock = Stack->hasDirective(
3419 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3420 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003421 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003422 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3423 PreviousCriticalLoc = Loc;
3424 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003425 }
3426 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003427 },
3428 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003429 if (DeadLock) {
3430 SemaRef.Diag(StartLoc,
3431 diag::err_omp_prohibited_region_critical_same_name)
3432 << CurrentName.getName();
3433 if (PreviousCriticalLoc.isValid())
3434 SemaRef.Diag(PreviousCriticalLoc,
3435 diag::note_omp_previous_critical_region);
3436 return true;
3437 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003438 } else if (CurrentRegion == OMPD_barrier) {
3439 // OpenMP [2.16, Nesting of Regions]
3440 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003441 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003442 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3443 isOpenMPTaskingDirective(ParentRegion) ||
3444 ParentRegion == OMPD_master ||
3445 ParentRegion == OMPD_critical ||
3446 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003447 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003448 !isOpenMPParallelDirective(CurrentRegion) &&
3449 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003450 // OpenMP [2.16, Nesting of Regions]
3451 // A worksharing region may not be closely nested inside a worksharing,
3452 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003453 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3454 isOpenMPTaskingDirective(ParentRegion) ||
3455 ParentRegion == OMPD_master ||
3456 ParentRegion == OMPD_critical ||
3457 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003458 Recommend = ShouldBeInParallelRegion;
3459 } else if (CurrentRegion == OMPD_ordered) {
3460 // OpenMP [2.16, Nesting of Regions]
3461 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003462 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003463 // An ordered region must be closely nested inside a loop region (or
3464 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003465 // OpenMP [2.8.1,simd Construct, Restrictions]
3466 // An ordered construct with the simd clause is the only OpenMP construct
3467 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003468 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003469 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003470 !(isOpenMPSimdDirective(ParentRegion) ||
3471 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003472 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003473 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003474 // OpenMP [2.16, Nesting of Regions]
3475 // If specified, a teams construct must be contained within a target
3476 // construct.
3477 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003478 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003479 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003480 }
Kelvin Libf594a52016-12-17 05:48:59 +00003481 if (!NestingProhibited &&
3482 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3483 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3484 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003485 // OpenMP [2.16, Nesting of Regions]
3486 // distribute, parallel, parallel sections, parallel workshare, and the
3487 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3488 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003489 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3490 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003491 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003492 }
David Majnemer9d168222016-08-05 17:44:54 +00003493 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003494 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003495 // OpenMP 4.5 [2.17 Nesting of Regions]
3496 // The region associated with the distribute construct must be strictly
3497 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003498 NestingProhibited =
3499 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003500 Recommend = ShouldBeInTeamsRegion;
3501 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003502 if (!NestingProhibited &&
3503 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3504 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3505 // OpenMP 4.5 [2.17 Nesting of Regions]
3506 // If a target, target update, target data, target enter data, or
3507 // target exit data construct is encountered during execution of a
3508 // target region, the behavior is unspecified.
3509 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003510 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003511 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003512 if (isOpenMPTargetExecutionDirective(K)) {
3513 OffendingRegion = K;
3514 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003515 }
3516 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003517 },
3518 false /* don't skip top directive */);
3519 CloseNesting = false;
3520 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003521 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003522 if (OrphanSeen) {
3523 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3524 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3525 } else {
3526 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3527 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3528 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3529 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003530 return true;
3531 }
3532 }
3533 return false;
3534}
3535
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003536static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3537 ArrayRef<OMPClause *> Clauses,
3538 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3539 bool ErrorFound = false;
3540 unsigned NamedModifiersNumber = 0;
3541 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3542 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003543 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003544 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003545 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3546 // At most one if clause without a directive-name-modifier can appear on
3547 // the directive.
3548 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3549 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003550 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003551 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3552 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3553 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003554 } else if (CurNM != OMPD_unknown) {
3555 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003556 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003557 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003558 FoundNameModifiers[CurNM] = IC;
3559 if (CurNM == OMPD_unknown)
3560 continue;
3561 // Check if the specified name modifier is allowed for the current
3562 // directive.
3563 // At most one if clause with the particular directive-name-modifier can
3564 // appear on the directive.
3565 bool MatchFound = false;
3566 for (auto NM : AllowedNameModifiers) {
3567 if (CurNM == NM) {
3568 MatchFound = true;
3569 break;
3570 }
3571 }
3572 if (!MatchFound) {
3573 S.Diag(IC->getNameModifierLoc(),
3574 diag::err_omp_wrong_if_directive_name_modifier)
3575 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3576 ErrorFound = true;
3577 }
3578 }
3579 }
3580 // If any if clause on the directive includes a directive-name-modifier then
3581 // all if clauses on the directive must include a directive-name-modifier.
3582 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3583 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003584 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003585 diag::err_omp_no_more_if_clause);
3586 } else {
3587 std::string Values;
3588 std::string Sep(", ");
3589 unsigned AllowedCnt = 0;
3590 unsigned TotalAllowedNum =
3591 AllowedNameModifiers.size() - NamedModifiersNumber;
3592 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3593 ++Cnt) {
3594 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3595 if (!FoundNameModifiers[NM]) {
3596 Values += "'";
3597 Values += getOpenMPDirectiveName(NM);
3598 Values += "'";
3599 if (AllowedCnt + 2 == TotalAllowedNum)
3600 Values += " or ";
3601 else if (AllowedCnt + 1 != TotalAllowedNum)
3602 Values += Sep;
3603 ++AllowedCnt;
3604 }
3605 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003606 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003607 diag::err_omp_unnamed_if_clause)
3608 << (TotalAllowedNum > 1) << Values;
3609 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003610 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003611 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3612 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003613 ErrorFound = true;
3614 }
3615 return ErrorFound;
3616}
3617
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003618StmtResult Sema::ActOnOpenMPExecutableDirective(
3619 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3620 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3621 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003622 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003623 // First check CancelRegion which is then used in checkNestingOfRegions.
3624 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3625 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003626 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003627 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003628
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003629 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003630 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003631 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003632 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003633 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003634 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3635
3636 // Check default data sharing attributes for referenced variables.
3637 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003638 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3639 Stmt *S = AStmt;
3640 while (--ThisCaptureLevel >= 0)
3641 S = cast<CapturedStmt>(S)->getCapturedStmt();
3642 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003643 if (DSAChecker.isErrorFound())
3644 return StmtError();
3645 // Generate list of implicitly defined firstprivate variables.
3646 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003647
Alexey Bataev88202be2017-07-27 13:20:36 +00003648 SmallVector<Expr *, 4> ImplicitFirstprivates(
3649 DSAChecker.getImplicitFirstprivate().begin(),
3650 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003651 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3652 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003653 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003654 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003655 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003656 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003657 if (E)
3658 ImplicitFirstprivates.emplace_back(E);
3659 }
3660 }
3661 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003662 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003663 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3664 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003665 ClausesWithImplicit.push_back(Implicit);
3666 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003667 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003668 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003669 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003670 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003671 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003672 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003673 CXXScopeSpec MapperIdScopeSpec;
3674 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003675 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003676 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3677 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3678 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003679 ClausesWithImplicit.emplace_back(Implicit);
3680 ErrorFound |=
3681 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003682 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003683 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003684 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003685 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003686 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003687
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003688 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003689 switch (Kind) {
3690 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003691 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3692 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003693 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003694 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003695 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003696 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3697 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003698 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003699 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003700 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3701 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003702 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003703 case OMPD_for_simd:
3704 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3705 EndLoc, VarsWithInheritedDSA);
3706 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003707 case OMPD_sections:
3708 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3709 EndLoc);
3710 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003711 case OMPD_section:
3712 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003713 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003714 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3715 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003716 case OMPD_single:
3717 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3718 EndLoc);
3719 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003720 case OMPD_master:
3721 assert(ClausesWithImplicit.empty() &&
3722 "No clauses are allowed for 'omp master' directive");
3723 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3724 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003725 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003726 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3727 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003728 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003729 case OMPD_parallel_for:
3730 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3731 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003732 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003733 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003734 case OMPD_parallel_for_simd:
3735 Res = ActOnOpenMPParallelForSimdDirective(
3736 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003737 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003738 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003739 case OMPD_parallel_sections:
3740 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3741 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003742 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003743 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003744 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003745 Res =
3746 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003747 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003748 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003749 case OMPD_taskyield:
3750 assert(ClausesWithImplicit.empty() &&
3751 "No clauses are allowed for 'omp taskyield' directive");
3752 assert(AStmt == nullptr &&
3753 "No associated statement allowed for 'omp taskyield' directive");
3754 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3755 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003756 case OMPD_barrier:
3757 assert(ClausesWithImplicit.empty() &&
3758 "No clauses are allowed for 'omp barrier' directive");
3759 assert(AStmt == nullptr &&
3760 "No associated statement allowed for 'omp barrier' directive");
3761 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3762 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003763 case OMPD_taskwait:
3764 assert(ClausesWithImplicit.empty() &&
3765 "No clauses are allowed for 'omp taskwait' directive");
3766 assert(AStmt == nullptr &&
3767 "No associated statement allowed for 'omp taskwait' directive");
3768 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3769 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003770 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003771 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3772 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003773 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003774 case OMPD_flush:
3775 assert(AStmt == nullptr &&
3776 "No associated statement allowed for 'omp flush' directive");
3777 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3778 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003779 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003780 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3781 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003782 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003783 case OMPD_atomic:
3784 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3785 EndLoc);
3786 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003787 case OMPD_teams:
3788 Res =
3789 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3790 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003791 case OMPD_target:
3792 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3793 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003794 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003795 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003796 case OMPD_target_parallel:
3797 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3798 StartLoc, EndLoc);
3799 AllowedNameModifiers.push_back(OMPD_target);
3800 AllowedNameModifiers.push_back(OMPD_parallel);
3801 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003802 case OMPD_target_parallel_for:
3803 Res = ActOnOpenMPTargetParallelForDirective(
3804 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3805 AllowedNameModifiers.push_back(OMPD_target);
3806 AllowedNameModifiers.push_back(OMPD_parallel);
3807 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003808 case OMPD_cancellation_point:
3809 assert(ClausesWithImplicit.empty() &&
3810 "No clauses are allowed for 'omp cancellation point' directive");
3811 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3812 "cancellation point' directive");
3813 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3814 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003815 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003816 assert(AStmt == nullptr &&
3817 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003818 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3819 CancelRegion);
3820 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003821 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003822 case OMPD_target_data:
3823 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3824 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003825 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003826 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003827 case OMPD_target_enter_data:
3828 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003829 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003830 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3831 break;
Samuel Antao72590762016-01-19 20:04:50 +00003832 case OMPD_target_exit_data:
3833 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003834 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003835 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3836 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003837 case OMPD_taskloop:
3838 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3839 EndLoc, VarsWithInheritedDSA);
3840 AllowedNameModifiers.push_back(OMPD_taskloop);
3841 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003842 case OMPD_taskloop_simd:
3843 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3844 EndLoc, VarsWithInheritedDSA);
3845 AllowedNameModifiers.push_back(OMPD_taskloop);
3846 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003847 case OMPD_distribute:
3848 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3849 EndLoc, VarsWithInheritedDSA);
3850 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003851 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003852 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3853 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003854 AllowedNameModifiers.push_back(OMPD_target_update);
3855 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003856 case OMPD_distribute_parallel_for:
3857 Res = ActOnOpenMPDistributeParallelForDirective(
3858 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3859 AllowedNameModifiers.push_back(OMPD_parallel);
3860 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003861 case OMPD_distribute_parallel_for_simd:
3862 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3863 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3864 AllowedNameModifiers.push_back(OMPD_parallel);
3865 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003866 case OMPD_distribute_simd:
3867 Res = ActOnOpenMPDistributeSimdDirective(
3868 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3869 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003870 case OMPD_target_parallel_for_simd:
3871 Res = ActOnOpenMPTargetParallelForSimdDirective(
3872 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3873 AllowedNameModifiers.push_back(OMPD_target);
3874 AllowedNameModifiers.push_back(OMPD_parallel);
3875 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003876 case OMPD_target_simd:
3877 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3878 EndLoc, VarsWithInheritedDSA);
3879 AllowedNameModifiers.push_back(OMPD_target);
3880 break;
Kelvin Li02532872016-08-05 14:37:37 +00003881 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003882 Res = ActOnOpenMPTeamsDistributeDirective(
3883 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003884 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003885 case OMPD_teams_distribute_simd:
3886 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3887 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3888 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003889 case OMPD_teams_distribute_parallel_for_simd:
3890 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3891 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3892 AllowedNameModifiers.push_back(OMPD_parallel);
3893 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003894 case OMPD_teams_distribute_parallel_for:
3895 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3896 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3897 AllowedNameModifiers.push_back(OMPD_parallel);
3898 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003899 case OMPD_target_teams:
3900 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3901 EndLoc);
3902 AllowedNameModifiers.push_back(OMPD_target);
3903 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003904 case OMPD_target_teams_distribute:
3905 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3906 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3907 AllowedNameModifiers.push_back(OMPD_target);
3908 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003909 case OMPD_target_teams_distribute_parallel_for:
3910 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3911 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3912 AllowedNameModifiers.push_back(OMPD_target);
3913 AllowedNameModifiers.push_back(OMPD_parallel);
3914 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003915 case OMPD_target_teams_distribute_parallel_for_simd:
3916 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3917 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3918 AllowedNameModifiers.push_back(OMPD_target);
3919 AllowedNameModifiers.push_back(OMPD_parallel);
3920 break;
Kelvin Lida681182017-01-10 18:08:18 +00003921 case OMPD_target_teams_distribute_simd:
3922 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3923 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3924 AllowedNameModifiers.push_back(OMPD_target);
3925 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003926 case OMPD_declare_target:
3927 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003928 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003929 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003930 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003931 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003932 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003933 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003934 llvm_unreachable("OpenMP Directive is not allowed");
3935 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003936 llvm_unreachable("Unknown OpenMP directive");
3937 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003938
Roman Lebedevb5700602019-03-20 16:32:36 +00003939 ErrorFound = Res.isInvalid() || ErrorFound;
3940
Alexey Bataeve3727102018-04-18 15:57:46 +00003941 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003942 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3943 << P.first << P.second->getSourceRange();
3944 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003945 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3946
3947 if (!AllowedNameModifiers.empty())
3948 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3949 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003950
Alexey Bataeved09d242014-05-28 05:53:51 +00003951 if (ErrorFound)
3952 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00003953
3954 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3955 Res.getAs<OMPExecutableDirective>()
3956 ->getStructuredBlock()
3957 ->setIsOMPStructuredBlock(true);
3958 }
3959
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003960 return Res;
3961}
3962
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003963Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3964 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003965 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003966 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3967 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003968 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003969 assert(Linears.size() == LinModifiers.size());
3970 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003971 if (!DG || DG.get().isNull())
3972 return DeclGroupPtrTy();
3973
3974 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003975 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003976 return DG;
3977 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003978 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003979 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3980 ADecl = FTD->getTemplatedDecl();
3981
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003982 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3983 if (!FD) {
3984 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003985 return DeclGroupPtrTy();
3986 }
3987
Alexey Bataev2af33e32016-04-07 12:45:37 +00003988 // OpenMP [2.8.2, declare simd construct, Description]
3989 // The parameter of the simdlen clause must be a constant positive integer
3990 // expression.
3991 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003992 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003993 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003994 // OpenMP [2.8.2, declare simd construct, Description]
3995 // The special this pointer can be used as if was one of the arguments to the
3996 // function in any of the linear, aligned, or uniform clauses.
3997 // The uniform clause declares one or more arguments to have an invariant
3998 // value for all concurrent invocations of the function in the execution of a
3999 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004000 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4001 const Expr *UniformedLinearThis = nullptr;
4002 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004003 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004004 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4005 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004006 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4007 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004008 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004009 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004010 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004011 }
4012 if (isa<CXXThisExpr>(E)) {
4013 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004014 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004015 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004016 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4017 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004018 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004019 // OpenMP [2.8.2, declare simd construct, Description]
4020 // The aligned clause declares that the object to which each list item points
4021 // is aligned to the number of bytes expressed in the optional parameter of
4022 // the aligned clause.
4023 // The special this pointer can be used as if was one of the arguments to the
4024 // function in any of the linear, aligned, or uniform clauses.
4025 // The type of list items appearing in the aligned clause must be array,
4026 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004027 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4028 const Expr *AlignedThis = nullptr;
4029 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004030 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004031 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4032 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4033 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004034 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4035 FD->getParamDecl(PVD->getFunctionScopeIndex())
4036 ->getCanonicalDecl() == CanonPVD) {
4037 // OpenMP [2.8.1, simd construct, Restrictions]
4038 // A list-item cannot appear in more than one aligned clause.
4039 if (AlignedArgs.count(CanonPVD) > 0) {
4040 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4041 << 1 << E->getSourceRange();
4042 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4043 diag::note_omp_explicit_dsa)
4044 << getOpenMPClauseName(OMPC_aligned);
4045 continue;
4046 }
4047 AlignedArgs[CanonPVD] = E;
4048 QualType QTy = PVD->getType()
4049 .getNonReferenceType()
4050 .getUnqualifiedType()
4051 .getCanonicalType();
4052 const Type *Ty = QTy.getTypePtrOrNull();
4053 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4054 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4055 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4056 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4057 }
4058 continue;
4059 }
4060 }
4061 if (isa<CXXThisExpr>(E)) {
4062 if (AlignedThis) {
4063 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4064 << 2 << E->getSourceRange();
4065 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4066 << getOpenMPClauseName(OMPC_aligned);
4067 }
4068 AlignedThis = E;
4069 continue;
4070 }
4071 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4072 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4073 }
4074 // The optional parameter of the aligned clause, alignment, must be a constant
4075 // positive integer expression. If no optional parameter is specified,
4076 // implementation-defined default alignments for SIMD instructions on the
4077 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004078 SmallVector<const Expr *, 4> NewAligns;
4079 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004080 ExprResult Align;
4081 if (E)
4082 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4083 NewAligns.push_back(Align.get());
4084 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004085 // OpenMP [2.8.2, declare simd construct, Description]
4086 // The linear clause declares one or more list items to be private to a SIMD
4087 // lane and to have a linear relationship with respect to the iteration space
4088 // of a loop.
4089 // The special this pointer can be used as if was one of the arguments to the
4090 // function in any of the linear, aligned, or uniform clauses.
4091 // When a linear-step expression is specified in a linear clause it must be
4092 // either a constant integer expression or an integer-typed parameter that is
4093 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004094 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004095 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4096 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004097 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004098 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4099 ++MI;
4100 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004101 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4102 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4103 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004104 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4105 FD->getParamDecl(PVD->getFunctionScopeIndex())
4106 ->getCanonicalDecl() == CanonPVD) {
4107 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4108 // A list-item cannot appear in more than one linear clause.
4109 if (LinearArgs.count(CanonPVD) > 0) {
4110 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4111 << getOpenMPClauseName(OMPC_linear)
4112 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4113 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4114 diag::note_omp_explicit_dsa)
4115 << getOpenMPClauseName(OMPC_linear);
4116 continue;
4117 }
4118 // Each argument can appear in at most one uniform or linear clause.
4119 if (UniformedArgs.count(CanonPVD) > 0) {
4120 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4121 << getOpenMPClauseName(OMPC_linear)
4122 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4123 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4124 diag::note_omp_explicit_dsa)
4125 << getOpenMPClauseName(OMPC_uniform);
4126 continue;
4127 }
4128 LinearArgs[CanonPVD] = E;
4129 if (E->isValueDependent() || E->isTypeDependent() ||
4130 E->isInstantiationDependent() ||
4131 E->containsUnexpandedParameterPack())
4132 continue;
4133 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4134 PVD->getOriginalType());
4135 continue;
4136 }
4137 }
4138 if (isa<CXXThisExpr>(E)) {
4139 if (UniformedLinearThis) {
4140 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4141 << getOpenMPClauseName(OMPC_linear)
4142 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4143 << E->getSourceRange();
4144 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4145 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4146 : OMPC_linear);
4147 continue;
4148 }
4149 UniformedLinearThis = E;
4150 if (E->isValueDependent() || E->isTypeDependent() ||
4151 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4152 continue;
4153 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4154 E->getType());
4155 continue;
4156 }
4157 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4158 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4159 }
4160 Expr *Step = nullptr;
4161 Expr *NewStep = nullptr;
4162 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004163 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004164 // Skip the same step expression, it was checked already.
4165 if (Step == E || !E) {
4166 NewSteps.push_back(E ? NewStep : nullptr);
4167 continue;
4168 }
4169 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004170 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4171 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4172 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004173 if (UniformedArgs.count(CanonPVD) == 0) {
4174 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4175 << Step->getSourceRange();
4176 } else if (E->isValueDependent() || E->isTypeDependent() ||
4177 E->isInstantiationDependent() ||
4178 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004179 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004180 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004181 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004182 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4183 << Step->getSourceRange();
4184 }
4185 continue;
4186 }
4187 NewStep = Step;
4188 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4189 !Step->isInstantiationDependent() &&
4190 !Step->containsUnexpandedParameterPack()) {
4191 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4192 .get();
4193 if (NewStep)
4194 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4195 }
4196 NewSteps.push_back(NewStep);
4197 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004198 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4199 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004200 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004201 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4202 const_cast<Expr **>(Linears.data()), Linears.size(),
4203 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4204 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004205 ADecl->addAttr(NewAttr);
4206 return ConvertDeclToDeclGroup(ADecl);
4207}
4208
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004209StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4210 Stmt *AStmt,
4211 SourceLocation StartLoc,
4212 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004213 if (!AStmt)
4214 return StmtError();
4215
Alexey Bataeve3727102018-04-18 15:57:46 +00004216 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004217 // 1.2.2 OpenMP Language Terminology
4218 // Structured block - An executable statement with a single entry at the
4219 // top and a single exit at the bottom.
4220 // The point of exit cannot be a branch out of the structured block.
4221 // longjmp() and throw() must not violate the entry/exit criteria.
4222 CS->getCapturedDecl()->setNothrow();
4223
Reid Kleckner87a31802018-03-12 21:43:02 +00004224 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004225
Alexey Bataev25e5b442015-09-15 12:52:43 +00004226 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4227 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004228}
4229
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004230namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004231/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004232/// extracting iteration space of each loop in the loop nest, that will be used
4233/// for IR generation.
4234class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004235 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004236 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004237 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004238 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004239 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004240 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004241 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004242 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004243 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004244 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004245 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004246 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004247 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004248 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004249 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004250 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004251 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004252 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004253 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004254 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004255 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004256 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004257 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004258 /// Var < UB
4259 /// Var <= UB
4260 /// UB > Var
4261 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004262 /// This will have no value when the condition is !=
4263 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004264 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004265 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004266 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004267 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004268
4269public:
4270 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004271 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004272 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004273 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004274 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004275 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004276 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004277 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004278 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004279 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004280 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004281 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004282 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004283 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004284 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004285 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004286 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004287 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004288 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004289 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004290 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004291 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004292 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004293 /// True, if the compare operator is strict (<, > or !=).
4294 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004295 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004296 Expr *buildNumIterations(
4297 Scope *S, const bool LimitedType,
4298 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004299 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004300 Expr *
4301 buildPreCond(Scope *S, Expr *Cond,
4302 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004303 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004304 DeclRefExpr *
4305 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4306 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004307 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004308 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004309 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004310 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004311 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004312 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004313 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004314 /// Build loop data with counter value for depend clauses in ordered
4315 /// directives.
4316 Expr *
4317 buildOrderedLoopData(Scope *S, Expr *Counter,
4318 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4319 SourceLocation Loc, Expr *Inc = nullptr,
4320 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004321 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004322 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004323
4324private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004325 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004326 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004327 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004328 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004329 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004330 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004331 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4332 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004333 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004334 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004335};
4336
Alexey Bataeve3727102018-04-18 15:57:46 +00004337bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004338 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004339 assert(!LB && !UB && !Step);
4340 return false;
4341 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004342 return LCDecl->getType()->isDependentType() ||
4343 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4344 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004345}
4346
Alexey Bataeve3727102018-04-18 15:57:46 +00004347bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004348 Expr *NewLCRefExpr,
4349 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004350 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004351 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004352 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004353 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004354 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004355 LCDecl = getCanonicalDecl(NewLCDecl);
4356 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004357 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4358 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004359 if ((Ctor->isCopyOrMoveConstructor() ||
4360 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4361 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004362 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004363 LB = NewLB;
4364 return false;
4365}
4366
Alexey Bataev316ccf62019-01-29 18:51:58 +00004367bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4368 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004369 bool StrictOp, SourceRange SR,
4370 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004371 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004372 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4373 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004374 if (!NewUB)
4375 return true;
4376 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004377 if (LessOp)
4378 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004379 TestIsStrictOp = StrictOp;
4380 ConditionSrcRange = SR;
4381 ConditionLoc = SL;
4382 return false;
4383}
4384
Alexey Bataeve3727102018-04-18 15:57:46 +00004385bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004386 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004387 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004388 if (!NewStep)
4389 return true;
4390 if (!NewStep->isValueDependent()) {
4391 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004392 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004393 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4394 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004395 if (Val.isInvalid())
4396 return true;
4397 NewStep = Val.get();
4398
4399 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4400 // If test-expr is of form var relational-op b and relational-op is < or
4401 // <= then incr-expr must cause var to increase on each iteration of the
4402 // loop. If test-expr is of form var relational-op b and relational-op is
4403 // > or >= then incr-expr must cause var to decrease on each iteration of
4404 // the loop.
4405 // If test-expr is of form b relational-op var and relational-op is < or
4406 // <= then incr-expr must cause var to decrease on each iteration of the
4407 // loop. If test-expr is of form b relational-op var and relational-op is
4408 // > or >= then incr-expr must cause var to increase on each iteration of
4409 // the loop.
4410 llvm::APSInt Result;
4411 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4412 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4413 bool IsConstNeg =
4414 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004415 bool IsConstPos =
4416 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004417 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004418
4419 // != with increment is treated as <; != with decrement is treated as >
4420 if (!TestIsLessOp.hasValue())
4421 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004422 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004423 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004424 (IsConstNeg || (IsUnsigned && Subtract)) :
4425 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004426 SemaRef.Diag(NewStep->getExprLoc(),
4427 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004428 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004429 SemaRef.Diag(ConditionLoc,
4430 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004431 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004432 return true;
4433 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004434 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004435 NewStep =
4436 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4437 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004438 Subtract = !Subtract;
4439 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004440 }
4441
4442 Step = NewStep;
4443 SubtractStep = Subtract;
4444 return false;
4445}
4446
Alexey Bataeve3727102018-04-18 15:57:46 +00004447bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004448 // Check init-expr for canonical loop form and save loop counter
4449 // variable - #Var and its initialization value - #LB.
4450 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4451 // var = lb
4452 // integer-type var = lb
4453 // random-access-iterator-type var = lb
4454 // pointer-type var = lb
4455 //
4456 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004457 if (EmitDiags) {
4458 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4459 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004460 return true;
4461 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004462 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4463 if (!ExprTemp->cleanupsHaveSideEffects())
4464 S = ExprTemp->getSubExpr();
4465
Alexander Musmana5f070a2014-10-01 06:03:56 +00004466 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004467 if (Expr *E = dyn_cast<Expr>(S))
4468 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004469 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004470 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004471 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004472 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4473 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4474 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004475 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4476 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004477 }
4478 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4479 if (ME->isArrow() &&
4480 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004481 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004482 }
4483 }
David Majnemer9d168222016-08-05 17:44:54 +00004484 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004485 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004486 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004487 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004488 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004489 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004490 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004491 diag::ext_omp_loop_not_canonical_init)
4492 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004493 return setLCDeclAndLB(
4494 Var,
4495 buildDeclRefExpr(SemaRef, Var,
4496 Var->getType().getNonReferenceType(),
4497 DS->getBeginLoc()),
4498 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004499 }
4500 }
4501 }
David Majnemer9d168222016-08-05 17:44:54 +00004502 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004503 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004504 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004505 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004506 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4507 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004508 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4509 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004510 }
4511 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4512 if (ME->isArrow() &&
4513 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004514 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004515 }
4516 }
4517 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004518
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004520 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004521 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004522 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004523 << S->getSourceRange();
4524 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004525 return true;
4526}
4527
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004528/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004529/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004530static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004531 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004532 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004533 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004534 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004535 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004536 if ((Ctor->isCopyOrMoveConstructor() ||
4537 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4538 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004539 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004540 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4541 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004542 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004543 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004544 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004545 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4546 return getCanonicalDecl(ME->getMemberDecl());
4547 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004548}
4549
Alexey Bataeve3727102018-04-18 15:57:46 +00004550bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004551 // Check test-expr for canonical form, save upper-bound UB, flags for
4552 // less/greater and for strict/non-strict comparison.
4553 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4554 // var relational-op b
4555 // b relational-op var
4556 //
4557 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004558 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004559 return true;
4560 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004561 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004562 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004563 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004564 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004565 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4566 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004567 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4568 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4569 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004570 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4571 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004572 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4573 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4574 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004575 } else if (BO->getOpcode() == BO_NE)
4576 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4577 BO->getRHS() : BO->getLHS(),
4578 /*LessOp=*/llvm::None,
4579 /*StrictOp=*/true,
4580 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004581 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004582 if (CE->getNumArgs() == 2) {
4583 auto Op = CE->getOperator();
4584 switch (Op) {
4585 case OO_Greater:
4586 case OO_GreaterEqual:
4587 case OO_Less:
4588 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004589 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4590 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004591 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4592 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004593 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4594 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004595 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4596 CE->getOperatorLoc());
4597 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004598 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004599 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4600 CE->getArg(1) : CE->getArg(0),
4601 /*LessOp=*/llvm::None,
4602 /*StrictOp=*/true,
4603 CE->getSourceRange(),
4604 CE->getOperatorLoc());
4605 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004606 default:
4607 break;
4608 }
4609 }
4610 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004611 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004612 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004613 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004614 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004615 return true;
4616}
4617
Alexey Bataeve3727102018-04-18 15:57:46 +00004618bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004619 // RHS of canonical loop form increment can be:
4620 // var + incr
4621 // incr + var
4622 // var - incr
4623 //
4624 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004625 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004626 if (BO->isAdditiveOp()) {
4627 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004628 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4629 return setStep(BO->getRHS(), !IsAdd);
4630 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4631 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004632 }
David Majnemer9d168222016-08-05 17:44:54 +00004633 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004634 bool IsAdd = CE->getOperator() == OO_Plus;
4635 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004636 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4637 return setStep(CE->getArg(1), !IsAdd);
4638 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4639 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004640 }
4641 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004642 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004643 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004644 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004645 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004646 return true;
4647}
4648
Alexey Bataeve3727102018-04-18 15:57:46 +00004649bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004650 // Check incr-expr for canonical loop form and return true if it
4651 // does not conform.
4652 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4653 // ++var
4654 // var++
4655 // --var
4656 // var--
4657 // var += incr
4658 // var -= incr
4659 // var = var + incr
4660 // var = incr + var
4661 // var = var - incr
4662 //
4663 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004664 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004665 return true;
4666 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004667 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4668 if (!ExprTemp->cleanupsHaveSideEffects())
4669 S = ExprTemp->getSubExpr();
4670
Alexander Musmana5f070a2014-10-01 06:03:56 +00004671 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004672 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004673 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004674 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004675 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4676 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004677 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004678 (UO->isDecrementOp() ? -1 : 1))
4679 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004680 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004681 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004682 switch (BO->getOpcode()) {
4683 case BO_AddAssign:
4684 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004685 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4686 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004687 break;
4688 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004689 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4690 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004691 break;
4692 default:
4693 break;
4694 }
David Majnemer9d168222016-08-05 17:44:54 +00004695 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004696 switch (CE->getOperator()) {
4697 case OO_PlusPlus:
4698 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004699 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4700 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004701 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004702 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004703 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4704 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004705 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004706 break;
4707 case OO_PlusEqual:
4708 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004709 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4710 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004711 break;
4712 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004713 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4714 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004715 break;
4716 default:
4717 break;
4718 }
4719 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004720 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004721 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004722 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004723 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004724 return true;
4725}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004726
Alexey Bataev5a3af132016-03-29 08:58:54 +00004727static ExprResult
4728tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004729 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004730 if (SemaRef.CurContext->isDependentContext())
4731 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004732 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4733 return SemaRef.PerformImplicitConversion(
4734 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4735 /*AllowExplicit=*/true);
4736 auto I = Captures.find(Capture);
4737 if (I != Captures.end())
4738 return buildCapture(SemaRef, Capture, I->second);
4739 DeclRefExpr *Ref = nullptr;
4740 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4741 Captures[Capture] = Ref;
4742 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004743}
4744
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004745/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004746Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004747 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004748 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004749 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004750 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004751 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004752 SemaRef.getLangOpts().CPlusPlus) {
4753 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004754 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4755 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004756 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4757 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004758 if (!Upper || !Lower)
4759 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004760
4761 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4762
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004763 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004764 // BuildBinOp already emitted error, this one is to point user to upper
4765 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004766 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004767 << Upper->getSourceRange() << Lower->getSourceRange();
4768 return nullptr;
4769 }
4770 }
4771
4772 if (!Diff.isUsable())
4773 return nullptr;
4774
4775 // Upper - Lower [- 1]
4776 if (TestIsStrictOp)
4777 Diff = SemaRef.BuildBinOp(
4778 S, DefaultLoc, BO_Sub, Diff.get(),
4779 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4780 if (!Diff.isUsable())
4781 return nullptr;
4782
4783 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004784 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004785 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004786 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004787 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004788 if (!Diff.isUsable())
4789 return nullptr;
4790
4791 // Parentheses (for dumping/debugging purposes only).
4792 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4793 if (!Diff.isUsable())
4794 return nullptr;
4795
4796 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004797 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004798 if (!Diff.isUsable())
4799 return nullptr;
4800
Alexander Musman174b3ca2014-10-06 11:16:29 +00004801 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004802 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004803 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004804 bool UseVarType = VarType->hasIntegerRepresentation() &&
4805 C.getTypeSize(Type) > C.getTypeSize(VarType);
4806 if (!Type->isIntegerType() || UseVarType) {
4807 unsigned NewSize =
4808 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4809 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4810 : Type->hasSignedIntegerRepresentation();
4811 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004812 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4813 Diff = SemaRef.PerformImplicitConversion(
4814 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4815 if (!Diff.isUsable())
4816 return nullptr;
4817 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004818 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004819 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004820 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4821 if (NewSize != C.getTypeSize(Type)) {
4822 if (NewSize < C.getTypeSize(Type)) {
4823 assert(NewSize == 64 && "incorrect loop var size");
4824 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4825 << InitSrcRange << ConditionSrcRange;
4826 }
4827 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004828 NewSize, Type->hasSignedIntegerRepresentation() ||
4829 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004830 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4831 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4832 Sema::AA_Converting, true);
4833 if (!Diff.isUsable())
4834 return nullptr;
4835 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004836 }
4837 }
4838
Alexander Musmana5f070a2014-10-01 06:03:56 +00004839 return Diff.get();
4840}
4841
Alexey Bataeve3727102018-04-18 15:57:46 +00004842Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004843 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004844 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004845 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4846 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4847 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004848
Alexey Bataeve3727102018-04-18 15:57:46 +00004849 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4850 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004851 if (!NewLB.isUsable() || !NewUB.isUsable())
4852 return nullptr;
4853
Alexey Bataeve3727102018-04-18 15:57:46 +00004854 ExprResult CondExpr =
4855 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004856 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004857 (TestIsStrictOp ? BO_LT : BO_LE) :
4858 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004859 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004860 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004861 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4862 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004863 CondExpr = SemaRef.PerformImplicitConversion(
4864 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4865 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004866 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004867 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004868 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004869 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4870}
4871
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004872/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004873DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004874 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4875 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004876 auto *VD = dyn_cast<VarDecl>(LCDecl);
4877 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004878 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4879 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004880 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004881 const DSAStackTy::DSAVarData Data =
4882 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004883 // If the loop control decl is explicitly marked as private, do not mark it
4884 // as captured again.
4885 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4886 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004887 return Ref;
4888 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00004889 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00004890}
4891
Alexey Bataeve3727102018-04-18 15:57:46 +00004892Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004893 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004894 QualType Type = LCDecl->getType().getNonReferenceType();
4895 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004896 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4897 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4898 isa<VarDecl>(LCDecl)
4899 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4900 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004901 if (PrivateVar->isInvalidDecl())
4902 return nullptr;
4903 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4904 }
4905 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004906}
4907
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004908/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004909Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004910
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004911/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004912Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004913
Alexey Bataevf138fda2018-08-13 19:04:24 +00004914Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4915 Scope *S, Expr *Counter,
4916 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4917 Expr *Inc, OverloadedOperatorKind OOK) {
4918 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4919 if (!Cnt)
4920 return nullptr;
4921 if (Inc) {
4922 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4923 "Expected only + or - operations for depend clauses.");
4924 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4925 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4926 if (!Cnt)
4927 return nullptr;
4928 }
4929 ExprResult Diff;
4930 QualType VarType = LCDecl->getType().getNonReferenceType();
4931 if (VarType->isIntegerType() || VarType->isPointerType() ||
4932 SemaRef.getLangOpts().CPlusPlus) {
4933 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004934 Expr *Upper = TestIsLessOp.getValue()
4935 ? Cnt
4936 : tryBuildCapture(SemaRef, UB, Captures).get();
4937 Expr *Lower = TestIsLessOp.getValue()
4938 ? tryBuildCapture(SemaRef, LB, Captures).get()
4939 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004940 if (!Upper || !Lower)
4941 return nullptr;
4942
4943 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4944
4945 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4946 // BuildBinOp already emitted error, this one is to point user to upper
4947 // and lower bound, and to tell what is passed to 'operator-'.
4948 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4949 << Upper->getSourceRange() << Lower->getSourceRange();
4950 return nullptr;
4951 }
4952 }
4953
4954 if (!Diff.isUsable())
4955 return nullptr;
4956
4957 // Parentheses (for dumping/debugging purposes only).
4958 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4959 if (!Diff.isUsable())
4960 return nullptr;
4961
4962 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4963 if (!NewStep.isUsable())
4964 return nullptr;
4965 // (Upper - Lower) / Step
4966 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4967 if (!Diff.isUsable())
4968 return nullptr;
4969
4970 return Diff.get();
4971}
4972
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004973/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004974struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004975 /// True if the condition operator is the strict compare operator (<, > or
4976 /// !=).
4977 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004978 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004979 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004980 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004981 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004982 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004983 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004984 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004985 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004986 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004987 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004988 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004989 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004990 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004991 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004992 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004993 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004994 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004995 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004996 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004997 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004998 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004999 SourceRange IncSrcRange;
5000};
5001
Alexey Bataev23b69422014-06-18 07:08:49 +00005002} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005003
Alexey Bataev9c821032015-04-30 04:23:23 +00005004void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5005 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5006 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005007 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5008 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005009 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005010 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00005011 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005012 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5013 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005014 auto *VD = dyn_cast<VarDecl>(D);
5015 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005016 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005017 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005018 } else {
5019 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5020 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005021 VD = cast<VarDecl>(Ref->getDecl());
5022 }
5023 }
5024 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005025 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5026 if (LD != D->getCanonicalDecl()) {
5027 DSAStack->resetPossibleLoopCounter();
5028 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5029 MarkDeclarationsReferencedInExpr(
5030 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5031 Var->getType().getNonLValueExprType(Context),
5032 ForLoc, /*RefersToCapture=*/true));
5033 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005034 }
5035 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005036 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005037 }
5038}
5039
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005040/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005041/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005042static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005043 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5044 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005045 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5046 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005047 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005048 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005049 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005050 // OpenMP [2.6, Canonical Loop Form]
5051 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005052 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005053 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005054 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005055 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005056 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005057 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005058 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005059 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5060 SemaRef.Diag(DSA.getConstructLoc(),
5061 diag::note_omp_collapse_ordered_expr)
5062 << 2 << CollapseLoopCountExpr->getSourceRange()
5063 << OrderedLoopCountExpr->getSourceRange();
5064 else if (CollapseLoopCountExpr)
5065 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5066 diag::note_omp_collapse_ordered_expr)
5067 << 0 << CollapseLoopCountExpr->getSourceRange();
5068 else
5069 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5070 diag::note_omp_collapse_ordered_expr)
5071 << 1 << OrderedLoopCountExpr->getSourceRange();
5072 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005073 return true;
5074 }
5075 assert(For->getBody());
5076
5077 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5078
5079 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005080 Stmt *Init = For->getInit();
5081 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005082 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005083
5084 bool HasErrors = false;
5085
5086 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005087 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5088 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005089
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005090 // OpenMP [2.6, Canonical Loop Form]
5091 // Var is one of the following:
5092 // A variable of signed or unsigned integer type.
5093 // For C++, a variable of a random access iterator type.
5094 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005095 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005096 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5097 !VarType->isPointerType() &&
5098 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005099 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005100 << SemaRef.getLangOpts().CPlusPlus;
5101 HasErrors = true;
5102 }
5103
5104 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5105 // a Construct
5106 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5107 // parallel for construct is (are) private.
5108 // The loop iteration variable in the associated for-loop of a simd
5109 // construct with just one associated for-loop is linear with a
5110 // constant-linear-step that is the increment of the associated for-loop.
5111 // Exclude loop var from the list of variables with implicitly defined data
5112 // sharing attributes.
5113 VarsWithImplicitDSA.erase(LCDecl);
5114
5115 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5116 // in a Construct, C/C++].
5117 // The loop iteration variable in the associated for-loop of a simd
5118 // construct with just one associated for-loop may be listed in a linear
5119 // clause with a constant-linear-step that is the increment of the
5120 // associated for-loop.
5121 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5122 // parallel for construct may be listed in a private or lastprivate clause.
5123 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5124 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5125 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005126 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005127 isOpenMPSimdDirective(DKind)
5128 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5129 : OMPC_private;
5130 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5131 DVar.CKind != PredeterminedCKind) ||
5132 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5133 isOpenMPDistributeDirective(DKind)) &&
5134 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5135 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5136 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005137 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005138 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5139 << getOpenMPClauseName(PredeterminedCKind);
5140 if (DVar.RefExpr == nullptr)
5141 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005142 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005143 HasErrors = true;
5144 } else if (LoopDeclRefExpr != nullptr) {
5145 // Make the loop iteration variable private (for worksharing constructs),
5146 // linear (for simd directives with the only one associated loop) or
5147 // lastprivate (for simd directives with several collapsed or ordered
5148 // loops).
5149 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005150 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005151 }
5152
5153 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5154
5155 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005156 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005157
5158 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005159 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005160 }
5161
Alexey Bataeve3727102018-04-18 15:57:46 +00005162 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005163 return HasErrors;
5164
Alexander Musmana5f070a2014-10-01 06:03:56 +00005165 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005166 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005167 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5168 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005169 DSA.getCurScope(),
5170 (isOpenMPWorksharingDirective(DKind) ||
5171 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5172 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005173 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5174 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5175 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5176 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5177 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5178 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5179 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5180 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005181 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005182
Alexey Bataev62dbb972015-04-22 11:59:37 +00005183 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5184 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005185 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005186 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005187 ResultIterSpace.CounterInit == nullptr ||
5188 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005189 if (!HasErrors && DSA.isOrderedRegion()) {
5190 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5191 if (CurrentNestedLoopCount <
5192 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5193 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5194 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5195 DSA.getOrderedRegionParam().second->setLoopCounter(
5196 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5197 }
5198 }
5199 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5200 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5201 // Erroneous case - clause has some problems.
5202 continue;
5203 }
5204 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5205 Pair.second.size() <= CurrentNestedLoopCount) {
5206 // Erroneous case - clause has some problems.
5207 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5208 continue;
5209 }
5210 Expr *CntValue;
5211 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5212 CntValue = ISC.buildOrderedLoopData(
5213 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5214 Pair.first->getDependencyLoc());
5215 else
5216 CntValue = ISC.buildOrderedLoopData(
5217 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5218 Pair.first->getDependencyLoc(),
5219 Pair.second[CurrentNestedLoopCount].first,
5220 Pair.second[CurrentNestedLoopCount].second);
5221 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5222 }
5223 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005224
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005225 return HasErrors;
5226}
5227
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005228/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005229static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005230buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005231 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005232 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005233 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005234 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005235 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005236 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005237 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005238 VarRef.get()->getType())) {
5239 NewStart = SemaRef.PerformImplicitConversion(
5240 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5241 /*AllowExplicit=*/true);
5242 if (!NewStart.isUsable())
5243 return ExprError();
5244 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005245
Alexey Bataeve3727102018-04-18 15:57:46 +00005246 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005247 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5248 return Init;
5249}
5250
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005251/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005252static ExprResult buildCounterUpdate(
5253 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5254 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5255 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005256 // Add parentheses (for debugging purposes only).
5257 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5258 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5259 !Step.isUsable())
5260 return ExprError();
5261
Alexey Bataev5a3af132016-03-29 08:58:54 +00005262 ExprResult NewStep = Step;
5263 if (Captures)
5264 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005265 if (NewStep.isInvalid())
5266 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005267 ExprResult Update =
5268 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005269 if (!Update.isUsable())
5270 return ExprError();
5271
Alexey Bataevc0214e02016-02-16 12:13:49 +00005272 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5273 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005274 ExprResult NewStart = Start;
5275 if (Captures)
5276 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005277 if (NewStart.isInvalid())
5278 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005279
Alexey Bataevc0214e02016-02-16 12:13:49 +00005280 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5281 ExprResult SavedUpdate = Update;
5282 ExprResult UpdateVal;
5283 if (VarRef.get()->getType()->isOverloadableType() ||
5284 NewStart.get()->getType()->isOverloadableType() ||
5285 Update.get()->getType()->isOverloadableType()) {
5286 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5287 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5288 Update =
5289 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5290 if (Update.isUsable()) {
5291 UpdateVal =
5292 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5293 VarRef.get(), SavedUpdate.get());
5294 if (UpdateVal.isUsable()) {
5295 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5296 UpdateVal.get());
5297 }
5298 }
5299 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5300 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005301
Alexey Bataevc0214e02016-02-16 12:13:49 +00005302 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5303 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5304 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5305 NewStart.get(), SavedUpdate.get());
5306 if (!Update.isUsable())
5307 return ExprError();
5308
Alexey Bataev11481f52016-02-17 10:29:05 +00005309 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5310 VarRef.get()->getType())) {
5311 Update = SemaRef.PerformImplicitConversion(
5312 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5313 if (!Update.isUsable())
5314 return ExprError();
5315 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005316
5317 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5318 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005319 return Update;
5320}
5321
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005322/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005323/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005324static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005325 if (E == nullptr)
5326 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005327 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005328 QualType OldType = E->getType();
5329 unsigned HasBits = C.getTypeSize(OldType);
5330 if (HasBits >= Bits)
5331 return ExprResult(E);
5332 // OK to convert to signed, because new type has more bits than old.
5333 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5334 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5335 true);
5336}
5337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005338/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005339/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005340static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005341 if (E == nullptr)
5342 return false;
5343 llvm::APSInt Result;
5344 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5345 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5346 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005347}
5348
Alexey Bataev5a3af132016-03-29 08:58:54 +00005349/// Build preinits statement for the given declarations.
5350static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005351 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005352 if (!PreInits.empty()) {
5353 return new (Context) DeclStmt(
5354 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5355 SourceLocation(), SourceLocation());
5356 }
5357 return nullptr;
5358}
5359
5360/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005361static Stmt *
5362buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005363 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005364 if (!Captures.empty()) {
5365 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005366 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005367 PreInits.push_back(Pair.second->getDecl());
5368 return buildPreInits(Context, PreInits);
5369 }
5370 return nullptr;
5371}
5372
5373/// Build postupdate expression for the given list of postupdates expressions.
5374static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5375 Expr *PostUpdate = nullptr;
5376 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005377 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005378 Expr *ConvE = S.BuildCStyleCastExpr(
5379 E->getExprLoc(),
5380 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5381 E->getExprLoc(), E)
5382 .get();
5383 PostUpdate = PostUpdate
5384 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5385 PostUpdate, ConvE)
5386 .get()
5387 : ConvE;
5388 }
5389 }
5390 return PostUpdate;
5391}
5392
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005393/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005394/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5395/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005396static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005397checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005398 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5399 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005400 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005401 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005402 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005403 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005404 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005405 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005406 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005407 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005408 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005409 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005410 if (OrderedLoopCountExpr) {
5411 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005412 Expr::EvalResult EVResult;
5413 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5414 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005415 if (Result.getLimitedValue() < NestedLoopCount) {
5416 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5417 diag::err_omp_wrong_ordered_loop_count)
5418 << OrderedLoopCountExpr->getSourceRange();
5419 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5420 diag::note_collapse_loop_count)
5421 << CollapseLoopCountExpr->getSourceRange();
5422 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005423 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005424 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005425 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005426 // This is helper routine for loop directives (e.g., 'for', 'simd',
5427 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005428 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005429 SmallVector<LoopIterationSpace, 4> IterSpaces(
5430 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005431 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005432 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005433 if (checkOpenMPIterationSpace(
5434 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5435 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5436 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5437 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005438 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005439 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005440 // OpenMP [2.8.1, simd construct, Restrictions]
5441 // All loops associated with the construct must be perfectly nested; that
5442 // is, there must be no intervening code nor any OpenMP directive between
5443 // any two loops.
5444 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005445 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005446 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5447 if (checkOpenMPIterationSpace(
5448 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5449 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5450 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5451 Captures))
5452 return 0;
5453 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5454 // Handle initialization of captured loop iterator variables.
5455 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5456 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5457 Captures[DRE] = DRE;
5458 }
5459 }
5460 // Move on to the next nested for loop, or to the loop body.
5461 // OpenMP [2.8.1, simd construct, Restrictions]
5462 // All loops associated with the construct must be perfectly nested; that
5463 // is, there must be no intervening code nor any OpenMP directive between
5464 // any two loops.
5465 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5466 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005467
Alexander Musmana5f070a2014-10-01 06:03:56 +00005468 Built.clear(/* size */ NestedLoopCount);
5469
5470 if (SemaRef.CurContext->isDependentContext())
5471 return NestedLoopCount;
5472
5473 // An example of what is generated for the following code:
5474 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005475 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005476 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005477 // for (k = 0; k < NK; ++k)
5478 // for (j = J0; j < NJ; j+=2) {
5479 // <loop body>
5480 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005481 //
5482 // We generate the code below.
5483 // Note: the loop body may be outlined in CodeGen.
5484 // Note: some counters may be C++ classes, operator- is used to find number of
5485 // iterations and operator+= to calculate counter value.
5486 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5487 // or i64 is currently supported).
5488 //
5489 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5490 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5491 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5492 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5493 // // similar updates for vars in clauses (e.g. 'linear')
5494 // <loop body (using local i and j)>
5495 // }
5496 // i = NI; // assign final values of counters
5497 // j = NJ;
5498 //
5499
5500 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5501 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005502 // Precondition tests if there is at least one iteration (all conditions are
5503 // true).
5504 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005505 Expr *N0 = IterSpaces[0].NumIterations;
5506 ExprResult LastIteration32 =
5507 widenIterationCount(/*Bits=*/32,
5508 SemaRef
5509 .PerformImplicitConversion(
5510 N0->IgnoreImpCasts(), N0->getType(),
5511 Sema::AA_Converting, /*AllowExplicit=*/true)
5512 .get(),
5513 SemaRef);
5514 ExprResult LastIteration64 = widenIterationCount(
5515 /*Bits=*/64,
5516 SemaRef
5517 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5518 Sema::AA_Converting,
5519 /*AllowExplicit=*/true)
5520 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005521 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005522
5523 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5524 return NestedLoopCount;
5525
Alexey Bataeve3727102018-04-18 15:57:46 +00005526 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005527 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5528
5529 Scope *CurScope = DSA.getCurScope();
5530 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005531 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005532 PreCond =
5533 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5534 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005535 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005536 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005537 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005538 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5539 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005540 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005541 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005542 SemaRef
5543 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5544 Sema::AA_Converting,
5545 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005546 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005547 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005548 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005549 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005550 SemaRef
5551 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5552 Sema::AA_Converting,
5553 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005554 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005555 }
5556
5557 // Choose either the 32-bit or 64-bit version.
5558 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005559 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5560 (LastIteration32.isUsable() &&
5561 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5562 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5563 fitsInto(
5564 /*Bits=*/32,
5565 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5566 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005567 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005568 QualType VType = LastIteration.get()->getType();
5569 QualType RealVType = VType;
5570 QualType StrideVType = VType;
5571 if (isOpenMPTaskLoopDirective(DKind)) {
5572 VType =
5573 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5574 StrideVType =
5575 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5576 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005577
5578 if (!LastIteration.isUsable())
5579 return 0;
5580
5581 // Save the number of iterations.
5582 ExprResult NumIterations = LastIteration;
5583 {
5584 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005585 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5586 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005587 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5588 if (!LastIteration.isUsable())
5589 return 0;
5590 }
5591
5592 // Calculate the last iteration number beforehand instead of doing this on
5593 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5594 llvm::APSInt Result;
5595 bool IsConstant =
5596 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5597 ExprResult CalcLastIteration;
5598 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005599 ExprResult SaveRef =
5600 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005601 LastIteration = SaveRef;
5602
5603 // Prepare SaveRef + 1.
5604 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005605 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005606 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5607 if (!NumIterations.isUsable())
5608 return 0;
5609 }
5610
5611 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5612
David Majnemer9d168222016-08-05 17:44:54 +00005613 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005614 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005615 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5616 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005617 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005618 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5619 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005620 SemaRef.AddInitializerToDecl(LBDecl,
5621 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5622 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005623
5624 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005625 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5626 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005627 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005628 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005629
5630 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5631 // This will be used to implement clause 'lastprivate'.
5632 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005633 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5634 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005635 SemaRef.AddInitializerToDecl(ILDecl,
5636 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5637 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005638
5639 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005640 VarDecl *STDecl =
5641 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5642 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005643 SemaRef.AddInitializerToDecl(STDecl,
5644 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5645 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005646
5647 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005648 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005649 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5650 UB.get(), LastIteration.get());
5651 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005652 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5653 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005654 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5655 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005656 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005657
5658 // If we have a combined directive that combines 'distribute', 'for' or
5659 // 'simd' we need to be able to access the bounds of the schedule of the
5660 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5661 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5662 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005663 // Lower bound variable, initialized with zero.
5664 VarDecl *CombLBDecl =
5665 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5666 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5667 SemaRef.AddInitializerToDecl(
5668 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5669 /*DirectInit*/ false);
5670
5671 // Upper bound variable, initialized with last iteration number.
5672 VarDecl *CombUBDecl =
5673 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5674 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5675 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5676 /*DirectInit*/ false);
5677
5678 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5679 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5680 ExprResult CombCondOp =
5681 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5682 LastIteration.get(), CombUB.get());
5683 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5684 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005685 CombEUB =
5686 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005687
Alexey Bataeve3727102018-04-18 15:57:46 +00005688 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005689 // We expect to have at least 2 more parameters than the 'parallel'
5690 // directive does - the lower and upper bounds of the previous schedule.
5691 assert(CD->getNumParams() >= 4 &&
5692 "Unexpected number of parameters in loop combined directive");
5693
5694 // Set the proper type for the bounds given what we learned from the
5695 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005696 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5697 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005698
5699 // Previous lower and upper bounds are obtained from the region
5700 // parameters.
5701 PrevLB =
5702 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5703 PrevUB =
5704 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5705 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005706 }
5707
5708 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005709 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005710 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005711 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005712 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5713 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005714 Expr *RHS =
5715 (isOpenMPWorksharingDirective(DKind) ||
5716 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5717 ? LB.get()
5718 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005719 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005720 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005721
5722 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5723 Expr *CombRHS =
5724 (isOpenMPWorksharingDirective(DKind) ||
5725 isOpenMPTaskLoopDirective(DKind) ||
5726 isOpenMPDistributeDirective(DKind))
5727 ? CombLB.get()
5728 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5729 CombInit =
5730 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005731 CombInit =
5732 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005733 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005734 }
5735
Alexey Bataev316ccf62019-01-29 18:51:58 +00005736 bool UseStrictCompare =
5737 RealVType->hasUnsignedIntegerRepresentation() &&
5738 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5739 return LIS.IsStrictCompare;
5740 });
5741 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5742 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005743 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005744 Expr *BoundUB = UB.get();
5745 if (UseStrictCompare) {
5746 BoundUB =
5747 SemaRef
5748 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5749 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5750 .get();
5751 BoundUB =
5752 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5753 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005754 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005755 (isOpenMPWorksharingDirective(DKind) ||
5756 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005757 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5758 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5759 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005760 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5761 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005762 ExprResult CombDistCond;
5763 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005764 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5765 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005766 }
5767
Carlo Bertolliffafe102017-04-20 00:39:39 +00005768 ExprResult CombCond;
5769 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005770 Expr *BoundCombUB = CombUB.get();
5771 if (UseStrictCompare) {
5772 BoundCombUB =
5773 SemaRef
5774 .BuildBinOp(
5775 CurScope, CondLoc, BO_Add, BoundCombUB,
5776 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5777 .get();
5778 BoundCombUB =
5779 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5780 .get();
5781 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005782 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005783 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5784 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005785 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005786 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005787 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005788 ExprResult Inc =
5789 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5790 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5791 if (!Inc.isUsable())
5792 return 0;
5793 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005794 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005795 if (!Inc.isUsable())
5796 return 0;
5797
5798 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5799 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005800 // In combined construct, add combined version that use CombLB and CombUB
5801 // base variables for the update
5802 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005803 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5804 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005805 // LB + ST
5806 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5807 if (!NextLB.isUsable())
5808 return 0;
5809 // LB = LB + ST
5810 NextLB =
5811 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005812 NextLB =
5813 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005814 if (!NextLB.isUsable())
5815 return 0;
5816 // UB + ST
5817 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5818 if (!NextUB.isUsable())
5819 return 0;
5820 // UB = UB + ST
5821 NextUB =
5822 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005823 NextUB =
5824 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005825 if (!NextUB.isUsable())
5826 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005827 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5828 CombNextLB =
5829 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5830 if (!NextLB.isUsable())
5831 return 0;
5832 // LB = LB + ST
5833 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5834 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005835 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5836 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005837 if (!CombNextLB.isUsable())
5838 return 0;
5839 // UB + ST
5840 CombNextUB =
5841 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5842 if (!CombNextUB.isUsable())
5843 return 0;
5844 // UB = UB + ST
5845 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5846 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005847 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5848 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005849 if (!CombNextUB.isUsable())
5850 return 0;
5851 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005852 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005853
Carlo Bertolliffafe102017-04-20 00:39:39 +00005854 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005855 // directive with for as IV = IV + ST; ensure upper bound expression based
5856 // on PrevUB instead of NumIterations - used to implement 'for' when found
5857 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005858 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005859 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005860 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005861 DistCond = SemaRef.BuildBinOp(
5862 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005863 assert(DistCond.isUsable() && "distribute cond expr was not built");
5864
5865 DistInc =
5866 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5867 assert(DistInc.isUsable() && "distribute inc expr was not built");
5868 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5869 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005870 DistInc =
5871 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005872 assert(DistInc.isUsable() && "distribute inc expr was not built");
5873
5874 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5875 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005876 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005877 ExprResult IsUBGreater =
5878 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5879 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5880 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5881 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5882 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005883 PrevEUB =
5884 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005885
Alexey Bataev316ccf62019-01-29 18:51:58 +00005886 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5887 // parallel for is in combination with a distribute directive with
5888 // schedule(static, 1)
5889 Expr *BoundPrevUB = PrevUB.get();
5890 if (UseStrictCompare) {
5891 BoundPrevUB =
5892 SemaRef
5893 .BuildBinOp(
5894 CurScope, CondLoc, BO_Add, BoundPrevUB,
5895 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5896 .get();
5897 BoundPrevUB =
5898 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5899 .get();
5900 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005901 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005902 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5903 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005904 }
5905
Alexander Musmana5f070a2014-10-01 06:03:56 +00005906 // Build updates and final values of the loop counters.
5907 bool HasErrors = false;
5908 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005909 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005910 Built.Updates.resize(NestedLoopCount);
5911 Built.Finals.resize(NestedLoopCount);
5912 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005913 // We implement the following algorithm for obtaining the
5914 // original loop iteration variable values based on the
5915 // value of the collapsed loop iteration variable IV.
5916 //
5917 // Let n+1 be the number of collapsed loops in the nest.
5918 // Iteration variables (I0, I1, .... In)
5919 // Iteration counts (N0, N1, ... Nn)
5920 //
5921 // Acc = IV;
5922 //
5923 // To compute Ik for loop k, 0 <= k <= n, generate:
5924 // Prod = N(k+1) * N(k+2) * ... * Nn;
5925 // Ik = Acc / Prod;
5926 // Acc -= Ik * Prod;
5927 //
5928 ExprResult Acc = IV;
5929 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005930 LoopIterationSpace &IS = IterSpaces[Cnt];
5931 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005932 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005933
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005934 // Compute prod
5935 ExprResult Prod =
5936 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5937 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5938 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5939 IterSpaces[K].NumIterations);
5940
5941 // Iter = Acc / Prod
5942 // If there is at least one more inner loop to avoid
5943 // multiplication by 1.
5944 if (Cnt + 1 < NestedLoopCount)
5945 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5946 Acc.get(), Prod.get());
5947 else
5948 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005949 if (!Iter.isUsable()) {
5950 HasErrors = true;
5951 break;
5952 }
5953
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005954 // Update Acc:
5955 // Acc -= Iter * Prod
5956 // Check if there is at least one more inner loop to avoid
5957 // multiplication by 1.
5958 if (Cnt + 1 < NestedLoopCount)
5959 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5960 Iter.get(), Prod.get());
5961 else
5962 Prod = Iter;
5963 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5964 Acc.get(), Prod.get());
5965
Alexey Bataev39f915b82015-05-08 10:41:21 +00005966 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005967 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005968 DeclRefExpr *CounterVar = buildDeclRefExpr(
5969 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5970 /*RefersToCapture=*/true);
5971 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005972 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005973 if (!Init.isUsable()) {
5974 HasErrors = true;
5975 break;
5976 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005977 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005978 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5979 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005980 if (!Update.isUsable()) {
5981 HasErrors = true;
5982 break;
5983 }
5984
5985 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005986 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005987 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005988 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005989 if (!Final.isUsable()) {
5990 HasErrors = true;
5991 break;
5992 }
5993
Alexander Musmana5f070a2014-10-01 06:03:56 +00005994 if (!Update.isUsable() || !Final.isUsable()) {
5995 HasErrors = true;
5996 break;
5997 }
5998 // Save results
5999 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006000 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006001 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006002 Built.Updates[Cnt] = Update.get();
6003 Built.Finals[Cnt] = Final.get();
6004 }
6005 }
6006
6007 if (HasErrors)
6008 return 0;
6009
6010 // Save results
6011 Built.IterationVarRef = IV.get();
6012 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006013 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006014 Built.CalcLastIteration = SemaRef
6015 .ActOnFinishFullExpr(CalcLastIteration.get(),
6016 /*DiscardedValue*/ false)
6017 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006018 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006019 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006020 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006021 Built.Init = Init.get();
6022 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006023 Built.LB = LB.get();
6024 Built.UB = UB.get();
6025 Built.IL = IL.get();
6026 Built.ST = ST.get();
6027 Built.EUB = EUB.get();
6028 Built.NLB = NextLB.get();
6029 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006030 Built.PrevLB = PrevLB.get();
6031 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006032 Built.DistInc = DistInc.get();
6033 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006034 Built.DistCombinedFields.LB = CombLB.get();
6035 Built.DistCombinedFields.UB = CombUB.get();
6036 Built.DistCombinedFields.EUB = CombEUB.get();
6037 Built.DistCombinedFields.Init = CombInit.get();
6038 Built.DistCombinedFields.Cond = CombCond.get();
6039 Built.DistCombinedFields.NLB = CombNextLB.get();
6040 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006041 Built.DistCombinedFields.DistCond = CombDistCond.get();
6042 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006043
Alexey Bataevabfc0692014-06-25 06:52:00 +00006044 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006045}
6046
Alexey Bataev10e775f2015-07-30 11:36:16 +00006047static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006048 auto CollapseClauses =
6049 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6050 if (CollapseClauses.begin() != CollapseClauses.end())
6051 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006052 return nullptr;
6053}
6054
Alexey Bataev10e775f2015-07-30 11:36:16 +00006055static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006056 auto OrderedClauses =
6057 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6058 if (OrderedClauses.begin() != OrderedClauses.end())
6059 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006060 return nullptr;
6061}
6062
Kelvin Lic5609492016-07-15 04:39:07 +00006063static bool checkSimdlenSafelenSpecified(Sema &S,
6064 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006065 const OMPSafelenClause *Safelen = nullptr;
6066 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006067
Alexey Bataeve3727102018-04-18 15:57:46 +00006068 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006069 if (Clause->getClauseKind() == OMPC_safelen)
6070 Safelen = cast<OMPSafelenClause>(Clause);
6071 else if (Clause->getClauseKind() == OMPC_simdlen)
6072 Simdlen = cast<OMPSimdlenClause>(Clause);
6073 if (Safelen && Simdlen)
6074 break;
6075 }
6076
6077 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006078 const Expr *SimdlenLength = Simdlen->getSimdlen();
6079 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006080 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6081 SimdlenLength->isInstantiationDependent() ||
6082 SimdlenLength->containsUnexpandedParameterPack())
6083 return false;
6084 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6085 SafelenLength->isInstantiationDependent() ||
6086 SafelenLength->containsUnexpandedParameterPack())
6087 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006088 Expr::EvalResult SimdlenResult, SafelenResult;
6089 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6090 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6091 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6092 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006093 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6094 // If both simdlen and safelen clauses are specified, the value of the
6095 // simdlen parameter must be less than or equal to the value of the safelen
6096 // parameter.
6097 if (SimdlenRes > SafelenRes) {
6098 S.Diag(SimdlenLength->getExprLoc(),
6099 diag::err_omp_wrong_simdlen_safelen_values)
6100 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6101 return true;
6102 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006103 }
6104 return false;
6105}
6106
Alexey Bataeve3727102018-04-18 15:57:46 +00006107StmtResult
6108Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6109 SourceLocation StartLoc, SourceLocation EndLoc,
6110 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006111 if (!AStmt)
6112 return StmtError();
6113
6114 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006115 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006116 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6117 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006118 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006119 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6120 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006121 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006122 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006123
Alexander Musmana5f070a2014-10-01 06:03:56 +00006124 assert((CurContext->isDependentContext() || B.builtAll()) &&
6125 "omp simd loop exprs were not built");
6126
Alexander Musman3276a272015-03-21 10:12:56 +00006127 if (!CurContext->isDependentContext()) {
6128 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006129 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006130 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006131 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006132 B.NumIterations, *this, CurScope,
6133 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006134 return StmtError();
6135 }
6136 }
6137
Kelvin Lic5609492016-07-15 04:39:07 +00006138 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006139 return StmtError();
6140
Reid Kleckner87a31802018-03-12 21:43:02 +00006141 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006142 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6143 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006144}
6145
Alexey Bataeve3727102018-04-18 15:57:46 +00006146StmtResult
6147Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6148 SourceLocation StartLoc, SourceLocation EndLoc,
6149 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006150 if (!AStmt)
6151 return StmtError();
6152
6153 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006154 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006155 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6156 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006157 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006158 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6159 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006160 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006161 return StmtError();
6162
Alexander Musmana5f070a2014-10-01 06:03:56 +00006163 assert((CurContext->isDependentContext() || B.builtAll()) &&
6164 "omp for loop exprs were not built");
6165
Alexey Bataev54acd402015-08-04 11:18:19 +00006166 if (!CurContext->isDependentContext()) {
6167 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006168 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006169 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006170 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006171 B.NumIterations, *this, CurScope,
6172 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006173 return StmtError();
6174 }
6175 }
6176
Reid Kleckner87a31802018-03-12 21:43:02 +00006177 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006178 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006179 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006180}
6181
Alexander Musmanf82886e2014-09-18 05:12:34 +00006182StmtResult Sema::ActOnOpenMPForSimdDirective(
6183 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006184 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006185 if (!AStmt)
6186 return StmtError();
6187
6188 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006189 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006190 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6191 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006192 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006193 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006194 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6195 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006196 if (NestedLoopCount == 0)
6197 return StmtError();
6198
Alexander Musmanc6388682014-12-15 07:07:06 +00006199 assert((CurContext->isDependentContext() || B.builtAll()) &&
6200 "omp for simd loop exprs were not built");
6201
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006202 if (!CurContext->isDependentContext()) {
6203 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006204 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006205 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006206 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006207 B.NumIterations, *this, CurScope,
6208 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006209 return StmtError();
6210 }
6211 }
6212
Kelvin Lic5609492016-07-15 04:39:07 +00006213 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006214 return StmtError();
6215
Reid Kleckner87a31802018-03-12 21:43:02 +00006216 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006217 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6218 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006219}
6220
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006221StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6222 Stmt *AStmt,
6223 SourceLocation StartLoc,
6224 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006225 if (!AStmt)
6226 return StmtError();
6227
6228 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006229 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006230 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006231 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006232 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006233 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006234 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006235 return StmtError();
6236 // All associated statements must be '#pragma omp section' except for
6237 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006238 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006239 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6240 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006241 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006242 diag::err_omp_sections_substmt_not_section);
6243 return StmtError();
6244 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006245 cast<OMPSectionDirective>(SectionStmt)
6246 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006247 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006248 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006249 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006250 return StmtError();
6251 }
6252
Reid Kleckner87a31802018-03-12 21:43:02 +00006253 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006254
Alexey Bataev25e5b442015-09-15 12:52:43 +00006255 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6256 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006257}
6258
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006259StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6260 SourceLocation StartLoc,
6261 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006262 if (!AStmt)
6263 return StmtError();
6264
6265 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006266
Reid Kleckner87a31802018-03-12 21:43:02 +00006267 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006268 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006269
Alexey Bataev25e5b442015-09-15 12:52:43 +00006270 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6271 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006272}
6273
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006274StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6275 Stmt *AStmt,
6276 SourceLocation StartLoc,
6277 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006278 if (!AStmt)
6279 return StmtError();
6280
6281 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006282
Reid Kleckner87a31802018-03-12 21:43:02 +00006283 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006284
Alexey Bataev3255bf32015-01-19 05:20:46 +00006285 // OpenMP [2.7.3, single Construct, Restrictions]
6286 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006287 const OMPClause *Nowait = nullptr;
6288 const OMPClause *Copyprivate = nullptr;
6289 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006290 if (Clause->getClauseKind() == OMPC_nowait)
6291 Nowait = Clause;
6292 else if (Clause->getClauseKind() == OMPC_copyprivate)
6293 Copyprivate = Clause;
6294 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006295 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006296 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006297 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006298 return StmtError();
6299 }
6300 }
6301
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006302 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6303}
6304
Alexander Musman80c22892014-07-17 08:54:58 +00006305StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6306 SourceLocation StartLoc,
6307 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006308 if (!AStmt)
6309 return StmtError();
6310
6311 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006312
Reid Kleckner87a31802018-03-12 21:43:02 +00006313 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006314
6315 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6316}
6317
Alexey Bataev28c75412015-12-15 08:19:24 +00006318StmtResult Sema::ActOnOpenMPCriticalDirective(
6319 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6320 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006321 if (!AStmt)
6322 return StmtError();
6323
6324 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006325
Alexey Bataev28c75412015-12-15 08:19:24 +00006326 bool ErrorFound = false;
6327 llvm::APSInt Hint;
6328 SourceLocation HintLoc;
6329 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006330 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006331 if (C->getClauseKind() == OMPC_hint) {
6332 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006333 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006334 ErrorFound = true;
6335 }
6336 Expr *E = cast<OMPHintClause>(C)->getHint();
6337 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006338 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006339 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006340 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006341 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006342 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006343 }
6344 }
6345 }
6346 if (ErrorFound)
6347 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006348 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006349 if (Pair.first && DirName.getName() && !DependentHint) {
6350 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6351 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006352 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006353 Diag(HintLoc, diag::note_omp_critical_hint_here)
6354 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006355 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006356 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006357 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006358 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006359 << 1
6360 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6361 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006362 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006363 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006364 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006365 }
6366 }
6367
Reid Kleckner87a31802018-03-12 21:43:02 +00006368 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006369
Alexey Bataev28c75412015-12-15 08:19:24 +00006370 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6371 Clauses, AStmt);
6372 if (!Pair.first && DirName.getName() && !DependentHint)
6373 DSAStack->addCriticalWithHint(Dir, Hint);
6374 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006375}
6376
Alexey Bataev4acb8592014-07-07 13:01:15 +00006377StmtResult Sema::ActOnOpenMPParallelForDirective(
6378 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006379 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006380 if (!AStmt)
6381 return StmtError();
6382
Alexey Bataeve3727102018-04-18 15:57:46 +00006383 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006384 // 1.2.2 OpenMP Language Terminology
6385 // Structured block - An executable statement with a single entry at the
6386 // top and a single exit at the bottom.
6387 // The point of exit cannot be a branch out of the structured block.
6388 // longjmp() and throw() must not violate the entry/exit criteria.
6389 CS->getCapturedDecl()->setNothrow();
6390
Alexander Musmanc6388682014-12-15 07:07:06 +00006391 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006392 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6393 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006394 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006395 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006396 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6397 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006398 if (NestedLoopCount == 0)
6399 return StmtError();
6400
Alexander Musmana5f070a2014-10-01 06:03:56 +00006401 assert((CurContext->isDependentContext() || B.builtAll()) &&
6402 "omp parallel for loop exprs were not built");
6403
Alexey Bataev54acd402015-08-04 11:18:19 +00006404 if (!CurContext->isDependentContext()) {
6405 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006406 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006407 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006408 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006409 B.NumIterations, *this, CurScope,
6410 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006411 return StmtError();
6412 }
6413 }
6414
Reid Kleckner87a31802018-03-12 21:43:02 +00006415 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006416 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006417 NestedLoopCount, Clauses, AStmt, B,
6418 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006419}
6420
Alexander Musmane4e893b2014-09-23 09:33:00 +00006421StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6422 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006423 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006424 if (!AStmt)
6425 return StmtError();
6426
Alexey Bataeve3727102018-04-18 15:57:46 +00006427 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006428 // 1.2.2 OpenMP Language Terminology
6429 // Structured block - An executable statement with a single entry at the
6430 // top and a single exit at the bottom.
6431 // The point of exit cannot be a branch out of the structured block.
6432 // longjmp() and throw() must not violate the entry/exit criteria.
6433 CS->getCapturedDecl()->setNothrow();
6434
Alexander Musmanc6388682014-12-15 07:07:06 +00006435 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006436 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6437 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006438 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006439 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006440 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6441 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006442 if (NestedLoopCount == 0)
6443 return StmtError();
6444
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006445 if (!CurContext->isDependentContext()) {
6446 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006447 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006448 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006449 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006450 B.NumIterations, *this, CurScope,
6451 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006452 return StmtError();
6453 }
6454 }
6455
Kelvin Lic5609492016-07-15 04:39:07 +00006456 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006457 return StmtError();
6458
Reid Kleckner87a31802018-03-12 21:43:02 +00006459 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006460 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006461 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006462}
6463
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006464StmtResult
6465Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6466 Stmt *AStmt, SourceLocation StartLoc,
6467 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006468 if (!AStmt)
6469 return StmtError();
6470
6471 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006472 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006473 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006474 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006475 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006476 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006477 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006478 return StmtError();
6479 // All associated statements must be '#pragma omp section' except for
6480 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006481 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006482 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6483 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006484 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006485 diag::err_omp_parallel_sections_substmt_not_section);
6486 return StmtError();
6487 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006488 cast<OMPSectionDirective>(SectionStmt)
6489 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006490 }
6491 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006492 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006493 diag::err_omp_parallel_sections_not_compound_stmt);
6494 return StmtError();
6495 }
6496
Reid Kleckner87a31802018-03-12 21:43:02 +00006497 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006498
Alexey Bataev25e5b442015-09-15 12:52:43 +00006499 return OMPParallelSectionsDirective::Create(
6500 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006501}
6502
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006503StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6504 Stmt *AStmt, SourceLocation StartLoc,
6505 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006506 if (!AStmt)
6507 return StmtError();
6508
David Majnemer9d168222016-08-05 17:44:54 +00006509 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006510 // 1.2.2 OpenMP Language Terminology
6511 // Structured block - An executable statement with a single entry at the
6512 // top and a single exit at the bottom.
6513 // The point of exit cannot be a branch out of the structured block.
6514 // longjmp() and throw() must not violate the entry/exit criteria.
6515 CS->getCapturedDecl()->setNothrow();
6516
Reid Kleckner87a31802018-03-12 21:43:02 +00006517 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006518
Alexey Bataev25e5b442015-09-15 12:52:43 +00006519 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6520 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006521}
6522
Alexey Bataev68446b72014-07-18 07:47:19 +00006523StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6524 SourceLocation EndLoc) {
6525 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6526}
6527
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006528StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6529 SourceLocation EndLoc) {
6530 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6531}
6532
Alexey Bataev2df347a2014-07-18 10:17:07 +00006533StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6534 SourceLocation EndLoc) {
6535 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6536}
6537
Alexey Bataev169d96a2017-07-18 20:17:46 +00006538StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6539 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006540 SourceLocation StartLoc,
6541 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006542 if (!AStmt)
6543 return StmtError();
6544
6545 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006546
Reid Kleckner87a31802018-03-12 21:43:02 +00006547 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006548
Alexey Bataev169d96a2017-07-18 20:17:46 +00006549 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006550 AStmt,
6551 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006552}
6553
Alexey Bataev6125da92014-07-21 11:26:11 +00006554StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6555 SourceLocation StartLoc,
6556 SourceLocation EndLoc) {
6557 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6558 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6559}
6560
Alexey Bataev346265e2015-09-25 10:37:12 +00006561StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6562 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006563 SourceLocation StartLoc,
6564 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006565 const OMPClause *DependFound = nullptr;
6566 const OMPClause *DependSourceClause = nullptr;
6567 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006568 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006569 const OMPThreadsClause *TC = nullptr;
6570 const OMPSIMDClause *SC = nullptr;
6571 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006572 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6573 DependFound = C;
6574 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6575 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006576 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006577 << getOpenMPDirectiveName(OMPD_ordered)
6578 << getOpenMPClauseName(OMPC_depend) << 2;
6579 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006580 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006581 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006582 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006583 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006584 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006585 << 0;
6586 ErrorFound = true;
6587 }
6588 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6589 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006590 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006591 << 1;
6592 ErrorFound = true;
6593 }
6594 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006595 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006596 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006597 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006598 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006599 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006600 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006601 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006602 if (!ErrorFound && !SC &&
6603 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006604 // OpenMP [2.8.1,simd Construct, Restrictions]
6605 // An ordered construct with the simd clause is the only OpenMP construct
6606 // that can appear in the simd region.
6607 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006608 ErrorFound = true;
6609 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006610 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006611 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6612 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006613 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006614 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006615 diag::err_omp_ordered_directive_without_param);
6616 ErrorFound = true;
6617 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006618 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006619 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006620 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6621 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006622 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006623 ErrorFound = true;
6624 }
6625 }
6626 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006627 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006628
6629 if (AStmt) {
6630 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6631
Reid Kleckner87a31802018-03-12 21:43:02 +00006632 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006633 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006634
6635 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006636}
6637
Alexey Bataev1d160b12015-03-13 12:27:31 +00006638namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006639/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006640/// construct.
6641class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006642 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006643 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006644 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006645 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006646 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006647 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006648 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006649 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006650 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006651 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006652 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006653 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006654 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006655 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006656 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006657 /// expression.
6658 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006659 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006660 /// part.
6661 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006662 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006663 NoError
6664 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006665 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006666 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006667 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006668 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006670 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006671 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006672 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006673 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006674 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6675 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6676 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006677 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006678 /// important for non-associative operations.
6679 bool IsXLHSInRHSPart;
6680 BinaryOperatorKind Op;
6681 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006682 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006683 /// if it is a prefix unary operation.
6684 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006685
6686public:
6687 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006688 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006689 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006690 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006691 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006692 /// expression. If DiagId and NoteId == 0, then only check is performed
6693 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006694 /// \param DiagId Diagnostic which should be emitted if error is found.
6695 /// \param NoteId Diagnostic note for the main error message.
6696 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006697 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006698 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006699 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006700 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006701 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006702 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006703 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6704 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6705 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006706 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006707 /// false otherwise.
6708 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6709
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006710 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006711 /// if it is a prefix unary operation.
6712 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6713
Alexey Bataev1d160b12015-03-13 12:27:31 +00006714private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006715 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6716 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006717};
6718} // namespace
6719
6720bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6721 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6722 ExprAnalysisErrorCode ErrorFound = NoError;
6723 SourceLocation ErrorLoc, NoteLoc;
6724 SourceRange ErrorRange, NoteRange;
6725 // Allowed constructs are:
6726 // x = x binop expr;
6727 // x = expr binop x;
6728 if (AtomicBinOp->getOpcode() == BO_Assign) {
6729 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006730 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006731 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6732 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6733 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6734 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006735 Op = AtomicInnerBinOp->getOpcode();
6736 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006737 Expr *LHS = AtomicInnerBinOp->getLHS();
6738 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006739 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6740 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6741 /*Canonical=*/true);
6742 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6743 /*Canonical=*/true);
6744 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6745 /*Canonical=*/true);
6746 if (XId == LHSId) {
6747 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006748 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006749 } else if (XId == RHSId) {
6750 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006751 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006752 } else {
6753 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6754 ErrorRange = AtomicInnerBinOp->getSourceRange();
6755 NoteLoc = X->getExprLoc();
6756 NoteRange = X->getSourceRange();
6757 ErrorFound = NotAnUpdateExpression;
6758 }
6759 } else {
6760 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6761 ErrorRange = AtomicInnerBinOp->getSourceRange();
6762 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6763 NoteRange = SourceRange(NoteLoc, NoteLoc);
6764 ErrorFound = NotABinaryOperator;
6765 }
6766 } else {
6767 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6768 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6769 ErrorFound = NotABinaryExpression;
6770 }
6771 } else {
6772 ErrorLoc = AtomicBinOp->getExprLoc();
6773 ErrorRange = AtomicBinOp->getSourceRange();
6774 NoteLoc = AtomicBinOp->getOperatorLoc();
6775 NoteRange = SourceRange(NoteLoc, NoteLoc);
6776 ErrorFound = NotAnAssignmentOp;
6777 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006778 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006779 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6780 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6781 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006782 }
6783 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006784 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006785 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006786}
6787
6788bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6789 unsigned NoteId) {
6790 ExprAnalysisErrorCode ErrorFound = NoError;
6791 SourceLocation ErrorLoc, NoteLoc;
6792 SourceRange ErrorRange, NoteRange;
6793 // Allowed constructs are:
6794 // x++;
6795 // x--;
6796 // ++x;
6797 // --x;
6798 // x binop= expr;
6799 // x = x binop expr;
6800 // x = expr binop x;
6801 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6802 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6803 if (AtomicBody->getType()->isScalarType() ||
6804 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006805 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006806 AtomicBody->IgnoreParenImpCasts())) {
6807 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006808 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006809 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006810 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006811 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006812 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006813 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006814 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6815 AtomicBody->IgnoreParenImpCasts())) {
6816 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006817 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006818 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006819 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006820 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006821 // Check for Unary Operation
6822 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006823 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006824 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6825 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006826 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006827 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6828 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006829 } else {
6830 ErrorFound = NotAnUnaryIncDecExpression;
6831 ErrorLoc = AtomicUnaryOp->getExprLoc();
6832 ErrorRange = AtomicUnaryOp->getSourceRange();
6833 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6834 NoteRange = SourceRange(NoteLoc, NoteLoc);
6835 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006836 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006837 ErrorFound = NotABinaryOrUnaryExpression;
6838 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6839 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6840 }
6841 } else {
6842 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006843 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006844 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6845 }
6846 } else {
6847 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006848 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006849 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6850 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006851 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006852 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6853 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6854 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006855 }
6856 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006857 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006858 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006859 // Build an update expression of form 'OpaqueValueExpr(x) binop
6860 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6861 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6862 auto *OVEX = new (SemaRef.getASTContext())
6863 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6864 auto *OVEExpr = new (SemaRef.getASTContext())
6865 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006866 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006867 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6868 IsXLHSInRHSPart ? OVEExpr : OVEX);
6869 if (Update.isInvalid())
6870 return true;
6871 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6872 Sema::AA_Casting);
6873 if (Update.isInvalid())
6874 return true;
6875 UpdateExpr = Update.get();
6876 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006877 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006878}
6879
Alexey Bataev0162e452014-07-22 10:10:35 +00006880StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6881 Stmt *AStmt,
6882 SourceLocation StartLoc,
6883 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006884 if (!AStmt)
6885 return StmtError();
6886
David Majnemer9d168222016-08-05 17:44:54 +00006887 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006888 // 1.2.2 OpenMP Language Terminology
6889 // Structured block - An executable statement with a single entry at the
6890 // top and a single exit at the bottom.
6891 // The point of exit cannot be a branch out of the structured block.
6892 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006893 OpenMPClauseKind AtomicKind = OMPC_unknown;
6894 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006895 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006896 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006897 C->getClauseKind() == OMPC_update ||
6898 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006899 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006900 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006901 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006902 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6903 << getOpenMPClauseName(AtomicKind);
6904 } else {
6905 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006906 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006907 }
6908 }
6909 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006910
Alexey Bataeve3727102018-04-18 15:57:46 +00006911 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006912 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6913 Body = EWC->getSubExpr();
6914
Alexey Bataev62cec442014-11-18 10:14:22 +00006915 Expr *X = nullptr;
6916 Expr *V = nullptr;
6917 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006918 Expr *UE = nullptr;
6919 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006920 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006921 // OpenMP [2.12.6, atomic Construct]
6922 // In the next expressions:
6923 // * x and v (as applicable) are both l-value expressions with scalar type.
6924 // * During the execution of an atomic region, multiple syntactic
6925 // occurrences of x must designate the same storage location.
6926 // * Neither of v and expr (as applicable) may access the storage location
6927 // designated by x.
6928 // * Neither of x and expr (as applicable) may access the storage location
6929 // designated by v.
6930 // * expr is an expression with scalar type.
6931 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6932 // * binop, binop=, ++, and -- are not overloaded operators.
6933 // * The expression x binop expr must be numerically equivalent to x binop
6934 // (expr). This requirement is satisfied if the operators in expr have
6935 // precedence greater than binop, or by using parentheses around expr or
6936 // subexpressions of expr.
6937 // * The expression expr binop x must be numerically equivalent to (expr)
6938 // binop x. This requirement is satisfied if the operators in expr have
6939 // precedence equal to or greater than binop, or by using parentheses around
6940 // expr or subexpressions of expr.
6941 // * For forms that allow multiple occurrences of x, the number of times
6942 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006943 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006944 enum {
6945 NotAnExpression,
6946 NotAnAssignmentOp,
6947 NotAScalarType,
6948 NotAnLValue,
6949 NoError
6950 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006951 SourceLocation ErrorLoc, NoteLoc;
6952 SourceRange ErrorRange, NoteRange;
6953 // If clause is read:
6954 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006955 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6956 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006957 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6958 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6959 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6960 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6961 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6962 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6963 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006964 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006965 ErrorFound = NotAnLValue;
6966 ErrorLoc = AtomicBinOp->getExprLoc();
6967 ErrorRange = AtomicBinOp->getSourceRange();
6968 NoteLoc = NotLValueExpr->getExprLoc();
6969 NoteRange = NotLValueExpr->getSourceRange();
6970 }
6971 } else if (!X->isInstantiationDependent() ||
6972 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006973 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006974 (X->isInstantiationDependent() || X->getType()->isScalarType())
6975 ? V
6976 : X;
6977 ErrorFound = NotAScalarType;
6978 ErrorLoc = AtomicBinOp->getExprLoc();
6979 ErrorRange = AtomicBinOp->getSourceRange();
6980 NoteLoc = NotScalarExpr->getExprLoc();
6981 NoteRange = NotScalarExpr->getSourceRange();
6982 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006983 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006984 ErrorFound = NotAnAssignmentOp;
6985 ErrorLoc = AtomicBody->getExprLoc();
6986 ErrorRange = AtomicBody->getSourceRange();
6987 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6988 : AtomicBody->getExprLoc();
6989 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6990 : AtomicBody->getSourceRange();
6991 }
6992 } else {
6993 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006994 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006995 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006996 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006997 if (ErrorFound != NoError) {
6998 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6999 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007000 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7001 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007002 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007003 }
7004 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007005 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007006 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007007 enum {
7008 NotAnExpression,
7009 NotAnAssignmentOp,
7010 NotAScalarType,
7011 NotAnLValue,
7012 NoError
7013 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007014 SourceLocation ErrorLoc, NoteLoc;
7015 SourceRange ErrorRange, NoteRange;
7016 // If clause is write:
7017 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007018 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7019 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007020 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7021 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007022 X = AtomicBinOp->getLHS();
7023 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007024 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7025 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7026 if (!X->isLValue()) {
7027 ErrorFound = NotAnLValue;
7028 ErrorLoc = AtomicBinOp->getExprLoc();
7029 ErrorRange = AtomicBinOp->getSourceRange();
7030 NoteLoc = X->getExprLoc();
7031 NoteRange = X->getSourceRange();
7032 }
7033 } else if (!X->isInstantiationDependent() ||
7034 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007035 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007036 (X->isInstantiationDependent() || X->getType()->isScalarType())
7037 ? E
7038 : X;
7039 ErrorFound = NotAScalarType;
7040 ErrorLoc = AtomicBinOp->getExprLoc();
7041 ErrorRange = AtomicBinOp->getSourceRange();
7042 NoteLoc = NotScalarExpr->getExprLoc();
7043 NoteRange = NotScalarExpr->getSourceRange();
7044 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007045 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007046 ErrorFound = NotAnAssignmentOp;
7047 ErrorLoc = AtomicBody->getExprLoc();
7048 ErrorRange = AtomicBody->getSourceRange();
7049 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7050 : AtomicBody->getExprLoc();
7051 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7052 : AtomicBody->getSourceRange();
7053 }
7054 } else {
7055 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007056 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007057 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007058 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007059 if (ErrorFound != NoError) {
7060 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7061 << ErrorRange;
7062 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7063 << NoteRange;
7064 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007065 }
7066 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007067 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007068 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007069 // If clause is update:
7070 // x++;
7071 // x--;
7072 // ++x;
7073 // --x;
7074 // x binop= expr;
7075 // x = x binop expr;
7076 // x = expr binop x;
7077 OpenMPAtomicUpdateChecker Checker(*this);
7078 if (Checker.checkStatement(
7079 Body, (AtomicKind == OMPC_update)
7080 ? diag::err_omp_atomic_update_not_expression_statement
7081 : diag::err_omp_atomic_not_expression_statement,
7082 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007083 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007084 if (!CurContext->isDependentContext()) {
7085 E = Checker.getExpr();
7086 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007087 UE = Checker.getUpdateExpr();
7088 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007089 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007090 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007091 enum {
7092 NotAnAssignmentOp,
7093 NotACompoundStatement,
7094 NotTwoSubstatements,
7095 NotASpecificExpression,
7096 NoError
7097 } ErrorFound = NoError;
7098 SourceLocation ErrorLoc, NoteLoc;
7099 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007100 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007101 // If clause is a capture:
7102 // v = x++;
7103 // v = x--;
7104 // v = ++x;
7105 // v = --x;
7106 // v = x binop= expr;
7107 // v = x = x binop expr;
7108 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007109 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007110 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7111 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7112 V = AtomicBinOp->getLHS();
7113 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7114 OpenMPAtomicUpdateChecker Checker(*this);
7115 if (Checker.checkStatement(
7116 Body, diag::err_omp_atomic_capture_not_expression_statement,
7117 diag::note_omp_atomic_update))
7118 return StmtError();
7119 E = Checker.getExpr();
7120 X = Checker.getX();
7121 UE = Checker.getUpdateExpr();
7122 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7123 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007124 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007125 ErrorLoc = AtomicBody->getExprLoc();
7126 ErrorRange = AtomicBody->getSourceRange();
7127 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7128 : AtomicBody->getExprLoc();
7129 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7130 : AtomicBody->getSourceRange();
7131 ErrorFound = NotAnAssignmentOp;
7132 }
7133 if (ErrorFound != NoError) {
7134 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7135 << ErrorRange;
7136 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7137 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007138 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007139 if (CurContext->isDependentContext())
7140 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007141 } else {
7142 // If clause is a capture:
7143 // { v = x; x = expr; }
7144 // { v = x; x++; }
7145 // { v = x; x--; }
7146 // { v = x; ++x; }
7147 // { v = x; --x; }
7148 // { v = x; x binop= expr; }
7149 // { v = x; x = x binop expr; }
7150 // { v = x; x = expr binop x; }
7151 // { x++; v = x; }
7152 // { x--; v = x; }
7153 // { ++x; v = x; }
7154 // { --x; v = x; }
7155 // { x binop= expr; v = x; }
7156 // { x = x binop expr; v = x; }
7157 // { x = expr binop x; v = x; }
7158 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7159 // Check that this is { expr1; expr2; }
7160 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007161 Stmt *First = CS->body_front();
7162 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007163 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7164 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7165 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7166 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7167 // Need to find what subexpression is 'v' and what is 'x'.
7168 OpenMPAtomicUpdateChecker Checker(*this);
7169 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7170 BinaryOperator *BinOp = nullptr;
7171 if (IsUpdateExprFound) {
7172 BinOp = dyn_cast<BinaryOperator>(First);
7173 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7174 }
7175 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7176 // { v = x; x++; }
7177 // { v = x; x--; }
7178 // { v = x; ++x; }
7179 // { v = x; --x; }
7180 // { v = x; x binop= expr; }
7181 // { v = x; x = x binop expr; }
7182 // { v = x; x = expr binop x; }
7183 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007184 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007185 llvm::FoldingSetNodeID XId, PossibleXId;
7186 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7187 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7188 IsUpdateExprFound = XId == PossibleXId;
7189 if (IsUpdateExprFound) {
7190 V = BinOp->getLHS();
7191 X = Checker.getX();
7192 E = Checker.getExpr();
7193 UE = Checker.getUpdateExpr();
7194 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007195 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007196 }
7197 }
7198 if (!IsUpdateExprFound) {
7199 IsUpdateExprFound = !Checker.checkStatement(First);
7200 BinOp = nullptr;
7201 if (IsUpdateExprFound) {
7202 BinOp = dyn_cast<BinaryOperator>(Second);
7203 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7204 }
7205 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7206 // { x++; v = x; }
7207 // { x--; v = x; }
7208 // { ++x; v = x; }
7209 // { --x; v = x; }
7210 // { x binop= expr; v = x; }
7211 // { x = x binop expr; v = x; }
7212 // { x = expr binop x; v = x; }
7213 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007214 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007215 llvm::FoldingSetNodeID XId, PossibleXId;
7216 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7217 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7218 IsUpdateExprFound = XId == PossibleXId;
7219 if (IsUpdateExprFound) {
7220 V = BinOp->getLHS();
7221 X = Checker.getX();
7222 E = Checker.getExpr();
7223 UE = Checker.getUpdateExpr();
7224 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007225 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007226 }
7227 }
7228 }
7229 if (!IsUpdateExprFound) {
7230 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007231 auto *FirstExpr = dyn_cast<Expr>(First);
7232 auto *SecondExpr = dyn_cast<Expr>(Second);
7233 if (!FirstExpr || !SecondExpr ||
7234 !(FirstExpr->isInstantiationDependent() ||
7235 SecondExpr->isInstantiationDependent())) {
7236 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7237 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007238 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007239 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007240 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007241 NoteRange = ErrorRange = FirstBinOp
7242 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007243 : SourceRange(ErrorLoc, ErrorLoc);
7244 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007245 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7246 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7247 ErrorFound = NotAnAssignmentOp;
7248 NoteLoc = ErrorLoc = SecondBinOp
7249 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007250 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007251 NoteRange = ErrorRange =
7252 SecondBinOp ? SecondBinOp->getSourceRange()
7253 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007254 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007255 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007256 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007257 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007258 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7259 llvm::FoldingSetNodeID X1Id, X2Id;
7260 PossibleXRHSInFirst->Profile(X1Id, Context,
7261 /*Canonical=*/true);
7262 PossibleXLHSInSecond->Profile(X2Id, Context,
7263 /*Canonical=*/true);
7264 IsUpdateExprFound = X1Id == X2Id;
7265 if (IsUpdateExprFound) {
7266 V = FirstBinOp->getLHS();
7267 X = SecondBinOp->getLHS();
7268 E = SecondBinOp->getRHS();
7269 UE = nullptr;
7270 IsXLHSInRHSPart = false;
7271 IsPostfixUpdate = true;
7272 } else {
7273 ErrorFound = NotASpecificExpression;
7274 ErrorLoc = FirstBinOp->getExprLoc();
7275 ErrorRange = FirstBinOp->getSourceRange();
7276 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7277 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7278 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007279 }
7280 }
7281 }
7282 }
7283 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007284 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007285 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007286 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007287 ErrorFound = NotTwoSubstatements;
7288 }
7289 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007290 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007291 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007292 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007293 ErrorFound = NotACompoundStatement;
7294 }
7295 if (ErrorFound != NoError) {
7296 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7297 << ErrorRange;
7298 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7299 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007300 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007301 if (CurContext->isDependentContext())
7302 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007303 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007304 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007305
Reid Kleckner87a31802018-03-12 21:43:02 +00007306 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007307
Alexey Bataev62cec442014-11-18 10:14:22 +00007308 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007309 X, V, E, UE, IsXLHSInRHSPart,
7310 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007311}
7312
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007313StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7314 Stmt *AStmt,
7315 SourceLocation StartLoc,
7316 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007317 if (!AStmt)
7318 return StmtError();
7319
Alexey Bataeve3727102018-04-18 15:57:46 +00007320 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007321 // 1.2.2 OpenMP Language Terminology
7322 // Structured block - An executable statement with a single entry at the
7323 // top and a single exit at the bottom.
7324 // The point of exit cannot be a branch out of the structured block.
7325 // longjmp() and throw() must not violate the entry/exit criteria.
7326 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007327 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7328 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7329 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7330 // 1.2.2 OpenMP Language Terminology
7331 // Structured block - An executable statement with a single entry at the
7332 // top and a single exit at the bottom.
7333 // The point of exit cannot be a branch out of the structured block.
7334 // longjmp() and throw() must not violate the entry/exit criteria.
7335 CS->getCapturedDecl()->setNothrow();
7336 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007337
Alexey Bataev13314bf2014-10-09 04:18:56 +00007338 // OpenMP [2.16, Nesting of Regions]
7339 // If specified, a teams construct must be contained within a target
7340 // construct. That target construct must contain no statements or directives
7341 // outside of the teams construct.
7342 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007343 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007344 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007345 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007346 auto I = CS->body_begin();
7347 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007348 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007349 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7350 OMPTeamsFound) {
7351
Alexey Bataev13314bf2014-10-09 04:18:56 +00007352 OMPTeamsFound = false;
7353 break;
7354 }
7355 ++I;
7356 }
7357 assert(I != CS->body_end() && "Not found statement");
7358 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007359 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007360 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007361 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007362 }
7363 if (!OMPTeamsFound) {
7364 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7365 Diag(DSAStack->getInnerTeamsRegionLoc(),
7366 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007367 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007368 << isa<OMPExecutableDirective>(S);
7369 return StmtError();
7370 }
7371 }
7372
Reid Kleckner87a31802018-03-12 21:43:02 +00007373 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007374
7375 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7376}
7377
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007378StmtResult
7379Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7380 Stmt *AStmt, SourceLocation StartLoc,
7381 SourceLocation EndLoc) {
7382 if (!AStmt)
7383 return StmtError();
7384
Alexey Bataeve3727102018-04-18 15:57:46 +00007385 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007386 // 1.2.2 OpenMP Language Terminology
7387 // Structured block - An executable statement with a single entry at the
7388 // top and a single exit at the bottom.
7389 // The point of exit cannot be a branch out of the structured block.
7390 // longjmp() and throw() must not violate the entry/exit criteria.
7391 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007392 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7393 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7394 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7395 // 1.2.2 OpenMP Language Terminology
7396 // Structured block - An executable statement with a single entry at the
7397 // top and a single exit at the bottom.
7398 // The point of exit cannot be a branch out of the structured block.
7399 // longjmp() and throw() must not violate the entry/exit criteria.
7400 CS->getCapturedDecl()->setNothrow();
7401 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007402
Reid Kleckner87a31802018-03-12 21:43:02 +00007403 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007404
7405 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7406 AStmt);
7407}
7408
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007409StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007411 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007412 if (!AStmt)
7413 return StmtError();
7414
Alexey Bataeve3727102018-04-18 15:57:46 +00007415 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007416 // 1.2.2 OpenMP Language Terminology
7417 // Structured block - An executable statement with a single entry at the
7418 // top and a single exit at the bottom.
7419 // The point of exit cannot be a branch out of the structured block.
7420 // longjmp() and throw() must not violate the entry/exit criteria.
7421 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007422 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7423 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7424 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7425 // 1.2.2 OpenMP Language Terminology
7426 // Structured block - An executable statement with a single entry at the
7427 // top and a single exit at the bottom.
7428 // The point of exit cannot be a branch out of the structured block.
7429 // longjmp() and throw() must not violate the entry/exit criteria.
7430 CS->getCapturedDecl()->setNothrow();
7431 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007432
7433 OMPLoopDirective::HelperExprs B;
7434 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7435 // define the nested loops number.
7436 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007437 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007438 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007439 VarsWithImplicitDSA, B);
7440 if (NestedLoopCount == 0)
7441 return StmtError();
7442
7443 assert((CurContext->isDependentContext() || B.builtAll()) &&
7444 "omp target parallel for loop exprs were not built");
7445
7446 if (!CurContext->isDependentContext()) {
7447 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007448 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007449 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007450 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007451 B.NumIterations, *this, CurScope,
7452 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007453 return StmtError();
7454 }
7455 }
7456
Reid Kleckner87a31802018-03-12 21:43:02 +00007457 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007458 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7459 NestedLoopCount, Clauses, AStmt,
7460 B, DSAStack->isCancelRegion());
7461}
7462
Alexey Bataev95b64a92017-05-30 16:00:04 +00007463/// Check for existence of a map clause in the list of clauses.
7464static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7465 const OpenMPClauseKind K) {
7466 return llvm::any_of(
7467 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7468}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007469
Alexey Bataev95b64a92017-05-30 16:00:04 +00007470template <typename... Params>
7471static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7472 const Params... ClauseTypes) {
7473 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007474}
7475
Michael Wong65f367f2015-07-21 13:44:28 +00007476StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7477 Stmt *AStmt,
7478 SourceLocation StartLoc,
7479 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007480 if (!AStmt)
7481 return StmtError();
7482
7483 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7484
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007485 // OpenMP [2.10.1, Restrictions, p. 97]
7486 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007487 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7488 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7489 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007490 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007491 return StmtError();
7492 }
7493
Reid Kleckner87a31802018-03-12 21:43:02 +00007494 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007495
7496 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7497 AStmt);
7498}
7499
Samuel Antaodf67fc42016-01-19 19:15:56 +00007500StmtResult
7501Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7502 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007503 SourceLocation EndLoc, Stmt *AStmt) {
7504 if (!AStmt)
7505 return StmtError();
7506
Alexey Bataeve3727102018-04-18 15:57:46 +00007507 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007508 // 1.2.2 OpenMP Language Terminology
7509 // Structured block - An executable statement with a single entry at the
7510 // top and a single exit at the bottom.
7511 // The point of exit cannot be a branch out of the structured block.
7512 // longjmp() and throw() must not violate the entry/exit criteria.
7513 CS->getCapturedDecl()->setNothrow();
7514 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7515 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7516 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7517 // 1.2.2 OpenMP Language Terminology
7518 // Structured block - An executable statement with a single entry at the
7519 // top and a single exit at the bottom.
7520 // The point of exit cannot be a branch out of the structured block.
7521 // longjmp() and throw() must not violate the entry/exit criteria.
7522 CS->getCapturedDecl()->setNothrow();
7523 }
7524
Samuel Antaodf67fc42016-01-19 19:15:56 +00007525 // OpenMP [2.10.2, Restrictions, p. 99]
7526 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007527 if (!hasClauses(Clauses, OMPC_map)) {
7528 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7529 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007530 return StmtError();
7531 }
7532
Alexey Bataev7828b252017-11-21 17:08:48 +00007533 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7534 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007535}
7536
Samuel Antao72590762016-01-19 20:04:50 +00007537StmtResult
7538Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7539 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007540 SourceLocation EndLoc, Stmt *AStmt) {
7541 if (!AStmt)
7542 return StmtError();
7543
Alexey Bataeve3727102018-04-18 15:57:46 +00007544 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007545 // 1.2.2 OpenMP Language Terminology
7546 // Structured block - An executable statement with a single entry at the
7547 // top and a single exit at the bottom.
7548 // The point of exit cannot be a branch out of the structured block.
7549 // longjmp() and throw() must not violate the entry/exit criteria.
7550 CS->getCapturedDecl()->setNothrow();
7551 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7552 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7553 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7554 // 1.2.2 OpenMP Language Terminology
7555 // Structured block - An executable statement with a single entry at the
7556 // top and a single exit at the bottom.
7557 // The point of exit cannot be a branch out of the structured block.
7558 // longjmp() and throw() must not violate the entry/exit criteria.
7559 CS->getCapturedDecl()->setNothrow();
7560 }
7561
Samuel Antao72590762016-01-19 20:04:50 +00007562 // OpenMP [2.10.3, Restrictions, p. 102]
7563 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007564 if (!hasClauses(Clauses, OMPC_map)) {
7565 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7566 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007567 return StmtError();
7568 }
7569
Alexey Bataev7828b252017-11-21 17:08:48 +00007570 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7571 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007572}
7573
Samuel Antao686c70c2016-05-26 17:30:50 +00007574StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7575 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007576 SourceLocation EndLoc,
7577 Stmt *AStmt) {
7578 if (!AStmt)
7579 return StmtError();
7580
Alexey Bataeve3727102018-04-18 15:57:46 +00007581 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007582 // 1.2.2 OpenMP Language Terminology
7583 // Structured block - An executable statement with a single entry at the
7584 // top and a single exit at the bottom.
7585 // The point of exit cannot be a branch out of the structured block.
7586 // longjmp() and throw() must not violate the entry/exit criteria.
7587 CS->getCapturedDecl()->setNothrow();
7588 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7589 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7590 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7591 // 1.2.2 OpenMP Language Terminology
7592 // Structured block - An executable statement with a single entry at the
7593 // top and a single exit at the bottom.
7594 // The point of exit cannot be a branch out of the structured block.
7595 // longjmp() and throw() must not violate the entry/exit criteria.
7596 CS->getCapturedDecl()->setNothrow();
7597 }
7598
Alexey Bataev95b64a92017-05-30 16:00:04 +00007599 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007600 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7601 return StmtError();
7602 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007603 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7604 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007605}
7606
Alexey Bataev13314bf2014-10-09 04:18:56 +00007607StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7608 Stmt *AStmt, SourceLocation StartLoc,
7609 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007610 if (!AStmt)
7611 return StmtError();
7612
Alexey Bataeve3727102018-04-18 15:57:46 +00007613 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007614 // 1.2.2 OpenMP Language Terminology
7615 // Structured block - An executable statement with a single entry at the
7616 // top and a single exit at the bottom.
7617 // The point of exit cannot be a branch out of the structured block.
7618 // longjmp() and throw() must not violate the entry/exit criteria.
7619 CS->getCapturedDecl()->setNothrow();
7620
Reid Kleckner87a31802018-03-12 21:43:02 +00007621 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007622
Alexey Bataevceabd412017-11-30 18:01:54 +00007623 DSAStack->setParentTeamsRegionLoc(StartLoc);
7624
Alexey Bataev13314bf2014-10-09 04:18:56 +00007625 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7626}
7627
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007628StmtResult
7629Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7630 SourceLocation EndLoc,
7631 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007632 if (DSAStack->isParentNowaitRegion()) {
7633 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7634 return StmtError();
7635 }
7636 if (DSAStack->isParentOrderedRegion()) {
7637 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7638 return StmtError();
7639 }
7640 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7641 CancelRegion);
7642}
7643
Alexey Bataev87933c72015-09-18 08:07:34 +00007644StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7645 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007646 SourceLocation EndLoc,
7647 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007648 if (DSAStack->isParentNowaitRegion()) {
7649 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7650 return StmtError();
7651 }
7652 if (DSAStack->isParentOrderedRegion()) {
7653 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7654 return StmtError();
7655 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007656 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007657 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7658 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007659}
7660
Alexey Bataev382967a2015-12-08 12:06:20 +00007661static bool checkGrainsizeNumTasksClauses(Sema &S,
7662 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007663 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007664 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007665 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007666 if (C->getClauseKind() == OMPC_grainsize ||
7667 C->getClauseKind() == OMPC_num_tasks) {
7668 if (!PrevClause)
7669 PrevClause = C;
7670 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007671 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007672 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7673 << getOpenMPClauseName(C->getClauseKind())
7674 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007675 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007676 diag::note_omp_previous_grainsize_num_tasks)
7677 << getOpenMPClauseName(PrevClause->getClauseKind());
7678 ErrorFound = true;
7679 }
7680 }
7681 }
7682 return ErrorFound;
7683}
7684
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007685static bool checkReductionClauseWithNogroup(Sema &S,
7686 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007687 const OMPClause *ReductionClause = nullptr;
7688 const OMPClause *NogroupClause = nullptr;
7689 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007690 if (C->getClauseKind() == OMPC_reduction) {
7691 ReductionClause = C;
7692 if (NogroupClause)
7693 break;
7694 continue;
7695 }
7696 if (C->getClauseKind() == OMPC_nogroup) {
7697 NogroupClause = C;
7698 if (ReductionClause)
7699 break;
7700 continue;
7701 }
7702 }
7703 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007704 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7705 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007706 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007707 return true;
7708 }
7709 return false;
7710}
7711
Alexey Bataev49f6e782015-12-01 04:18:41 +00007712StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7713 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007714 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007715 if (!AStmt)
7716 return StmtError();
7717
7718 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7719 OMPLoopDirective::HelperExprs B;
7720 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7721 // define the nested loops number.
7722 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007723 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007724 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007725 VarsWithImplicitDSA, B);
7726 if (NestedLoopCount == 0)
7727 return StmtError();
7728
7729 assert((CurContext->isDependentContext() || B.builtAll()) &&
7730 "omp for loop exprs were not built");
7731
Alexey Bataev382967a2015-12-08 12:06:20 +00007732 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7733 // The grainsize clause and num_tasks clause are mutually exclusive and may
7734 // not appear on the same taskloop directive.
7735 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7736 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007737 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7738 // If a reduction clause is present on the taskloop directive, the nogroup
7739 // clause must not be specified.
7740 if (checkReductionClauseWithNogroup(*this, Clauses))
7741 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007742
Reid Kleckner87a31802018-03-12 21:43:02 +00007743 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007744 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7745 NestedLoopCount, Clauses, AStmt, B);
7746}
7747
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007748StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7749 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007750 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007751 if (!AStmt)
7752 return StmtError();
7753
7754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7755 OMPLoopDirective::HelperExprs B;
7756 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7757 // define the nested loops number.
7758 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007759 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007760 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7761 VarsWithImplicitDSA, B);
7762 if (NestedLoopCount == 0)
7763 return StmtError();
7764
7765 assert((CurContext->isDependentContext() || B.builtAll()) &&
7766 "omp for loop exprs were not built");
7767
Alexey Bataev5a3af132016-03-29 08:58:54 +00007768 if (!CurContext->isDependentContext()) {
7769 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007770 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007771 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007772 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007773 B.NumIterations, *this, CurScope,
7774 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007775 return StmtError();
7776 }
7777 }
7778
Alexey Bataev382967a2015-12-08 12:06:20 +00007779 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7780 // The grainsize clause and num_tasks clause are mutually exclusive and may
7781 // not appear on the same taskloop directive.
7782 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7783 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007784 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7785 // If a reduction clause is present on the taskloop directive, the nogroup
7786 // clause must not be specified.
7787 if (checkReductionClauseWithNogroup(*this, Clauses))
7788 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007789 if (checkSimdlenSafelenSpecified(*this, Clauses))
7790 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007791
Reid Kleckner87a31802018-03-12 21:43:02 +00007792 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007793 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7794 NestedLoopCount, Clauses, AStmt, B);
7795}
7796
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007797StmtResult Sema::ActOnOpenMPDistributeDirective(
7798 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007799 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007800 if (!AStmt)
7801 return StmtError();
7802
7803 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7804 OMPLoopDirective::HelperExprs B;
7805 // In presence of clause 'collapse' with number of loops, it will
7806 // define the nested loops number.
7807 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007808 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007809 nullptr /*ordered not a clause on distribute*/, AStmt,
7810 *this, *DSAStack, VarsWithImplicitDSA, B);
7811 if (NestedLoopCount == 0)
7812 return StmtError();
7813
7814 assert((CurContext->isDependentContext() || B.builtAll()) &&
7815 "omp for loop exprs were not built");
7816
Reid Kleckner87a31802018-03-12 21:43:02 +00007817 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007818 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7819 NestedLoopCount, Clauses, AStmt, B);
7820}
7821
Carlo Bertolli9925f152016-06-27 14:55:37 +00007822StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7823 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007824 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007825 if (!AStmt)
7826 return StmtError();
7827
Alexey Bataeve3727102018-04-18 15:57:46 +00007828 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007829 // 1.2.2 OpenMP Language Terminology
7830 // Structured block - An executable statement with a single entry at the
7831 // top and a single exit at the bottom.
7832 // The point of exit cannot be a branch out of the structured block.
7833 // longjmp() and throw() must not violate the entry/exit criteria.
7834 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007835 for (int ThisCaptureLevel =
7836 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7837 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7838 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7839 // 1.2.2 OpenMP Language Terminology
7840 // Structured block - An executable statement with a single entry at the
7841 // top and a single exit at the bottom.
7842 // The point of exit cannot be a branch out of the structured block.
7843 // longjmp() and throw() must not violate the entry/exit criteria.
7844 CS->getCapturedDecl()->setNothrow();
7845 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007846
7847 OMPLoopDirective::HelperExprs B;
7848 // In presence of clause 'collapse' with number of loops, it will
7849 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007850 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007851 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007852 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007853 VarsWithImplicitDSA, B);
7854 if (NestedLoopCount == 0)
7855 return StmtError();
7856
7857 assert((CurContext->isDependentContext() || B.builtAll()) &&
7858 "omp for loop exprs were not built");
7859
Reid Kleckner87a31802018-03-12 21:43:02 +00007860 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007861 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007862 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7863 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007864}
7865
Kelvin Li4a39add2016-07-05 05:00:15 +00007866StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7867 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007868 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007869 if (!AStmt)
7870 return StmtError();
7871
Alexey Bataeve3727102018-04-18 15:57:46 +00007872 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007873 // 1.2.2 OpenMP Language Terminology
7874 // Structured block - An executable statement with a single entry at the
7875 // top and a single exit at the bottom.
7876 // The point of exit cannot be a branch out of the structured block.
7877 // longjmp() and throw() must not violate the entry/exit criteria.
7878 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007879 for (int ThisCaptureLevel =
7880 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7881 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7882 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7883 // 1.2.2 OpenMP Language Terminology
7884 // Structured block - An executable statement with a single entry at the
7885 // top and a single exit at the bottom.
7886 // The point of exit cannot be a branch out of the structured block.
7887 // longjmp() and throw() must not violate the entry/exit criteria.
7888 CS->getCapturedDecl()->setNothrow();
7889 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007890
7891 OMPLoopDirective::HelperExprs B;
7892 // In presence of clause 'collapse' with number of loops, it will
7893 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007894 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007895 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007896 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007897 VarsWithImplicitDSA, B);
7898 if (NestedLoopCount == 0)
7899 return StmtError();
7900
7901 assert((CurContext->isDependentContext() || B.builtAll()) &&
7902 "omp for loop exprs were not built");
7903
Alexey Bataev438388c2017-11-22 18:34:02 +00007904 if (!CurContext->isDependentContext()) {
7905 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007906 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007907 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7908 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7909 B.NumIterations, *this, CurScope,
7910 DSAStack))
7911 return StmtError();
7912 }
7913 }
7914
Kelvin Lic5609492016-07-15 04:39:07 +00007915 if (checkSimdlenSafelenSpecified(*this, Clauses))
7916 return StmtError();
7917
Reid Kleckner87a31802018-03-12 21:43:02 +00007918 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007919 return OMPDistributeParallelForSimdDirective::Create(
7920 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7921}
7922
Kelvin Li787f3fc2016-07-06 04:45:38 +00007923StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7924 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007925 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007926 if (!AStmt)
7927 return StmtError();
7928
Alexey Bataeve3727102018-04-18 15:57:46 +00007929 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007930 // 1.2.2 OpenMP Language Terminology
7931 // Structured block - An executable statement with a single entry at the
7932 // top and a single exit at the bottom.
7933 // The point of exit cannot be a branch out of the structured block.
7934 // longjmp() and throw() must not violate the entry/exit criteria.
7935 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007936 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7937 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7938 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7939 // 1.2.2 OpenMP Language Terminology
7940 // Structured block - An executable statement with a single entry at the
7941 // top and a single exit at the bottom.
7942 // The point of exit cannot be a branch out of the structured block.
7943 // longjmp() and throw() must not violate the entry/exit criteria.
7944 CS->getCapturedDecl()->setNothrow();
7945 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007946
7947 OMPLoopDirective::HelperExprs B;
7948 // In presence of clause 'collapse' with number of loops, it will
7949 // define the nested loops number.
7950 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007951 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007952 nullptr /*ordered not a clause on distribute*/, CS, *this,
7953 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007954 if (NestedLoopCount == 0)
7955 return StmtError();
7956
7957 assert((CurContext->isDependentContext() || B.builtAll()) &&
7958 "omp for loop exprs were not built");
7959
Alexey Bataev438388c2017-11-22 18:34:02 +00007960 if (!CurContext->isDependentContext()) {
7961 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007962 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007963 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7964 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7965 B.NumIterations, *this, CurScope,
7966 DSAStack))
7967 return StmtError();
7968 }
7969 }
7970
Kelvin Lic5609492016-07-15 04:39:07 +00007971 if (checkSimdlenSafelenSpecified(*this, Clauses))
7972 return StmtError();
7973
Reid Kleckner87a31802018-03-12 21:43:02 +00007974 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007975 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7976 NestedLoopCount, Clauses, AStmt, B);
7977}
7978
Kelvin Lia579b912016-07-14 02:54:56 +00007979StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7980 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007982 if (!AStmt)
7983 return StmtError();
7984
Alexey Bataeve3727102018-04-18 15:57:46 +00007985 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007986 // 1.2.2 OpenMP Language Terminology
7987 // Structured block - An executable statement with a single entry at the
7988 // top and a single exit at the bottom.
7989 // The point of exit cannot be a branch out of the structured block.
7990 // longjmp() and throw() must not violate the entry/exit criteria.
7991 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007992 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7993 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7994 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7995 // 1.2.2 OpenMP Language Terminology
7996 // Structured block - An executable statement with a single entry at the
7997 // top and a single exit at the bottom.
7998 // The point of exit cannot be a branch out of the structured block.
7999 // longjmp() and throw() must not violate the entry/exit criteria.
8000 CS->getCapturedDecl()->setNothrow();
8001 }
Kelvin Lia579b912016-07-14 02:54:56 +00008002
8003 OMPLoopDirective::HelperExprs B;
8004 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8005 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008006 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008007 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008008 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008009 VarsWithImplicitDSA, B);
8010 if (NestedLoopCount == 0)
8011 return StmtError();
8012
8013 assert((CurContext->isDependentContext() || B.builtAll()) &&
8014 "omp target parallel for simd loop exprs were not built");
8015
8016 if (!CurContext->isDependentContext()) {
8017 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008018 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008019 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008020 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8021 B.NumIterations, *this, CurScope,
8022 DSAStack))
8023 return StmtError();
8024 }
8025 }
Kelvin Lic5609492016-07-15 04:39:07 +00008026 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008027 return StmtError();
8028
Reid Kleckner87a31802018-03-12 21:43:02 +00008029 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008030 return OMPTargetParallelForSimdDirective::Create(
8031 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8032}
8033
Kelvin Li986330c2016-07-20 22:57:10 +00008034StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8035 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008036 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008037 if (!AStmt)
8038 return StmtError();
8039
Alexey Bataeve3727102018-04-18 15:57:46 +00008040 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008041 // 1.2.2 OpenMP Language Terminology
8042 // Structured block - An executable statement with a single entry at the
8043 // top and a single exit at the bottom.
8044 // The point of exit cannot be a branch out of the structured block.
8045 // longjmp() and throw() must not violate the entry/exit criteria.
8046 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008047 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8048 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8049 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8050 // 1.2.2 OpenMP Language Terminology
8051 // Structured block - An executable statement with a single entry at the
8052 // top and a single exit at the bottom.
8053 // The point of exit cannot be a branch out of the structured block.
8054 // longjmp() and throw() must not violate the entry/exit criteria.
8055 CS->getCapturedDecl()->setNothrow();
8056 }
8057
Kelvin Li986330c2016-07-20 22:57:10 +00008058 OMPLoopDirective::HelperExprs B;
8059 // In presence of clause 'collapse' with number of loops, it will define the
8060 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008061 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008062 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008063 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008064 VarsWithImplicitDSA, B);
8065 if (NestedLoopCount == 0)
8066 return StmtError();
8067
8068 assert((CurContext->isDependentContext() || B.builtAll()) &&
8069 "omp target simd loop exprs were not built");
8070
8071 if (!CurContext->isDependentContext()) {
8072 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008073 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008074 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008075 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8076 B.NumIterations, *this, CurScope,
8077 DSAStack))
8078 return StmtError();
8079 }
8080 }
8081
8082 if (checkSimdlenSafelenSpecified(*this, Clauses))
8083 return StmtError();
8084
Reid Kleckner87a31802018-03-12 21:43:02 +00008085 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008086 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8087 NestedLoopCount, Clauses, AStmt, B);
8088}
8089
Kelvin Li02532872016-08-05 14:37:37 +00008090StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8091 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008092 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008093 if (!AStmt)
8094 return StmtError();
8095
Alexey Bataeve3727102018-04-18 15:57:46 +00008096 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008097 // 1.2.2 OpenMP Language Terminology
8098 // Structured block - An executable statement with a single entry at the
8099 // top and a single exit at the bottom.
8100 // The point of exit cannot be a branch out of the structured block.
8101 // longjmp() and throw() must not violate the entry/exit criteria.
8102 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008103 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8104 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8105 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8106 // 1.2.2 OpenMP Language Terminology
8107 // Structured block - An executable statement with a single entry at the
8108 // top and a single exit at the bottom.
8109 // The point of exit cannot be a branch out of the structured block.
8110 // longjmp() and throw() must not violate the entry/exit criteria.
8111 CS->getCapturedDecl()->setNothrow();
8112 }
Kelvin Li02532872016-08-05 14:37:37 +00008113
8114 OMPLoopDirective::HelperExprs B;
8115 // In presence of clause 'collapse' with number of loops, it will
8116 // define the nested loops number.
8117 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008118 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008119 nullptr /*ordered not a clause on distribute*/, CS, *this,
8120 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008121 if (NestedLoopCount == 0)
8122 return StmtError();
8123
8124 assert((CurContext->isDependentContext() || B.builtAll()) &&
8125 "omp teams distribute loop exprs were not built");
8126
Reid Kleckner87a31802018-03-12 21:43:02 +00008127 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008128
8129 DSAStack->setParentTeamsRegionLoc(StartLoc);
8130
David Majnemer9d168222016-08-05 17:44:54 +00008131 return OMPTeamsDistributeDirective::Create(
8132 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008133}
8134
Kelvin Li4e325f72016-10-25 12:50:55 +00008135StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8136 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008137 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008138 if (!AStmt)
8139 return StmtError();
8140
Alexey Bataeve3727102018-04-18 15:57:46 +00008141 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008142 // 1.2.2 OpenMP Language Terminology
8143 // Structured block - An executable statement with a single entry at the
8144 // top and a single exit at the bottom.
8145 // The point of exit cannot be a branch out of the structured block.
8146 // longjmp() and throw() must not violate the entry/exit criteria.
8147 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008148 for (int ThisCaptureLevel =
8149 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8150 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8151 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8152 // 1.2.2 OpenMP Language Terminology
8153 // Structured block - An executable statement with a single entry at the
8154 // top and a single exit at the bottom.
8155 // The point of exit cannot be a branch out of the structured block.
8156 // longjmp() and throw() must not violate the entry/exit criteria.
8157 CS->getCapturedDecl()->setNothrow();
8158 }
8159
Kelvin Li4e325f72016-10-25 12:50:55 +00008160
8161 OMPLoopDirective::HelperExprs B;
8162 // In presence of clause 'collapse' with number of loops, it will
8163 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008164 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008165 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008166 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008167 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008168
8169 if (NestedLoopCount == 0)
8170 return StmtError();
8171
8172 assert((CurContext->isDependentContext() || B.builtAll()) &&
8173 "omp teams distribute simd loop exprs were not built");
8174
8175 if (!CurContext->isDependentContext()) {
8176 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008177 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008178 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8179 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8180 B.NumIterations, *this, CurScope,
8181 DSAStack))
8182 return StmtError();
8183 }
8184 }
8185
8186 if (checkSimdlenSafelenSpecified(*this, Clauses))
8187 return StmtError();
8188
Reid Kleckner87a31802018-03-12 21:43:02 +00008189 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008190
8191 DSAStack->setParentTeamsRegionLoc(StartLoc);
8192
Kelvin Li4e325f72016-10-25 12:50:55 +00008193 return OMPTeamsDistributeSimdDirective::Create(
8194 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8195}
8196
Kelvin Li579e41c2016-11-30 23:51:03 +00008197StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8198 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008199 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008200 if (!AStmt)
8201 return StmtError();
8202
Alexey Bataeve3727102018-04-18 15:57:46 +00008203 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008204 // 1.2.2 OpenMP Language Terminology
8205 // Structured block - An executable statement with a single entry at the
8206 // top and a single exit at the bottom.
8207 // The point of exit cannot be a branch out of the structured block.
8208 // longjmp() and throw() must not violate the entry/exit criteria.
8209 CS->getCapturedDecl()->setNothrow();
8210
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008211 for (int ThisCaptureLevel =
8212 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8213 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8214 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8215 // 1.2.2 OpenMP Language Terminology
8216 // Structured block - An executable statement with a single entry at the
8217 // top and a single exit at the bottom.
8218 // The point of exit cannot be a branch out of the structured block.
8219 // longjmp() and throw() must not violate the entry/exit criteria.
8220 CS->getCapturedDecl()->setNothrow();
8221 }
8222
Kelvin Li579e41c2016-11-30 23:51:03 +00008223 OMPLoopDirective::HelperExprs B;
8224 // In presence of clause 'collapse' with number of loops, it will
8225 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008226 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008227 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008228 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008229 VarsWithImplicitDSA, B);
8230
8231 if (NestedLoopCount == 0)
8232 return StmtError();
8233
8234 assert((CurContext->isDependentContext() || B.builtAll()) &&
8235 "omp for loop exprs were not built");
8236
8237 if (!CurContext->isDependentContext()) {
8238 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008239 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008240 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8241 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8242 B.NumIterations, *this, CurScope,
8243 DSAStack))
8244 return StmtError();
8245 }
8246 }
8247
8248 if (checkSimdlenSafelenSpecified(*this, Clauses))
8249 return StmtError();
8250
Reid Kleckner87a31802018-03-12 21:43:02 +00008251 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008252
8253 DSAStack->setParentTeamsRegionLoc(StartLoc);
8254
Kelvin Li579e41c2016-11-30 23:51:03 +00008255 return OMPTeamsDistributeParallelForSimdDirective::Create(
8256 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8257}
8258
Kelvin Li7ade93f2016-12-09 03:24:30 +00008259StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8260 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008261 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008262 if (!AStmt)
8263 return StmtError();
8264
Alexey Bataeve3727102018-04-18 15:57:46 +00008265 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008266 // 1.2.2 OpenMP Language Terminology
8267 // Structured block - An executable statement with a single entry at the
8268 // top and a single exit at the bottom.
8269 // The point of exit cannot be a branch out of the structured block.
8270 // longjmp() and throw() must not violate the entry/exit criteria.
8271 CS->getCapturedDecl()->setNothrow();
8272
Carlo Bertolli62fae152017-11-20 20:46:39 +00008273 for (int ThisCaptureLevel =
8274 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8275 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8276 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8277 // 1.2.2 OpenMP Language Terminology
8278 // Structured block - An executable statement with a single entry at the
8279 // top and a single exit at the bottom.
8280 // The point of exit cannot be a branch out of the structured block.
8281 // longjmp() and throw() must not violate the entry/exit criteria.
8282 CS->getCapturedDecl()->setNothrow();
8283 }
8284
Kelvin Li7ade93f2016-12-09 03:24:30 +00008285 OMPLoopDirective::HelperExprs B;
8286 // In presence of clause 'collapse' with number of loops, it will
8287 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008288 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008289 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008290 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008291 VarsWithImplicitDSA, B);
8292
8293 if (NestedLoopCount == 0)
8294 return StmtError();
8295
8296 assert((CurContext->isDependentContext() || B.builtAll()) &&
8297 "omp for loop exprs were not built");
8298
Reid Kleckner87a31802018-03-12 21:43:02 +00008299 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008300
8301 DSAStack->setParentTeamsRegionLoc(StartLoc);
8302
Kelvin Li7ade93f2016-12-09 03:24:30 +00008303 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008304 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8305 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008306}
8307
Kelvin Libf594a52016-12-17 05:48:59 +00008308StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8309 Stmt *AStmt,
8310 SourceLocation StartLoc,
8311 SourceLocation EndLoc) {
8312 if (!AStmt)
8313 return StmtError();
8314
Alexey Bataeve3727102018-04-18 15:57:46 +00008315 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008316 // 1.2.2 OpenMP Language Terminology
8317 // Structured block - An executable statement with a single entry at the
8318 // top and a single exit at the bottom.
8319 // The point of exit cannot be a branch out of the structured block.
8320 // longjmp() and throw() must not violate the entry/exit criteria.
8321 CS->getCapturedDecl()->setNothrow();
8322
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008323 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8324 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8325 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8326 // 1.2.2 OpenMP Language Terminology
8327 // Structured block - An executable statement with a single entry at the
8328 // top and a single exit at the bottom.
8329 // The point of exit cannot be a branch out of the structured block.
8330 // longjmp() and throw() must not violate the entry/exit criteria.
8331 CS->getCapturedDecl()->setNothrow();
8332 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008333 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008334
8335 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8336 AStmt);
8337}
8338
Kelvin Li83c451e2016-12-25 04:52:54 +00008339StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8340 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008342 if (!AStmt)
8343 return StmtError();
8344
Alexey Bataeve3727102018-04-18 15:57:46 +00008345 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008346 // 1.2.2 OpenMP Language Terminology
8347 // Structured block - An executable statement with a single entry at the
8348 // top and a single exit at the bottom.
8349 // The point of exit cannot be a branch out of the structured block.
8350 // longjmp() and throw() must not violate the entry/exit criteria.
8351 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008352 for (int ThisCaptureLevel =
8353 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8354 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8355 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8356 // 1.2.2 OpenMP Language Terminology
8357 // Structured block - An executable statement with a single entry at the
8358 // top and a single exit at the bottom.
8359 // The point of exit cannot be a branch out of the structured block.
8360 // longjmp() and throw() must not violate the entry/exit criteria.
8361 CS->getCapturedDecl()->setNothrow();
8362 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008363
8364 OMPLoopDirective::HelperExprs B;
8365 // In presence of clause 'collapse' with number of loops, it will
8366 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008367 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008368 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8369 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008370 VarsWithImplicitDSA, B);
8371 if (NestedLoopCount == 0)
8372 return StmtError();
8373
8374 assert((CurContext->isDependentContext() || B.builtAll()) &&
8375 "omp target teams distribute loop exprs were not built");
8376
Reid Kleckner87a31802018-03-12 21:43:02 +00008377 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008378 return OMPTargetTeamsDistributeDirective::Create(
8379 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8380}
8381
Kelvin Li80e8f562016-12-29 22:16:30 +00008382StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8383 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008385 if (!AStmt)
8386 return StmtError();
8387
Alexey Bataeve3727102018-04-18 15:57:46 +00008388 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008389 // 1.2.2 OpenMP Language Terminology
8390 // Structured block - An executable statement with a single entry at the
8391 // top and a single exit at the bottom.
8392 // The point of exit cannot be a branch out of the structured block.
8393 // longjmp() and throw() must not violate the entry/exit criteria.
8394 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008395 for (int ThisCaptureLevel =
8396 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8397 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8398 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8399 // 1.2.2 OpenMP Language Terminology
8400 // Structured block - An executable statement with a single entry at the
8401 // top and a single exit at the bottom.
8402 // The point of exit cannot be a branch out of the structured block.
8403 // longjmp() and throw() must not violate the entry/exit criteria.
8404 CS->getCapturedDecl()->setNothrow();
8405 }
8406
Kelvin Li80e8f562016-12-29 22:16:30 +00008407 OMPLoopDirective::HelperExprs B;
8408 // In presence of clause 'collapse' with number of loops, it will
8409 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008410 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008411 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8412 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008413 VarsWithImplicitDSA, B);
8414 if (NestedLoopCount == 0)
8415 return StmtError();
8416
8417 assert((CurContext->isDependentContext() || B.builtAll()) &&
8418 "omp target teams distribute parallel for loop exprs were not built");
8419
Alexey Bataev647dd842018-01-15 20:59:40 +00008420 if (!CurContext->isDependentContext()) {
8421 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008422 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008423 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8424 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8425 B.NumIterations, *this, CurScope,
8426 DSAStack))
8427 return StmtError();
8428 }
8429 }
8430
Reid Kleckner87a31802018-03-12 21:43:02 +00008431 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008432 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008433 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8434 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008435}
8436
Kelvin Li1851df52017-01-03 05:23:48 +00008437StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008439 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008440 if (!AStmt)
8441 return StmtError();
8442
Alexey Bataeve3727102018-04-18 15:57:46 +00008443 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008444 // 1.2.2 OpenMP Language Terminology
8445 // Structured block - An executable statement with a single entry at the
8446 // top and a single exit at the bottom.
8447 // The point of exit cannot be a branch out of the structured block.
8448 // longjmp() and throw() must not violate the entry/exit criteria.
8449 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008450 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8451 OMPD_target_teams_distribute_parallel_for_simd);
8452 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8453 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8454 // 1.2.2 OpenMP Language Terminology
8455 // Structured block - An executable statement with a single entry at the
8456 // top and a single exit at the bottom.
8457 // The point of exit cannot be a branch out of the structured block.
8458 // longjmp() and throw() must not violate the entry/exit criteria.
8459 CS->getCapturedDecl()->setNothrow();
8460 }
Kelvin Li1851df52017-01-03 05:23:48 +00008461
8462 OMPLoopDirective::HelperExprs B;
8463 // In presence of clause 'collapse' with number of loops, it will
8464 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008465 unsigned NestedLoopCount =
8466 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008467 getCollapseNumberExpr(Clauses),
8468 nullptr /*ordered not a clause on distribute*/, CS, *this,
8469 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008470 if (NestedLoopCount == 0)
8471 return StmtError();
8472
8473 assert((CurContext->isDependentContext() || B.builtAll()) &&
8474 "omp target teams distribute parallel for simd loop exprs were not "
8475 "built");
8476
8477 if (!CurContext->isDependentContext()) {
8478 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008479 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008480 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8481 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8482 B.NumIterations, *this, CurScope,
8483 DSAStack))
8484 return StmtError();
8485 }
8486 }
8487
Alexey Bataev438388c2017-11-22 18:34:02 +00008488 if (checkSimdlenSafelenSpecified(*this, Clauses))
8489 return StmtError();
8490
Reid Kleckner87a31802018-03-12 21:43:02 +00008491 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008492 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8493 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8494}
8495
Kelvin Lida681182017-01-10 18:08:18 +00008496StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8497 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008498 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008499 if (!AStmt)
8500 return StmtError();
8501
8502 auto *CS = cast<CapturedStmt>(AStmt);
8503 // 1.2.2 OpenMP Language Terminology
8504 // Structured block - An executable statement with a single entry at the
8505 // top and a single exit at the bottom.
8506 // The point of exit cannot be a branch out of the structured block.
8507 // longjmp() and throw() must not violate the entry/exit criteria.
8508 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008509 for (int ThisCaptureLevel =
8510 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8511 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8512 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8513 // 1.2.2 OpenMP Language Terminology
8514 // Structured block - An executable statement with a single entry at the
8515 // top and a single exit at the bottom.
8516 // The point of exit cannot be a branch out of the structured block.
8517 // longjmp() and throw() must not violate the entry/exit criteria.
8518 CS->getCapturedDecl()->setNothrow();
8519 }
Kelvin Lida681182017-01-10 18:08:18 +00008520
8521 OMPLoopDirective::HelperExprs B;
8522 // In presence of clause 'collapse' with number of loops, it will
8523 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008524 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008525 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008526 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008527 VarsWithImplicitDSA, B);
8528 if (NestedLoopCount == 0)
8529 return StmtError();
8530
8531 assert((CurContext->isDependentContext() || B.builtAll()) &&
8532 "omp target teams distribute simd loop exprs were not built");
8533
Alexey Bataev438388c2017-11-22 18:34:02 +00008534 if (!CurContext->isDependentContext()) {
8535 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008536 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008537 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8538 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8539 B.NumIterations, *this, CurScope,
8540 DSAStack))
8541 return StmtError();
8542 }
8543 }
8544
8545 if (checkSimdlenSafelenSpecified(*this, Clauses))
8546 return StmtError();
8547
Reid Kleckner87a31802018-03-12 21:43:02 +00008548 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008549 return OMPTargetTeamsDistributeSimdDirective::Create(
8550 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8551}
8552
Alexey Bataeved09d242014-05-28 05:53:51 +00008553OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008554 SourceLocation StartLoc,
8555 SourceLocation LParenLoc,
8556 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008557 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008558 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008559 case OMPC_final:
8560 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8561 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008562 case OMPC_num_threads:
8563 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8564 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008565 case OMPC_safelen:
8566 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8567 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008568 case OMPC_simdlen:
8569 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8570 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008571 case OMPC_allocator:
8572 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8573 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008574 case OMPC_collapse:
8575 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8576 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008577 case OMPC_ordered:
8578 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8579 break;
Michael Wonge710d542015-08-07 16:16:36 +00008580 case OMPC_device:
8581 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8582 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008583 case OMPC_num_teams:
8584 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8585 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008586 case OMPC_thread_limit:
8587 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8588 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008589 case OMPC_priority:
8590 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8591 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008592 case OMPC_grainsize:
8593 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8594 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008595 case OMPC_num_tasks:
8596 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8597 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008598 case OMPC_hint:
8599 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8600 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008601 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008602 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008603 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008604 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008605 case OMPC_private:
8606 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008607 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008608 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008609 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008610 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008611 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008612 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008613 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008614 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008615 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008616 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008617 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008618 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008619 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008620 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008621 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008622 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008623 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008624 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008625 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008626 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008627 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008628 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008629 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008630 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008631 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008632 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008633 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008634 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008635 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008636 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008637 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008638 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008639 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008640 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008641 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008642 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008643 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008644 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008645 llvm_unreachable("Clause is not allowed.");
8646 }
8647 return Res;
8648}
8649
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008650// An OpenMP directive such as 'target parallel' has two captured regions:
8651// for the 'target' and 'parallel' respectively. This function returns
8652// the region in which to capture expressions associated with a clause.
8653// A return value of OMPD_unknown signifies that the expression should not
8654// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008655static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8656 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8657 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008658 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008659 switch (CKind) {
8660 case OMPC_if:
8661 switch (DKind) {
8662 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008663 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008664 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008665 // If this clause applies to the nested 'parallel' region, capture within
8666 // the 'target' region, otherwise do not capture.
8667 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8668 CaptureRegion = OMPD_target;
8669 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008670 case OMPD_target_teams_distribute_parallel_for:
8671 case OMPD_target_teams_distribute_parallel_for_simd:
8672 // If this clause applies to the nested 'parallel' region, capture within
8673 // the 'teams' region, otherwise do not capture.
8674 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8675 CaptureRegion = OMPD_teams;
8676 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008677 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008678 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008679 CaptureRegion = OMPD_teams;
8680 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008681 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008682 case OMPD_target_enter_data:
8683 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008684 CaptureRegion = OMPD_task;
8685 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008686 case OMPD_cancel:
8687 case OMPD_parallel:
8688 case OMPD_parallel_sections:
8689 case OMPD_parallel_for:
8690 case OMPD_parallel_for_simd:
8691 case OMPD_target:
8692 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008693 case OMPD_target_teams:
8694 case OMPD_target_teams_distribute:
8695 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008696 case OMPD_distribute_parallel_for:
8697 case OMPD_distribute_parallel_for_simd:
8698 case OMPD_task:
8699 case OMPD_taskloop:
8700 case OMPD_taskloop_simd:
8701 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008702 // Do not capture if-clause expressions.
8703 break;
8704 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008705 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008706 case OMPD_taskyield:
8707 case OMPD_barrier:
8708 case OMPD_taskwait:
8709 case OMPD_cancellation_point:
8710 case OMPD_flush:
8711 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008712 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008713 case OMPD_declare_simd:
8714 case OMPD_declare_target:
8715 case OMPD_end_declare_target:
8716 case OMPD_teams:
8717 case OMPD_simd:
8718 case OMPD_for:
8719 case OMPD_for_simd:
8720 case OMPD_sections:
8721 case OMPD_section:
8722 case OMPD_single:
8723 case OMPD_master:
8724 case OMPD_critical:
8725 case OMPD_taskgroup:
8726 case OMPD_distribute:
8727 case OMPD_ordered:
8728 case OMPD_atomic:
8729 case OMPD_distribute_simd:
8730 case OMPD_teams_distribute:
8731 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008732 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008733 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8734 case OMPD_unknown:
8735 llvm_unreachable("Unknown OpenMP directive");
8736 }
8737 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008738 case OMPC_num_threads:
8739 switch (DKind) {
8740 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008741 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008742 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008743 CaptureRegion = OMPD_target;
8744 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008745 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008746 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008747 case OMPD_target_teams_distribute_parallel_for:
8748 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008749 CaptureRegion = OMPD_teams;
8750 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008751 case OMPD_parallel:
8752 case OMPD_parallel_sections:
8753 case OMPD_parallel_for:
8754 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008755 case OMPD_distribute_parallel_for:
8756 case OMPD_distribute_parallel_for_simd:
8757 // Do not capture num_threads-clause expressions.
8758 break;
8759 case OMPD_target_data:
8760 case OMPD_target_enter_data:
8761 case OMPD_target_exit_data:
8762 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008763 case OMPD_target:
8764 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008765 case OMPD_target_teams:
8766 case OMPD_target_teams_distribute:
8767 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008768 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008769 case OMPD_task:
8770 case OMPD_taskloop:
8771 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008772 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008773 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008774 case OMPD_taskyield:
8775 case OMPD_barrier:
8776 case OMPD_taskwait:
8777 case OMPD_cancellation_point:
8778 case OMPD_flush:
8779 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008780 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008781 case OMPD_declare_simd:
8782 case OMPD_declare_target:
8783 case OMPD_end_declare_target:
8784 case OMPD_teams:
8785 case OMPD_simd:
8786 case OMPD_for:
8787 case OMPD_for_simd:
8788 case OMPD_sections:
8789 case OMPD_section:
8790 case OMPD_single:
8791 case OMPD_master:
8792 case OMPD_critical:
8793 case OMPD_taskgroup:
8794 case OMPD_distribute:
8795 case OMPD_ordered:
8796 case OMPD_atomic:
8797 case OMPD_distribute_simd:
8798 case OMPD_teams_distribute:
8799 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008800 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008801 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8802 case OMPD_unknown:
8803 llvm_unreachable("Unknown OpenMP directive");
8804 }
8805 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008806 case OMPC_num_teams:
8807 switch (DKind) {
8808 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008809 case OMPD_target_teams_distribute:
8810 case OMPD_target_teams_distribute_simd:
8811 case OMPD_target_teams_distribute_parallel_for:
8812 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008813 CaptureRegion = OMPD_target;
8814 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008815 case OMPD_teams_distribute_parallel_for:
8816 case OMPD_teams_distribute_parallel_for_simd:
8817 case OMPD_teams:
8818 case OMPD_teams_distribute:
8819 case OMPD_teams_distribute_simd:
8820 // Do not capture num_teams-clause expressions.
8821 break;
8822 case OMPD_distribute_parallel_for:
8823 case OMPD_distribute_parallel_for_simd:
8824 case OMPD_task:
8825 case OMPD_taskloop:
8826 case OMPD_taskloop_simd:
8827 case OMPD_target_data:
8828 case OMPD_target_enter_data:
8829 case OMPD_target_exit_data:
8830 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008831 case OMPD_cancel:
8832 case OMPD_parallel:
8833 case OMPD_parallel_sections:
8834 case OMPD_parallel_for:
8835 case OMPD_parallel_for_simd:
8836 case OMPD_target:
8837 case OMPD_target_simd:
8838 case OMPD_target_parallel:
8839 case OMPD_target_parallel_for:
8840 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008841 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008842 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008843 case OMPD_taskyield:
8844 case OMPD_barrier:
8845 case OMPD_taskwait:
8846 case OMPD_cancellation_point:
8847 case OMPD_flush:
8848 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008849 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008850 case OMPD_declare_simd:
8851 case OMPD_declare_target:
8852 case OMPD_end_declare_target:
8853 case OMPD_simd:
8854 case OMPD_for:
8855 case OMPD_for_simd:
8856 case OMPD_sections:
8857 case OMPD_section:
8858 case OMPD_single:
8859 case OMPD_master:
8860 case OMPD_critical:
8861 case OMPD_taskgroup:
8862 case OMPD_distribute:
8863 case OMPD_ordered:
8864 case OMPD_atomic:
8865 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008866 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008867 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8868 case OMPD_unknown:
8869 llvm_unreachable("Unknown OpenMP directive");
8870 }
8871 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008872 case OMPC_thread_limit:
8873 switch (DKind) {
8874 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008875 case OMPD_target_teams_distribute:
8876 case OMPD_target_teams_distribute_simd:
8877 case OMPD_target_teams_distribute_parallel_for:
8878 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008879 CaptureRegion = OMPD_target;
8880 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008881 case OMPD_teams_distribute_parallel_for:
8882 case OMPD_teams_distribute_parallel_for_simd:
8883 case OMPD_teams:
8884 case OMPD_teams_distribute:
8885 case OMPD_teams_distribute_simd:
8886 // Do not capture thread_limit-clause expressions.
8887 break;
8888 case OMPD_distribute_parallel_for:
8889 case OMPD_distribute_parallel_for_simd:
8890 case OMPD_task:
8891 case OMPD_taskloop:
8892 case OMPD_taskloop_simd:
8893 case OMPD_target_data:
8894 case OMPD_target_enter_data:
8895 case OMPD_target_exit_data:
8896 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008897 case OMPD_cancel:
8898 case OMPD_parallel:
8899 case OMPD_parallel_sections:
8900 case OMPD_parallel_for:
8901 case OMPD_parallel_for_simd:
8902 case OMPD_target:
8903 case OMPD_target_simd:
8904 case OMPD_target_parallel:
8905 case OMPD_target_parallel_for:
8906 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008907 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008908 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008909 case OMPD_taskyield:
8910 case OMPD_barrier:
8911 case OMPD_taskwait:
8912 case OMPD_cancellation_point:
8913 case OMPD_flush:
8914 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008915 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008916 case OMPD_declare_simd:
8917 case OMPD_declare_target:
8918 case OMPD_end_declare_target:
8919 case OMPD_simd:
8920 case OMPD_for:
8921 case OMPD_for_simd:
8922 case OMPD_sections:
8923 case OMPD_section:
8924 case OMPD_single:
8925 case OMPD_master:
8926 case OMPD_critical:
8927 case OMPD_taskgroup:
8928 case OMPD_distribute:
8929 case OMPD_ordered:
8930 case OMPD_atomic:
8931 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008932 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008933 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8934 case OMPD_unknown:
8935 llvm_unreachable("Unknown OpenMP directive");
8936 }
8937 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008938 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008939 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008940 case OMPD_parallel_for:
8941 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008942 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008943 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008944 case OMPD_teams_distribute_parallel_for:
8945 case OMPD_teams_distribute_parallel_for_simd:
8946 case OMPD_target_parallel_for:
8947 case OMPD_target_parallel_for_simd:
8948 case OMPD_target_teams_distribute_parallel_for:
8949 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008950 CaptureRegion = OMPD_parallel;
8951 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008952 case OMPD_for:
8953 case OMPD_for_simd:
8954 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008955 break;
8956 case OMPD_task:
8957 case OMPD_taskloop:
8958 case OMPD_taskloop_simd:
8959 case OMPD_target_data:
8960 case OMPD_target_enter_data:
8961 case OMPD_target_exit_data:
8962 case OMPD_target_update:
8963 case OMPD_teams:
8964 case OMPD_teams_distribute:
8965 case OMPD_teams_distribute_simd:
8966 case OMPD_target_teams_distribute:
8967 case OMPD_target_teams_distribute_simd:
8968 case OMPD_target:
8969 case OMPD_target_simd:
8970 case OMPD_target_parallel:
8971 case OMPD_cancel:
8972 case OMPD_parallel:
8973 case OMPD_parallel_sections:
8974 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008975 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008976 case OMPD_taskyield:
8977 case OMPD_barrier:
8978 case OMPD_taskwait:
8979 case OMPD_cancellation_point:
8980 case OMPD_flush:
8981 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008982 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008983 case OMPD_declare_simd:
8984 case OMPD_declare_target:
8985 case OMPD_end_declare_target:
8986 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008987 case OMPD_sections:
8988 case OMPD_section:
8989 case OMPD_single:
8990 case OMPD_master:
8991 case OMPD_critical:
8992 case OMPD_taskgroup:
8993 case OMPD_distribute:
8994 case OMPD_ordered:
8995 case OMPD_atomic:
8996 case OMPD_distribute_simd:
8997 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008998 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008999 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9000 case OMPD_unknown:
9001 llvm_unreachable("Unknown OpenMP directive");
9002 }
9003 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009004 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009005 switch (DKind) {
9006 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009007 case OMPD_teams_distribute_parallel_for_simd:
9008 case OMPD_teams_distribute:
9009 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009010 case OMPD_target_teams_distribute_parallel_for:
9011 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009012 case OMPD_target_teams_distribute:
9013 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009014 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009015 break;
9016 case OMPD_distribute_parallel_for:
9017 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009018 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009019 case OMPD_distribute_simd:
9020 // Do not capture thread_limit-clause expressions.
9021 break;
9022 case OMPD_parallel_for:
9023 case OMPD_parallel_for_simd:
9024 case OMPD_target_parallel_for_simd:
9025 case OMPD_target_parallel_for:
9026 case OMPD_task:
9027 case OMPD_taskloop:
9028 case OMPD_taskloop_simd:
9029 case OMPD_target_data:
9030 case OMPD_target_enter_data:
9031 case OMPD_target_exit_data:
9032 case OMPD_target_update:
9033 case OMPD_teams:
9034 case OMPD_target:
9035 case OMPD_target_simd:
9036 case OMPD_target_parallel:
9037 case OMPD_cancel:
9038 case OMPD_parallel:
9039 case OMPD_parallel_sections:
9040 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009041 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009042 case OMPD_taskyield:
9043 case OMPD_barrier:
9044 case OMPD_taskwait:
9045 case OMPD_cancellation_point:
9046 case OMPD_flush:
9047 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009048 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009049 case OMPD_declare_simd:
9050 case OMPD_declare_target:
9051 case OMPD_end_declare_target:
9052 case OMPD_simd:
9053 case OMPD_for:
9054 case OMPD_for_simd:
9055 case OMPD_sections:
9056 case OMPD_section:
9057 case OMPD_single:
9058 case OMPD_master:
9059 case OMPD_critical:
9060 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009061 case OMPD_ordered:
9062 case OMPD_atomic:
9063 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009064 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009065 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9066 case OMPD_unknown:
9067 llvm_unreachable("Unknown OpenMP directive");
9068 }
9069 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009070 case OMPC_device:
9071 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009072 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009073 case OMPD_target_enter_data:
9074 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009075 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009076 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009077 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009078 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009079 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009080 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009081 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009082 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009083 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009084 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009085 CaptureRegion = OMPD_task;
9086 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009087 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009088 // Do not capture device-clause expressions.
9089 break;
9090 case OMPD_teams_distribute_parallel_for:
9091 case OMPD_teams_distribute_parallel_for_simd:
9092 case OMPD_teams:
9093 case OMPD_teams_distribute:
9094 case OMPD_teams_distribute_simd:
9095 case OMPD_distribute_parallel_for:
9096 case OMPD_distribute_parallel_for_simd:
9097 case OMPD_task:
9098 case OMPD_taskloop:
9099 case OMPD_taskloop_simd:
9100 case OMPD_cancel:
9101 case OMPD_parallel:
9102 case OMPD_parallel_sections:
9103 case OMPD_parallel_for:
9104 case OMPD_parallel_for_simd:
9105 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009106 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009107 case OMPD_taskyield:
9108 case OMPD_barrier:
9109 case OMPD_taskwait:
9110 case OMPD_cancellation_point:
9111 case OMPD_flush:
9112 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009113 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009114 case OMPD_declare_simd:
9115 case OMPD_declare_target:
9116 case OMPD_end_declare_target:
9117 case OMPD_simd:
9118 case OMPD_for:
9119 case OMPD_for_simd:
9120 case OMPD_sections:
9121 case OMPD_section:
9122 case OMPD_single:
9123 case OMPD_master:
9124 case OMPD_critical:
9125 case OMPD_taskgroup:
9126 case OMPD_distribute:
9127 case OMPD_ordered:
9128 case OMPD_atomic:
9129 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009130 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009131 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9132 case OMPD_unknown:
9133 llvm_unreachable("Unknown OpenMP directive");
9134 }
9135 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009136 case OMPC_firstprivate:
9137 case OMPC_lastprivate:
9138 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009139 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009140 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009141 case OMPC_linear:
9142 case OMPC_default:
9143 case OMPC_proc_bind:
9144 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009145 case OMPC_safelen:
9146 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009147 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009148 case OMPC_collapse:
9149 case OMPC_private:
9150 case OMPC_shared:
9151 case OMPC_aligned:
9152 case OMPC_copyin:
9153 case OMPC_copyprivate:
9154 case OMPC_ordered:
9155 case OMPC_nowait:
9156 case OMPC_untied:
9157 case OMPC_mergeable:
9158 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009159 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009160 case OMPC_flush:
9161 case OMPC_read:
9162 case OMPC_write:
9163 case OMPC_update:
9164 case OMPC_capture:
9165 case OMPC_seq_cst:
9166 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009167 case OMPC_threads:
9168 case OMPC_simd:
9169 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009170 case OMPC_priority:
9171 case OMPC_grainsize:
9172 case OMPC_nogroup:
9173 case OMPC_num_tasks:
9174 case OMPC_hint:
9175 case OMPC_defaultmap:
9176 case OMPC_unknown:
9177 case OMPC_uniform:
9178 case OMPC_to:
9179 case OMPC_from:
9180 case OMPC_use_device_ptr:
9181 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009182 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009183 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009184 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009185 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009186 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009187 llvm_unreachable("Unexpected OpenMP clause.");
9188 }
9189 return CaptureRegion;
9190}
9191
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009192OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9193 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009194 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009195 SourceLocation NameModifierLoc,
9196 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009197 SourceLocation EndLoc) {
9198 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009199 Stmt *HelperValStmt = nullptr;
9200 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009201 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9202 !Condition->isInstantiationDependent() &&
9203 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009204 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009205 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009206 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009207
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009208 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009209
9210 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9211 CaptureRegion =
9212 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009213 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009214 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009215 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009216 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9217 HelperValStmt = buildPreInits(Context, Captures);
9218 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009219 }
9220
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009221 return new (Context)
9222 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9223 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009224}
9225
Alexey Bataev3778b602014-07-17 07:32:53 +00009226OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9227 SourceLocation StartLoc,
9228 SourceLocation LParenLoc,
9229 SourceLocation EndLoc) {
9230 Expr *ValExpr = Condition;
9231 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9232 !Condition->isInstantiationDependent() &&
9233 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009234 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009235 if (Val.isInvalid())
9236 return nullptr;
9237
Richard Smith03a4aa32016-06-23 19:02:52 +00009238 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009239 }
9240
9241 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9242}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009243ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9244 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009245 if (!Op)
9246 return ExprError();
9247
9248 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9249 public:
9250 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009251 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009252 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9253 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009254 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9255 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009256 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9257 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009258 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9259 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009260 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9261 QualType T,
9262 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009263 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9264 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009265 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9266 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009267 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009268 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009269 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009270 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9271 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009272 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9273 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009274 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9275 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009276 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009277 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009278 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009279 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9280 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009281 llvm_unreachable("conversion functions are permitted");
9282 }
9283 } ConvertDiagnoser;
9284 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9285}
9286
Alexey Bataeve3727102018-04-18 15:57:46 +00009287static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009288 OpenMPClauseKind CKind,
9289 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009290 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9291 !ValExpr->isInstantiationDependent()) {
9292 SourceLocation Loc = ValExpr->getExprLoc();
9293 ExprResult Value =
9294 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9295 if (Value.isInvalid())
9296 return false;
9297
9298 ValExpr = Value.get();
9299 // The expression must evaluate to a non-negative integer value.
9300 llvm::APSInt Result;
9301 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009302 Result.isSigned() &&
9303 !((!StrictlyPositive && Result.isNonNegative()) ||
9304 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009305 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009306 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9307 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009308 return false;
9309 }
9310 }
9311 return true;
9312}
9313
Alexey Bataev568a8332014-03-06 06:15:19 +00009314OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9315 SourceLocation StartLoc,
9316 SourceLocation LParenLoc,
9317 SourceLocation EndLoc) {
9318 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009319 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009320
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009321 // OpenMP [2.5, Restrictions]
9322 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009323 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009324 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009325 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009326
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009327 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009328 OpenMPDirectiveKind CaptureRegion =
9329 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9330 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009331 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009332 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009333 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9334 HelperValStmt = buildPreInits(Context, Captures);
9335 }
9336
9337 return new (Context) OMPNumThreadsClause(
9338 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009339}
9340
Alexey Bataev62c87d22014-03-21 04:51:18 +00009341ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009342 OpenMPClauseKind CKind,
9343 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009344 if (!E)
9345 return ExprError();
9346 if (E->isValueDependent() || E->isTypeDependent() ||
9347 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009348 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009349 llvm::APSInt Result;
9350 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9351 if (ICE.isInvalid())
9352 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009353 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9354 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009355 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009356 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9357 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009358 return ExprError();
9359 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009360 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9361 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9362 << E->getSourceRange();
9363 return ExprError();
9364 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009365 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9366 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009367 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009368 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009369 return ICE;
9370}
9371
9372OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9373 SourceLocation LParenLoc,
9374 SourceLocation EndLoc) {
9375 // OpenMP [2.8.1, simd construct, Description]
9376 // The parameter of the safelen clause must be a constant
9377 // positive integer expression.
9378 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9379 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009380 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009381 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009382 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009383}
9384
Alexey Bataev66b15b52015-08-21 11:14:16 +00009385OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9386 SourceLocation LParenLoc,
9387 SourceLocation EndLoc) {
9388 // OpenMP [2.8.1, simd construct, Description]
9389 // The parameter of the simdlen clause must be a constant
9390 // positive integer expression.
9391 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9392 if (Simdlen.isInvalid())
9393 return nullptr;
9394 return new (Context)
9395 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9396}
9397
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009398/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009399static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9400 DSAStackTy *Stack) {
9401 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009402 if (!OMPAllocatorHandleT.isNull())
9403 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009404 // Build the predefined allocator expressions.
9405 bool ErrorFound = false;
9406 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9407 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9408 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9409 StringRef Allocator =
9410 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9411 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9412 auto *VD = dyn_cast_or_null<ValueDecl>(
9413 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9414 if (!VD) {
9415 ErrorFound = true;
9416 break;
9417 }
9418 QualType AllocatorType =
9419 VD->getType().getNonLValueExprType(S.getASTContext());
9420 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9421 if (!Res.isUsable()) {
9422 ErrorFound = true;
9423 break;
9424 }
9425 if (OMPAllocatorHandleT.isNull())
9426 OMPAllocatorHandleT = AllocatorType;
9427 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9428 ErrorFound = true;
9429 break;
9430 }
9431 Stack->setAllocator(AllocatorKind, Res.get());
9432 }
9433 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009434 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9435 return false;
9436 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00009437 OMPAllocatorHandleT.addConst();
9438 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009439 return true;
9440}
9441
9442OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9443 SourceLocation LParenLoc,
9444 SourceLocation EndLoc) {
9445 // OpenMP [2.11.3, allocate Directive, Description]
9446 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009447 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009448 return nullptr;
9449
9450 ExprResult Allocator = DefaultLvalueConversion(A);
9451 if (Allocator.isInvalid())
9452 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009453 Allocator = PerformImplicitConversion(Allocator.get(),
9454 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009455 Sema::AA_Initializing,
9456 /*AllowExplicit=*/true);
9457 if (Allocator.isInvalid())
9458 return nullptr;
9459 return new (Context)
9460 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9461}
9462
Alexander Musman64d33f12014-06-04 07:53:32 +00009463OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9464 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009465 SourceLocation LParenLoc,
9466 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009467 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009468 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009469 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009470 // The parameter of the collapse clause must be a constant
9471 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009472 ExprResult NumForLoopsResult =
9473 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9474 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009475 return nullptr;
9476 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009477 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009478}
9479
Alexey Bataev10e775f2015-07-30 11:36:16 +00009480OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9481 SourceLocation EndLoc,
9482 SourceLocation LParenLoc,
9483 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009484 // OpenMP [2.7.1, loop construct, Description]
9485 // OpenMP [2.8.1, simd construct, Description]
9486 // OpenMP [2.9.6, distribute construct, Description]
9487 // The parameter of the ordered clause must be a constant
9488 // positive integer expression if any.
9489 if (NumForLoops && LParenLoc.isValid()) {
9490 ExprResult NumForLoopsResult =
9491 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9492 if (NumForLoopsResult.isInvalid())
9493 return nullptr;
9494 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009495 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009496 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009497 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009498 auto *Clause = OMPOrderedClause::Create(
9499 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9500 StartLoc, LParenLoc, EndLoc);
9501 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9502 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009503}
9504
Alexey Bataeved09d242014-05-28 05:53:51 +00009505OMPClause *Sema::ActOnOpenMPSimpleClause(
9506 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9507 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009508 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009509 switch (Kind) {
9510 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009511 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009512 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9513 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009514 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009515 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009516 Res = ActOnOpenMPProcBindClause(
9517 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9518 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009519 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009520 case OMPC_atomic_default_mem_order:
9521 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9522 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9523 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9524 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009525 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009526 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009527 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009528 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009529 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009530 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009531 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009532 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009533 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009534 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009535 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009536 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009537 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009538 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009539 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009540 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009541 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009542 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009543 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009544 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009545 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009546 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009547 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009548 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009549 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009550 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009551 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009552 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009553 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009554 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009555 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009556 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009557 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009558 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009559 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009560 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009561 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009562 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009563 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009564 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009565 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009566 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009567 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009568 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009569 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009570 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009571 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009572 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009573 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009574 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009575 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009576 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009577 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009578 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009579 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009580 llvm_unreachable("Clause is not allowed.");
9581 }
9582 return Res;
9583}
9584
Alexey Bataev6402bca2015-12-28 07:25:51 +00009585static std::string
9586getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9587 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009588 SmallString<256> Buffer;
9589 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009590 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9591 unsigned Skipped = Exclude.size();
9592 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009593 for (unsigned I = First; I < Last; ++I) {
9594 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009595 --Skipped;
9596 continue;
9597 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009598 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9599 if (I == Bound - Skipped)
9600 Out << " or ";
9601 else if (I != Bound + 1 - Skipped)
9602 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009603 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009604 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009605}
9606
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009607OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9608 SourceLocation KindKwLoc,
9609 SourceLocation StartLoc,
9610 SourceLocation LParenLoc,
9611 SourceLocation EndLoc) {
9612 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009613 static_assert(OMPC_DEFAULT_unknown > 0,
9614 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009615 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009616 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9617 /*Last=*/OMPC_DEFAULT_unknown)
9618 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009619 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009620 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009621 switch (Kind) {
9622 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009623 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009624 break;
9625 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009626 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009627 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009628 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009629 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009630 break;
9631 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009632 return new (Context)
9633 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009634}
9635
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009636OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9637 SourceLocation KindKwLoc,
9638 SourceLocation StartLoc,
9639 SourceLocation LParenLoc,
9640 SourceLocation EndLoc) {
9641 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009642 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009643 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9644 /*Last=*/OMPC_PROC_BIND_unknown)
9645 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009646 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009647 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009648 return new (Context)
9649 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009650}
9651
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009652OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9653 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9654 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9655 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9656 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9657 << getListOfPossibleValues(
9658 OMPC_atomic_default_mem_order, /*First=*/0,
9659 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9660 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9661 return nullptr;
9662 }
9663 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9664 LParenLoc, EndLoc);
9665}
9666
Alexey Bataev56dafe82014-06-20 07:16:17 +00009667OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009668 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009669 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009670 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009671 SourceLocation EndLoc) {
9672 OMPClause *Res = nullptr;
9673 switch (Kind) {
9674 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009675 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9676 assert(Argument.size() == NumberOfElements &&
9677 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009678 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009679 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9680 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9681 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9682 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9683 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009684 break;
9685 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009686 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9687 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9688 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9689 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009690 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009691 case OMPC_dist_schedule:
9692 Res = ActOnOpenMPDistScheduleClause(
9693 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9694 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9695 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009696 case OMPC_defaultmap:
9697 enum { Modifier, DefaultmapKind };
9698 Res = ActOnOpenMPDefaultmapClause(
9699 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9700 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009701 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9702 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009703 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009704 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009705 case OMPC_num_threads:
9706 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009707 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009708 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009709 case OMPC_collapse:
9710 case OMPC_default:
9711 case OMPC_proc_bind:
9712 case OMPC_private:
9713 case OMPC_firstprivate:
9714 case OMPC_lastprivate:
9715 case OMPC_shared:
9716 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009717 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009718 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009719 case OMPC_linear:
9720 case OMPC_aligned:
9721 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009722 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009723 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009724 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009725 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009726 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009727 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009728 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009729 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009730 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009731 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009732 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009733 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009734 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009735 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009736 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009737 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009738 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009739 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009740 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009741 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009742 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009743 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009744 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009745 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009746 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009747 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009748 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009749 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009750 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009751 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009752 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009753 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009754 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009755 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009756 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009757 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009758 llvm_unreachable("Clause is not allowed.");
9759 }
9760 return Res;
9761}
9762
Alexey Bataev6402bca2015-12-28 07:25:51 +00009763static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9764 OpenMPScheduleClauseModifier M2,
9765 SourceLocation M1Loc, SourceLocation M2Loc) {
9766 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9767 SmallVector<unsigned, 2> Excluded;
9768 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9769 Excluded.push_back(M2);
9770 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9771 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9772 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9773 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9774 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9775 << getListOfPossibleValues(OMPC_schedule,
9776 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9777 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9778 Excluded)
9779 << getOpenMPClauseName(OMPC_schedule);
9780 return true;
9781 }
9782 return false;
9783}
9784
Alexey Bataev56dafe82014-06-20 07:16:17 +00009785OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009786 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009787 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009788 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9789 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9790 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9791 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9792 return nullptr;
9793 // OpenMP, 2.7.1, Loop Construct, Restrictions
9794 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9795 // but not both.
9796 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9797 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9798 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9799 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9800 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9801 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9802 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9803 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9804 return nullptr;
9805 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009806 if (Kind == OMPC_SCHEDULE_unknown) {
9807 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009808 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9809 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9810 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9811 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9812 Exclude);
9813 } else {
9814 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9815 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009816 }
9817 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9818 << Values << getOpenMPClauseName(OMPC_schedule);
9819 return nullptr;
9820 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009821 // OpenMP, 2.7.1, Loop Construct, Restrictions
9822 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9823 // schedule(guided).
9824 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9825 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9826 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9827 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9828 diag::err_omp_schedule_nonmonotonic_static);
9829 return nullptr;
9830 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009831 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009832 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009833 if (ChunkSize) {
9834 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9835 !ChunkSize->isInstantiationDependent() &&
9836 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009837 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009838 ExprResult Val =
9839 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9840 if (Val.isInvalid())
9841 return nullptr;
9842
9843 ValExpr = Val.get();
9844
9845 // OpenMP [2.7.1, Restrictions]
9846 // chunk_size must be a loop invariant integer expression with a positive
9847 // value.
9848 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009849 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9850 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9851 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009852 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009853 return nullptr;
9854 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009855 } else if (getOpenMPCaptureRegionForClause(
9856 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9857 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009858 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009859 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009860 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009861 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9862 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009863 }
9864 }
9865 }
9866
Alexey Bataev6402bca2015-12-28 07:25:51 +00009867 return new (Context)
9868 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009869 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009870}
9871
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009872OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9873 SourceLocation StartLoc,
9874 SourceLocation EndLoc) {
9875 OMPClause *Res = nullptr;
9876 switch (Kind) {
9877 case OMPC_ordered:
9878 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9879 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009880 case OMPC_nowait:
9881 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9882 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009883 case OMPC_untied:
9884 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9885 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009886 case OMPC_mergeable:
9887 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9888 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009889 case OMPC_read:
9890 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9891 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009892 case OMPC_write:
9893 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9894 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009895 case OMPC_update:
9896 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9897 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009898 case OMPC_capture:
9899 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9900 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009901 case OMPC_seq_cst:
9902 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9903 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009904 case OMPC_threads:
9905 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9906 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009907 case OMPC_simd:
9908 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9909 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009910 case OMPC_nogroup:
9911 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9912 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009913 case OMPC_unified_address:
9914 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9915 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009916 case OMPC_unified_shared_memory:
9917 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9918 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009919 case OMPC_reverse_offload:
9920 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9921 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009922 case OMPC_dynamic_allocators:
9923 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9924 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009925 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009926 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009927 case OMPC_num_threads:
9928 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009929 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009930 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009931 case OMPC_collapse:
9932 case OMPC_schedule:
9933 case OMPC_private:
9934 case OMPC_firstprivate:
9935 case OMPC_lastprivate:
9936 case OMPC_shared:
9937 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009938 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009939 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009940 case OMPC_linear:
9941 case OMPC_aligned:
9942 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009943 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009944 case OMPC_default:
9945 case OMPC_proc_bind:
9946 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009947 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009948 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009949 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009950 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009951 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009952 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009953 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009954 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009955 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009956 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009957 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009958 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009959 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009960 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009961 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009962 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009963 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009964 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009965 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009966 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009967 llvm_unreachable("Clause is not allowed.");
9968 }
9969 return Res;
9970}
9971
Alexey Bataev236070f2014-06-20 11:19:47 +00009972OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9973 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009974 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009975 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9976}
9977
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009978OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9979 SourceLocation EndLoc) {
9980 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9981}
9982
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009983OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9984 SourceLocation EndLoc) {
9985 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9986}
9987
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009988OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9989 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009990 return new (Context) OMPReadClause(StartLoc, EndLoc);
9991}
9992
Alexey Bataevdea47612014-07-23 07:46:59 +00009993OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9994 SourceLocation EndLoc) {
9995 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9996}
9997
Alexey Bataev67a4f222014-07-23 10:25:33 +00009998OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9999 SourceLocation EndLoc) {
10000 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10001}
10002
Alexey Bataev459dec02014-07-24 06:46:57 +000010003OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10004 SourceLocation EndLoc) {
10005 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10006}
10007
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010008OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10009 SourceLocation EndLoc) {
10010 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10011}
10012
Alexey Bataev346265e2015-09-25 10:37:12 +000010013OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10014 SourceLocation EndLoc) {
10015 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10016}
10017
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010018OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10019 SourceLocation EndLoc) {
10020 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10021}
10022
Alexey Bataevb825de12015-12-07 10:51:44 +000010023OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10024 SourceLocation EndLoc) {
10025 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10026}
10027
Kelvin Li1408f912018-09-26 04:28:39 +000010028OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10029 SourceLocation EndLoc) {
10030 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10031}
10032
Patrick Lyster4a370b92018-10-01 13:47:43 +000010033OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10034 SourceLocation EndLoc) {
10035 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10036}
10037
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010038OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10039 SourceLocation EndLoc) {
10040 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10041}
10042
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010043OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10044 SourceLocation EndLoc) {
10045 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10046}
10047
Alexey Bataevc5e02582014-06-16 07:08:35 +000010048OMPClause *Sema::ActOnOpenMPVarListClause(
10049 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010050 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10051 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10052 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010053 OpenMPLinearClauseKind LinKind,
10054 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010055 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10056 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10057 SourceLocation StartLoc = Locs.StartLoc;
10058 SourceLocation LParenLoc = Locs.LParenLoc;
10059 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010060 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010061 switch (Kind) {
10062 case OMPC_private:
10063 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10064 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010065 case OMPC_firstprivate:
10066 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10067 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010068 case OMPC_lastprivate:
10069 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10070 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010071 case OMPC_shared:
10072 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10073 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010074 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010075 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010076 EndLoc, ReductionOrMapperIdScopeSpec,
10077 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010078 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010079 case OMPC_task_reduction:
10080 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010081 EndLoc, ReductionOrMapperIdScopeSpec,
10082 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010083 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010084 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010085 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10086 EndLoc, ReductionOrMapperIdScopeSpec,
10087 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010088 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010089 case OMPC_linear:
10090 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010091 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010092 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010093 case OMPC_aligned:
10094 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10095 ColonLoc, EndLoc);
10096 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010097 case OMPC_copyin:
10098 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10099 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010100 case OMPC_copyprivate:
10101 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10102 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010103 case OMPC_flush:
10104 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10105 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010106 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010107 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010108 StartLoc, LParenLoc, EndLoc);
10109 break;
10110 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010111 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10112 ReductionOrMapperIdScopeSpec,
10113 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10114 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010115 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010116 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010117 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10118 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010119 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010120 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010121 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10122 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010123 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010124 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010125 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010126 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010127 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010128 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010129 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010130 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010131 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010132 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010133 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010134 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010135 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010136 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010137 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010138 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010139 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010140 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010141 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010142 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010143 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010144 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010145 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010146 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010147 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010148 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010149 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010150 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010151 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010152 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010153 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010154 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010155 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010156 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010157 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010158 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010159 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010160 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010161 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010162 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010163 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010164 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010165 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010166 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010167 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010168 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010169 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010170 llvm_unreachable("Clause is not allowed.");
10171 }
10172 return Res;
10173}
10174
Alexey Bataev90c228f2016-02-08 09:29:13 +000010175ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010176 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010177 ExprResult Res = BuildDeclRefExpr(
10178 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10179 if (!Res.isUsable())
10180 return ExprError();
10181 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10182 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10183 if (!Res.isUsable())
10184 return ExprError();
10185 }
10186 if (VK != VK_LValue && Res.get()->isGLValue()) {
10187 Res = DefaultLvalueConversion(Res.get());
10188 if (!Res.isUsable())
10189 return ExprError();
10190 }
10191 return Res;
10192}
10193
Alexey Bataev60da77e2016-02-29 05:54:20 +000010194static std::pair<ValueDecl *, bool>
10195getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10196 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010197 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10198 RefExpr->containsUnexpandedParameterPack())
10199 return std::make_pair(nullptr, true);
10200
Alexey Bataevd985eda2016-02-10 11:29:16 +000010201 // OpenMP [3.1, C/C++]
10202 // A list item is a variable name.
10203 // OpenMP [2.9.3.3, Restrictions, p.1]
10204 // A variable that is part of another variable (as an array or
10205 // structure element) cannot appear in a private clause.
10206 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010207 enum {
10208 NoArrayExpr = -1,
10209 ArraySubscript = 0,
10210 OMPArraySection = 1
10211 } IsArrayExpr = NoArrayExpr;
10212 if (AllowArraySection) {
10213 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010214 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010215 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10216 Base = TempASE->getBase()->IgnoreParenImpCasts();
10217 RefExpr = Base;
10218 IsArrayExpr = ArraySubscript;
10219 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010220 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010221 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10222 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10223 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10224 Base = TempASE->getBase()->IgnoreParenImpCasts();
10225 RefExpr = Base;
10226 IsArrayExpr = OMPArraySection;
10227 }
10228 }
10229 ELoc = RefExpr->getExprLoc();
10230 ERange = RefExpr->getSourceRange();
10231 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010232 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10233 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10234 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10235 (S.getCurrentThisType().isNull() || !ME ||
10236 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10237 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010238 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010239 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10240 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010241 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010242 S.Diag(ELoc,
10243 AllowArraySection
10244 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10245 : diag::err_omp_expected_var_name_member_expr)
10246 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10247 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010248 return std::make_pair(nullptr, false);
10249 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010250 return std::make_pair(
10251 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010252}
10253
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010254OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10255 SourceLocation StartLoc,
10256 SourceLocation LParenLoc,
10257 SourceLocation EndLoc) {
10258 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010259 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010260 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010261 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010262 SourceLocation ELoc;
10263 SourceRange ERange;
10264 Expr *SimpleRefExpr = RefExpr;
10265 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010266 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010267 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010268 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010269 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010270 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010271 ValueDecl *D = Res.first;
10272 if (!D)
10273 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010274
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010275 QualType Type = D->getType();
10276 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010277
10278 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10279 // A variable that appears in a private clause must not have an incomplete
10280 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010281 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010282 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010283 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010284
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010285 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10286 // A variable that is privatized must not have a const-qualified type
10287 // unless it is of class type with a mutable member. This restriction does
10288 // not apply to the firstprivate clause.
10289 //
10290 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10291 // A variable that appears in a private clause must not have a
10292 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010293 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010294 continue;
10295
Alexey Bataev758e55e2013-09-06 18:03:48 +000010296 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10297 // in a Construct]
10298 // Variables with the predetermined data-sharing attributes may not be
10299 // listed in data-sharing attributes clauses, except for the cases
10300 // listed below. For these exceptions only, listing a predetermined
10301 // variable in a data-sharing attribute clause is allowed and overrides
10302 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010303 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010304 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010305 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10306 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010307 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010308 continue;
10309 }
10310
Alexey Bataeve3727102018-04-18 15:57:46 +000010311 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010312 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010313 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010314 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010315 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10316 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010317 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010318 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010319 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010320 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010321 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010322 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010323 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010324 continue;
10325 }
10326
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010327 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10328 // A list item cannot appear in both a map clause and a data-sharing
10329 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010330 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010331 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010332 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010333 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010334 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10335 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10336 ConflictKind = WhereFoundClauseKind;
10337 return true;
10338 })) {
10339 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010340 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010341 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010342 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010343 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010344 continue;
10345 }
10346 }
10347
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010348 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10349 // A variable of class type (or array thereof) that appears in a private
10350 // clause requires an accessible, unambiguous default constructor for the
10351 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010352 // Generate helper private variable and initialize it with the default
10353 // value. The address of the original variable is replaced by the address of
10354 // the new private variable in CodeGen. This new variable is not added to
10355 // IdResolver, so the code in the OpenMP region uses original variable for
10356 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010357 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010358 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010359 buildVarDecl(*this, ELoc, Type, D->getName(),
10360 D->hasAttrs() ? &D->getAttrs() : nullptr,
10361 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010362 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010363 if (VDPrivate->isInvalidDecl())
10364 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010365 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010366 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010367
Alexey Bataev90c228f2016-02-08 09:29:13 +000010368 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010369 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010370 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010371 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010372 Vars.push_back((VD || CurContext->isDependentContext())
10373 ? RefExpr->IgnoreParens()
10374 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010375 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010376 }
10377
Alexey Bataeved09d242014-05-28 05:53:51 +000010378 if (Vars.empty())
10379 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010380
Alexey Bataev03b340a2014-10-21 03:16:40 +000010381 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10382 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010383}
10384
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010385namespace {
10386class DiagsUninitializedSeveretyRAII {
10387private:
10388 DiagnosticsEngine &Diags;
10389 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010390 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010391
10392public:
10393 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10394 bool IsIgnored)
10395 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10396 if (!IsIgnored) {
10397 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10398 /*Map*/ diag::Severity::Ignored, Loc);
10399 }
10400 }
10401 ~DiagsUninitializedSeveretyRAII() {
10402 if (!IsIgnored)
10403 Diags.popMappings(SavedLoc);
10404 }
10405};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010406}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010407
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010408OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10409 SourceLocation StartLoc,
10410 SourceLocation LParenLoc,
10411 SourceLocation EndLoc) {
10412 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010413 SmallVector<Expr *, 8> PrivateCopies;
10414 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010415 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010416 bool IsImplicitClause =
10417 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010418 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010419
Alexey Bataeve3727102018-04-18 15:57:46 +000010420 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010421 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010422 SourceLocation ELoc;
10423 SourceRange ERange;
10424 Expr *SimpleRefExpr = RefExpr;
10425 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010426 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010427 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010428 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010429 PrivateCopies.push_back(nullptr);
10430 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010431 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010432 ValueDecl *D = Res.first;
10433 if (!D)
10434 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010435
Alexey Bataev60da77e2016-02-29 05:54:20 +000010436 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010437 QualType Type = D->getType();
10438 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010439
10440 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10441 // A variable that appears in a private clause must not have an incomplete
10442 // type or a reference type.
10443 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010444 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010445 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010446 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010447
10448 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10449 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010450 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010451 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010452 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010453
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010454 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010455 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010456 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010457 DSAStackTy::DSAVarData DVar =
10458 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010459 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010460 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010461 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010462 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10463 // A list item that specifies a given variable may not appear in more
10464 // than one clause on the same directive, except that a variable may be
10465 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010466 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10467 // A list item may appear in a firstprivate or lastprivate clause but not
10468 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010469 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010470 (isOpenMPDistributeDirective(CurrDir) ||
10471 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010472 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010473 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010474 << getOpenMPClauseName(DVar.CKind)
10475 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010476 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010477 continue;
10478 }
10479
10480 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10481 // in a Construct]
10482 // Variables with the predetermined data-sharing attributes may not be
10483 // listed in data-sharing attributes clauses, except for the cases
10484 // listed below. For these exceptions only, listing a predetermined
10485 // variable in a data-sharing attribute clause is allowed and overrides
10486 // the variable's predetermined data-sharing attributes.
10487 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10488 // in a Construct, C/C++, p.2]
10489 // Variables with const-qualified type having no mutable member may be
10490 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010491 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010492 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10493 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010494 << getOpenMPClauseName(DVar.CKind)
10495 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010496 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010497 continue;
10498 }
10499
10500 // OpenMP [2.9.3.4, Restrictions, p.2]
10501 // A list item that is private within a parallel region must not appear
10502 // in a firstprivate clause on a worksharing construct if any of the
10503 // worksharing regions arising from the worksharing construct ever bind
10504 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010505 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10506 // A list item that is private within a teams region must not appear in a
10507 // firstprivate clause on a distribute construct if any of the distribute
10508 // regions arising from the distribute construct ever bind to any of the
10509 // teams regions arising from the teams construct.
10510 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10511 // A list item that appears in a reduction clause of a teams construct
10512 // must not appear in a firstprivate clause on a distribute construct if
10513 // any of the distribute regions arising from the distribute construct
10514 // ever bind to any of the teams regions arising from the teams construct.
10515 if ((isOpenMPWorksharingDirective(CurrDir) ||
10516 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010517 !isOpenMPParallelDirective(CurrDir) &&
10518 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010519 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010520 if (DVar.CKind != OMPC_shared &&
10521 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010522 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010523 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010524 Diag(ELoc, diag::err_omp_required_access)
10525 << getOpenMPClauseName(OMPC_firstprivate)
10526 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010527 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010528 continue;
10529 }
10530 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010531 // OpenMP [2.9.3.4, Restrictions, p.3]
10532 // A list item that appears in a reduction clause of a parallel construct
10533 // must not appear in a firstprivate clause on a worksharing or task
10534 // construct if any of the worksharing or task regions arising from the
10535 // worksharing or task construct ever bind to any of the parallel regions
10536 // arising from the parallel construct.
10537 // OpenMP [2.9.3.4, Restrictions, p.4]
10538 // A list item that appears in a reduction clause in worksharing
10539 // construct must not appear in a firstprivate clause in a task construct
10540 // encountered during execution of any of the worksharing regions arising
10541 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010542 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010543 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010544 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10545 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010546 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010547 isOpenMPWorksharingDirective(K) ||
10548 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010549 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010550 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010551 if (DVar.CKind == OMPC_reduction &&
10552 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010553 isOpenMPWorksharingDirective(DVar.DKind) ||
10554 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010555 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10556 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010557 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010558 continue;
10559 }
10560 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010561
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010562 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10563 // A list item cannot appear in both a map clause and a data-sharing
10564 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010565 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010566 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010567 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010568 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010569 [&ConflictKind](
10570 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10571 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010572 ConflictKind = WhereFoundClauseKind;
10573 return true;
10574 })) {
10575 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010576 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010577 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010578 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010579 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010580 continue;
10581 }
10582 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010583 }
10584
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010585 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010586 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010587 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010588 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10589 << getOpenMPClauseName(OMPC_firstprivate) << Type
10590 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10591 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010592 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010593 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010594 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010595 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010596 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010597 continue;
10598 }
10599
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010600 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010601 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010602 buildVarDecl(*this, ELoc, Type, D->getName(),
10603 D->hasAttrs() ? &D->getAttrs() : nullptr,
10604 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010605 // Generate helper private variable and initialize it with the value of the
10606 // original variable. The address of the original variable is replaced by
10607 // the address of the new private variable in the CodeGen. This new variable
10608 // is not added to IdResolver, so the code in the OpenMP region uses
10609 // original variable for proper diagnostics and variable capturing.
10610 Expr *VDInitRefExpr = nullptr;
10611 // For arrays generate initializer for single element and replace it by the
10612 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010613 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010614 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010615 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010616 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010617 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010618 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010619 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10620 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010621 InitializedEntity Entity =
10622 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010623 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10624
10625 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10626 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10627 if (Result.isInvalid())
10628 VDPrivate->setInvalidDecl();
10629 else
10630 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010631 // Remove temp variable declaration.
10632 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010633 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010634 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10635 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010636 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10637 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010638 AddInitializerToDecl(VDPrivate,
10639 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010640 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010641 }
10642 if (VDPrivate->isInvalidDecl()) {
10643 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010644 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010645 diag::note_omp_task_predetermined_firstprivate_here);
10646 }
10647 continue;
10648 }
10649 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010650 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010651 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10652 RefExpr->getExprLoc());
10653 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010654 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010655 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010656 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010657 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010658 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010659 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010660 ExprCaptures.push_back(Ref->getDecl());
10661 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010662 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010663 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010664 Vars.push_back((VD || CurContext->isDependentContext())
10665 ? RefExpr->IgnoreParens()
10666 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010667 PrivateCopies.push_back(VDPrivateRefExpr);
10668 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010669 }
10670
Alexey Bataeved09d242014-05-28 05:53:51 +000010671 if (Vars.empty())
10672 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010673
10674 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010675 Vars, PrivateCopies, Inits,
10676 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010677}
10678
Alexander Musman1bb328c2014-06-04 13:06:39 +000010679OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10680 SourceLocation StartLoc,
10681 SourceLocation LParenLoc,
10682 SourceLocation EndLoc) {
10683 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010684 SmallVector<Expr *, 8> SrcExprs;
10685 SmallVector<Expr *, 8> DstExprs;
10686 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010687 SmallVector<Decl *, 4> ExprCaptures;
10688 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010689 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010690 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010691 SourceLocation ELoc;
10692 SourceRange ERange;
10693 Expr *SimpleRefExpr = RefExpr;
10694 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010695 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010696 // It will be analyzed later.
10697 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010698 SrcExprs.push_back(nullptr);
10699 DstExprs.push_back(nullptr);
10700 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010701 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010702 ValueDecl *D = Res.first;
10703 if (!D)
10704 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010705
Alexey Bataev74caaf22016-02-20 04:09:36 +000010706 QualType Type = D->getType();
10707 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010708
10709 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10710 // A variable that appears in a lastprivate clause must not have an
10711 // incomplete type or a reference type.
10712 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010713 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010714 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010715 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010716
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010717 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10718 // A variable that is privatized must not have a const-qualified type
10719 // unless it is of class type with a mutable member. This restriction does
10720 // not apply to the firstprivate clause.
10721 //
10722 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10723 // A variable that appears in a lastprivate clause must not have a
10724 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010725 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010726 continue;
10727
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010728 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010729 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10730 // in a Construct]
10731 // Variables with the predetermined data-sharing attributes may not be
10732 // listed in data-sharing attributes clauses, except for the cases
10733 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010734 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10735 // A list item may appear in a firstprivate or lastprivate clause but not
10736 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010737 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010738 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010739 (isOpenMPDistributeDirective(CurrDir) ||
10740 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010741 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10742 Diag(ELoc, diag::err_omp_wrong_dsa)
10743 << getOpenMPClauseName(DVar.CKind)
10744 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010745 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010746 continue;
10747 }
10748
Alexey Bataevf29276e2014-06-18 04:14:57 +000010749 // OpenMP [2.14.3.5, Restrictions, p.2]
10750 // A list item that is private within a parallel region, or that appears in
10751 // the reduction clause of a parallel construct, must not appear in a
10752 // lastprivate clause on a worksharing construct if any of the corresponding
10753 // worksharing regions ever binds to any of the corresponding parallel
10754 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010755 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010756 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010757 !isOpenMPParallelDirective(CurrDir) &&
10758 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010759 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010760 if (DVar.CKind != OMPC_shared) {
10761 Diag(ELoc, diag::err_omp_required_access)
10762 << getOpenMPClauseName(OMPC_lastprivate)
10763 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010764 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010765 continue;
10766 }
10767 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010768
Alexander Musman1bb328c2014-06-04 13:06:39 +000010769 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010770 // A variable of class type (or array thereof) that appears in a
10771 // lastprivate clause requires an accessible, unambiguous default
10772 // constructor for the class type, unless the list item is also specified
10773 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010774 // A variable of class type (or array thereof) that appears in a
10775 // lastprivate clause requires an accessible, unambiguous copy assignment
10776 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010777 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010778 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10779 Type.getUnqualifiedType(), ".lastprivate.src",
10780 D->hasAttrs() ? &D->getAttrs() : nullptr);
10781 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010782 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010783 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010784 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010785 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010786 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010787 // For arrays generate assignment operation for single element and replace
10788 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010789 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10790 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010791 if (AssignmentOp.isInvalid())
10792 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010793 AssignmentOp =
10794 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010795 if (AssignmentOp.isInvalid())
10796 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010797
Alexey Bataev74caaf22016-02-20 04:09:36 +000010798 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010799 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010800 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010801 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010802 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010803 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010804 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010805 ExprCaptures.push_back(Ref->getDecl());
10806 }
10807 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010808 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010809 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010810 ExprResult RefRes = DefaultLvalueConversion(Ref);
10811 if (!RefRes.isUsable())
10812 continue;
10813 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010814 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10815 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010816 if (!PostUpdateRes.isUsable())
10817 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010818 ExprPostUpdates.push_back(
10819 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010820 }
10821 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010822 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010823 Vars.push_back((VD || CurContext->isDependentContext())
10824 ? RefExpr->IgnoreParens()
10825 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010826 SrcExprs.push_back(PseudoSrcExpr);
10827 DstExprs.push_back(PseudoDstExpr);
10828 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010829 }
10830
10831 if (Vars.empty())
10832 return nullptr;
10833
10834 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010835 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010836 buildPreInits(Context, ExprCaptures),
10837 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010838}
10839
Alexey Bataev758e55e2013-09-06 18:03:48 +000010840OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10841 SourceLocation StartLoc,
10842 SourceLocation LParenLoc,
10843 SourceLocation EndLoc) {
10844 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010845 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010846 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010847 SourceLocation ELoc;
10848 SourceRange ERange;
10849 Expr *SimpleRefExpr = RefExpr;
10850 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010851 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010852 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010853 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010854 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010855 ValueDecl *D = Res.first;
10856 if (!D)
10857 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010858
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010859 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010860 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10861 // in a Construct]
10862 // Variables with the predetermined data-sharing attributes may not be
10863 // listed in data-sharing attributes clauses, except for the cases
10864 // listed below. For these exceptions only, listing a predetermined
10865 // variable in a data-sharing attribute clause is allowed and overrides
10866 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010867 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010868 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10869 DVar.RefExpr) {
10870 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10871 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010872 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010873 continue;
10874 }
10875
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010876 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010877 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010878 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010879 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010880 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10881 ? RefExpr->IgnoreParens()
10882 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010883 }
10884
Alexey Bataeved09d242014-05-28 05:53:51 +000010885 if (Vars.empty())
10886 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010887
10888 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10889}
10890
Alexey Bataevc5e02582014-06-16 07:08:35 +000010891namespace {
10892class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10893 DSAStackTy *Stack;
10894
10895public:
10896 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010897 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10898 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010899 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10900 return false;
10901 if (DVar.CKind != OMPC_unknown)
10902 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010903 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010904 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010905 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010906 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010907 }
10908 return false;
10909 }
10910 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010911 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010912 if (Child && Visit(Child))
10913 return true;
10914 }
10915 return false;
10916 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010917 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010918};
Alexey Bataev23b69422014-06-18 07:08:49 +000010919} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010920
Alexey Bataev60da77e2016-02-29 05:54:20 +000010921namespace {
10922// Transform MemberExpression for specified FieldDecl of current class to
10923// DeclRefExpr to specified OMPCapturedExprDecl.
10924class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10925 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010926 ValueDecl *Field = nullptr;
10927 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010928
10929public:
10930 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10931 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10932
10933 ExprResult TransformMemberExpr(MemberExpr *E) {
10934 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10935 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010936 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010937 return CapturedExpr;
10938 }
10939 return BaseTransform::TransformMemberExpr(E);
10940 }
10941 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10942};
10943} // namespace
10944
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010945template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010946static T filterLookupForUDReductionAndMapper(
10947 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010948 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010949 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010950 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010951 return Res;
10952 }
10953 }
10954 return T();
10955}
10956
Alexey Bataev43b90b72018-09-12 16:31:59 +000010957static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10958 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10959
10960 for (auto RD : D->redecls()) {
10961 // Don't bother with extra checks if we already know this one isn't visible.
10962 if (RD == D)
10963 continue;
10964
10965 auto ND = cast<NamedDecl>(RD);
10966 if (LookupResult::isVisible(SemaRef, ND))
10967 return ND;
10968 }
10969
10970 return nullptr;
10971}
10972
10973static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010974argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010975 SourceLocation Loc, QualType Ty,
10976 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10977 // Find all of the associated namespaces and classes based on the
10978 // arguments we have.
10979 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10980 Sema::AssociatedClassSet AssociatedClasses;
10981 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10982 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10983 AssociatedClasses);
10984
10985 // C++ [basic.lookup.argdep]p3:
10986 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10987 // and let Y be the lookup set produced by argument dependent
10988 // lookup (defined as follows). If X contains [...] then Y is
10989 // empty. Otherwise Y is the set of declarations found in the
10990 // namespaces associated with the argument types as described
10991 // below. The set of declarations found by the lookup of the name
10992 // is the union of X and Y.
10993 //
10994 // Here, we compute Y and add its members to the overloaded
10995 // candidate set.
10996 for (auto *NS : AssociatedNamespaces) {
10997 // When considering an associated namespace, the lookup is the
10998 // same as the lookup performed when the associated namespace is
10999 // used as a qualifier (3.4.3.2) except that:
11000 //
11001 // -- Any using-directives in the associated namespace are
11002 // ignored.
11003 //
11004 // -- Any namespace-scope friend functions declared in
11005 // associated classes are visible within their respective
11006 // namespaces even if they are not visible during an ordinary
11007 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011008 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011009 for (auto *D : R) {
11010 auto *Underlying = D;
11011 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11012 Underlying = USD->getTargetDecl();
11013
Michael Kruse4304e9d2019-02-19 16:38:20 +000011014 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11015 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011016 continue;
11017
11018 if (!SemaRef.isVisible(D)) {
11019 D = findAcceptableDecl(SemaRef, D);
11020 if (!D)
11021 continue;
11022 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11023 Underlying = USD->getTargetDecl();
11024 }
11025 Lookups.emplace_back();
11026 Lookups.back().addDecl(Underlying);
11027 }
11028 }
11029}
11030
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011031static ExprResult
11032buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11033 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11034 const DeclarationNameInfo &ReductionId, QualType Ty,
11035 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11036 if (ReductionIdScopeSpec.isInvalid())
11037 return ExprError();
11038 SmallVector<UnresolvedSet<8>, 4> Lookups;
11039 if (S) {
11040 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11041 Lookup.suppressDiagnostics();
11042 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011043 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011044 do {
11045 S = S->getParent();
11046 } while (S && !S->isDeclScope(D));
11047 if (S)
11048 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011049 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011050 Lookups.back().append(Lookup.begin(), Lookup.end());
11051 Lookup.clear();
11052 }
11053 } else if (auto *ULE =
11054 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11055 Lookups.push_back(UnresolvedSet<8>());
11056 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011057 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011058 if (D == PrevD)
11059 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011060 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011061 Lookups.back().addDecl(DRD);
11062 PrevD = D;
11063 }
11064 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011065 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11066 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011067 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011068 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011069 return !D->isInvalidDecl() &&
11070 (D->getType()->isDependentType() ||
11071 D->getType()->isInstantiationDependentType() ||
11072 D->getType()->containsUnexpandedParameterPack());
11073 })) {
11074 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011075 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011076 if (Set.empty())
11077 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011078 ResSet.append(Set.begin(), Set.end());
11079 // The last item marks the end of all declarations at the specified scope.
11080 ResSet.addDecl(Set[Set.size() - 1]);
11081 }
11082 return UnresolvedLookupExpr::Create(
11083 SemaRef.Context, /*NamingClass=*/nullptr,
11084 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11085 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11086 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011087 // Lookup inside the classes.
11088 // C++ [over.match.oper]p3:
11089 // For a unary operator @ with an operand of a type whose
11090 // cv-unqualified version is T1, and for a binary operator @ with
11091 // a left operand of a type whose cv-unqualified version is T1 and
11092 // a right operand of a type whose cv-unqualified version is T2,
11093 // three sets of candidate functions, designated member
11094 // candidates, non-member candidates and built-in candidates, are
11095 // constructed as follows:
11096 // -- If T1 is a complete class type or a class currently being
11097 // defined, the set of member candidates is the result of the
11098 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11099 // the set of member candidates is empty.
11100 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11101 Lookup.suppressDiagnostics();
11102 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11103 // Complete the type if it can be completed.
11104 // If the type is neither complete nor being defined, bail out now.
11105 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11106 TyRec->getDecl()->getDefinition()) {
11107 Lookup.clear();
11108 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11109 if (Lookup.empty()) {
11110 Lookups.emplace_back();
11111 Lookups.back().append(Lookup.begin(), Lookup.end());
11112 }
11113 }
11114 }
11115 // Perform ADL.
Alexey Bataev74a04e82019-03-13 19:31:34 +000011116 if (SemaRef.getLangOpts().CPlusPlus) {
11117 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11118 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11119 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11120 if (!D->isInvalidDecl() &&
11121 SemaRef.Context.hasSameType(D->getType(), Ty))
11122 return D;
11123 return nullptr;
11124 }))
11125 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11126 VK_LValue, Loc);
11127 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11128 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11129 if (!D->isInvalidDecl() &&
11130 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11131 !Ty.isMoreQualifiedThan(D->getType()))
11132 return D;
11133 return nullptr;
11134 })) {
11135 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11136 /*DetectVirtual=*/false);
11137 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11138 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11139 VD->getType().getUnqualifiedType()))) {
11140 if (SemaRef.CheckBaseClassAccess(
11141 Loc, VD->getType(), Ty, Paths.front(),
11142 /*DiagID=*/0) != Sema::AR_inaccessible) {
11143 SemaRef.BuildBasePathArray(Paths, BasePath);
11144 return SemaRef.BuildDeclRefExpr(
11145 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11146 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011147 }
11148 }
11149 }
11150 }
11151 if (ReductionIdScopeSpec.isSet()) {
11152 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11153 return ExprError();
11154 }
11155 return ExprEmpty();
11156}
11157
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011158namespace {
11159/// Data for the reduction-based clauses.
11160struct ReductionData {
11161 /// List of original reduction items.
11162 SmallVector<Expr *, 8> Vars;
11163 /// List of private copies of the reduction items.
11164 SmallVector<Expr *, 8> Privates;
11165 /// LHS expressions for the reduction_op expressions.
11166 SmallVector<Expr *, 8> LHSs;
11167 /// RHS expressions for the reduction_op expressions.
11168 SmallVector<Expr *, 8> RHSs;
11169 /// Reduction operation expression.
11170 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011171 /// Taskgroup descriptors for the corresponding reduction items in
11172 /// in_reduction clauses.
11173 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011174 /// List of captures for clause.
11175 SmallVector<Decl *, 4> ExprCaptures;
11176 /// List of postupdate expressions.
11177 SmallVector<Expr *, 4> ExprPostUpdates;
11178 ReductionData() = delete;
11179 /// Reserves required memory for the reduction data.
11180 ReductionData(unsigned Size) {
11181 Vars.reserve(Size);
11182 Privates.reserve(Size);
11183 LHSs.reserve(Size);
11184 RHSs.reserve(Size);
11185 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011186 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011187 ExprCaptures.reserve(Size);
11188 ExprPostUpdates.reserve(Size);
11189 }
11190 /// Stores reduction item and reduction operation only (required for dependent
11191 /// reduction item).
11192 void push(Expr *Item, Expr *ReductionOp) {
11193 Vars.emplace_back(Item);
11194 Privates.emplace_back(nullptr);
11195 LHSs.emplace_back(nullptr);
11196 RHSs.emplace_back(nullptr);
11197 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011198 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011199 }
11200 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011201 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11202 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011203 Vars.emplace_back(Item);
11204 Privates.emplace_back(Private);
11205 LHSs.emplace_back(LHS);
11206 RHSs.emplace_back(RHS);
11207 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011208 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011209 }
11210};
11211} // namespace
11212
Alexey Bataeve3727102018-04-18 15:57:46 +000011213static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011214 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11215 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11216 const Expr *Length = OASE->getLength();
11217 if (Length == nullptr) {
11218 // For array sections of the form [1:] or [:], we would need to analyze
11219 // the lower bound...
11220 if (OASE->getColonLoc().isValid())
11221 return false;
11222
11223 // This is an array subscript which has implicit length 1!
11224 SingleElement = true;
11225 ArraySizes.push_back(llvm::APSInt::get(1));
11226 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011227 Expr::EvalResult Result;
11228 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011229 return false;
11230
Fangrui Song407659a2018-11-30 23:41:18 +000011231 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011232 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11233 ArraySizes.push_back(ConstantLengthValue);
11234 }
11235
11236 // Get the base of this array section and walk up from there.
11237 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11238
11239 // We require length = 1 for all array sections except the right-most to
11240 // guarantee that the memory region is contiguous and has no holes in it.
11241 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11242 Length = TempOASE->getLength();
11243 if (Length == nullptr) {
11244 // For array sections of the form [1:] or [:], we would need to analyze
11245 // the lower bound...
11246 if (OASE->getColonLoc().isValid())
11247 return false;
11248
11249 // This is an array subscript which has implicit length 1!
11250 ArraySizes.push_back(llvm::APSInt::get(1));
11251 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011252 Expr::EvalResult Result;
11253 if (!Length->EvaluateAsInt(Result, Context))
11254 return false;
11255
11256 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11257 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011258 return false;
11259
11260 ArraySizes.push_back(ConstantLengthValue);
11261 }
11262 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11263 }
11264
11265 // If we have a single element, we don't need to add the implicit lengths.
11266 if (!SingleElement) {
11267 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11268 // Has implicit length 1!
11269 ArraySizes.push_back(llvm::APSInt::get(1));
11270 Base = TempASE->getBase()->IgnoreParenImpCasts();
11271 }
11272 }
11273
11274 // This array section can be privatized as a single value or as a constant
11275 // sized array.
11276 return true;
11277}
11278
Alexey Bataeve3727102018-04-18 15:57:46 +000011279static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011280 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11281 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11282 SourceLocation ColonLoc, SourceLocation EndLoc,
11283 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011284 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011285 DeclarationName DN = ReductionId.getName();
11286 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011287 BinaryOperatorKind BOK = BO_Comma;
11288
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011289 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011290 // OpenMP [2.14.3.6, reduction clause]
11291 // C
11292 // reduction-identifier is either an identifier or one of the following
11293 // operators: +, -, *, &, |, ^, && and ||
11294 // C++
11295 // reduction-identifier is either an id-expression or one of the following
11296 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011297 switch (OOK) {
11298 case OO_Plus:
11299 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011300 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011301 break;
11302 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011303 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011304 break;
11305 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011306 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011307 break;
11308 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011309 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011310 break;
11311 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011312 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011313 break;
11314 case OO_AmpAmp:
11315 BOK = BO_LAnd;
11316 break;
11317 case OO_PipePipe:
11318 BOK = BO_LOr;
11319 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011320 case OO_New:
11321 case OO_Delete:
11322 case OO_Array_New:
11323 case OO_Array_Delete:
11324 case OO_Slash:
11325 case OO_Percent:
11326 case OO_Tilde:
11327 case OO_Exclaim:
11328 case OO_Equal:
11329 case OO_Less:
11330 case OO_Greater:
11331 case OO_LessEqual:
11332 case OO_GreaterEqual:
11333 case OO_PlusEqual:
11334 case OO_MinusEqual:
11335 case OO_StarEqual:
11336 case OO_SlashEqual:
11337 case OO_PercentEqual:
11338 case OO_CaretEqual:
11339 case OO_AmpEqual:
11340 case OO_PipeEqual:
11341 case OO_LessLess:
11342 case OO_GreaterGreater:
11343 case OO_LessLessEqual:
11344 case OO_GreaterGreaterEqual:
11345 case OO_EqualEqual:
11346 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011347 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011348 case OO_PlusPlus:
11349 case OO_MinusMinus:
11350 case OO_Comma:
11351 case OO_ArrowStar:
11352 case OO_Arrow:
11353 case OO_Call:
11354 case OO_Subscript:
11355 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011356 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011357 case NUM_OVERLOADED_OPERATORS:
11358 llvm_unreachable("Unexpected reduction identifier");
11359 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011360 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011361 if (II->isStr("max"))
11362 BOK = BO_GT;
11363 else if (II->isStr("min"))
11364 BOK = BO_LT;
11365 }
11366 break;
11367 }
11368 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011369 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011370 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011371 else
11372 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011373 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011374
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011375 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11376 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011377 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011378 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011379 // OpenMP [2.1, C/C++]
11380 // A list item is a variable or array section, subject to the restrictions
11381 // specified in Section 2.4 on page 42 and in each of the sections
11382 // describing clauses and directives for which a list appears.
11383 // OpenMP [2.14.3.3, Restrictions, p.1]
11384 // A variable that is part of another variable (as an array or
11385 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011386 if (!FirstIter && IR != ER)
11387 ++IR;
11388 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011389 SourceLocation ELoc;
11390 SourceRange ERange;
11391 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011392 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011393 /*AllowArraySection=*/true);
11394 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011395 // Try to find 'declare reduction' corresponding construct before using
11396 // builtin/overloaded operators.
11397 QualType Type = Context.DependentTy;
11398 CXXCastPath BasePath;
11399 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011400 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011401 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011402 Expr *ReductionOp = nullptr;
11403 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011404 (DeclareReductionRef.isUnset() ||
11405 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011406 ReductionOp = DeclareReductionRef.get();
11407 // It will be analyzed later.
11408 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011409 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011410 ValueDecl *D = Res.first;
11411 if (!D)
11412 continue;
11413
Alexey Bataev88202be2017-07-27 13:20:36 +000011414 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011415 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011416 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11417 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011418 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011419 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011420 } else if (OASE) {
11421 QualType BaseType =
11422 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11423 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011424 Type = ATy->getElementType();
11425 else
11426 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011427 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011428 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011429 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011430 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011431 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011432
Alexey Bataevc5e02582014-06-16 07:08:35 +000011433 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11434 // A variable that appears in a private clause must not have an incomplete
11435 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011436 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011437 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011438 continue;
11439 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011440 // A list item that appears in a reduction clause must not be
11441 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011442 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11443 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011444 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011445
11446 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011447 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11448 // If a list-item is a reference type then it must bind to the same object
11449 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011450 if (!ASE && !OASE) {
11451 if (VD) {
11452 VarDecl *VDDef = VD->getDefinition();
11453 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11454 DSARefChecker Check(Stack);
11455 if (Check.Visit(VDDef->getInit())) {
11456 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11457 << getOpenMPClauseName(ClauseKind) << ERange;
11458 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11459 continue;
11460 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011461 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011462 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011463
Alexey Bataevbc529672018-09-28 19:33:14 +000011464 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11465 // in a Construct]
11466 // Variables with the predetermined data-sharing attributes may not be
11467 // listed in data-sharing attributes clauses, except for the cases
11468 // listed below. For these exceptions only, listing a predetermined
11469 // variable in a data-sharing attribute clause is allowed and overrides
11470 // the variable's predetermined data-sharing attributes.
11471 // OpenMP [2.14.3.6, Restrictions, p.3]
11472 // Any number of reduction clauses can be specified on the directive,
11473 // but a list item can appear only once in the reduction clauses for that
11474 // directive.
11475 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11476 if (DVar.CKind == OMPC_reduction) {
11477 S.Diag(ELoc, diag::err_omp_once_referenced)
11478 << getOpenMPClauseName(ClauseKind);
11479 if (DVar.RefExpr)
11480 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11481 continue;
11482 }
11483 if (DVar.CKind != OMPC_unknown) {
11484 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11485 << getOpenMPClauseName(DVar.CKind)
11486 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011487 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011488 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011489 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011490
11491 // OpenMP [2.14.3.6, Restrictions, p.1]
11492 // A list item that appears in a reduction clause of a worksharing
11493 // construct must be shared in the parallel regions to which any of the
11494 // worksharing regions arising from the worksharing construct bind.
11495 if (isOpenMPWorksharingDirective(CurrDir) &&
11496 !isOpenMPParallelDirective(CurrDir) &&
11497 !isOpenMPTeamsDirective(CurrDir)) {
11498 DVar = Stack->getImplicitDSA(D, true);
11499 if (DVar.CKind != OMPC_shared) {
11500 S.Diag(ELoc, diag::err_omp_required_access)
11501 << getOpenMPClauseName(OMPC_reduction)
11502 << getOpenMPClauseName(OMPC_shared);
11503 reportOriginalDsa(S, Stack, D, DVar);
11504 continue;
11505 }
11506 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011507 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011508
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011509 // Try to find 'declare reduction' corresponding construct before using
11510 // builtin/overloaded operators.
11511 CXXCastPath BasePath;
11512 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011513 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011514 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11515 if (DeclareReductionRef.isInvalid())
11516 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011517 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011518 (DeclareReductionRef.isUnset() ||
11519 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011520 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011521 continue;
11522 }
11523 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11524 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011525 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011526 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011527 << Type << ReductionIdRange;
11528 continue;
11529 }
11530
11531 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11532 // The type of a list item that appears in a reduction clause must be valid
11533 // for the reduction-identifier. For a max or min reduction in C, the type
11534 // of the list item must be an allowed arithmetic data type: char, int,
11535 // float, double, or _Bool, possibly modified with long, short, signed, or
11536 // unsigned. For a max or min reduction in C++, the type of the list item
11537 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11538 // double, or bool, possibly modified with long, short, signed, or unsigned.
11539 if (DeclareReductionRef.isUnset()) {
11540 if ((BOK == BO_GT || BOK == BO_LT) &&
11541 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011542 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11543 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011544 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011545 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011546 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11547 VarDecl::DeclarationOnly;
11548 S.Diag(D->getLocation(),
11549 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011550 << D;
11551 }
11552 continue;
11553 }
11554 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011555 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011556 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11557 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011558 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011559 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11560 VarDecl::DeclarationOnly;
11561 S.Diag(D->getLocation(),
11562 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011563 << D;
11564 }
11565 continue;
11566 }
11567 }
11568
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011569 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011570 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11571 D->hasAttrs() ? &D->getAttrs() : nullptr);
11572 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11573 D->hasAttrs() ? &D->getAttrs() : nullptr);
11574 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011575
11576 // Try if we can determine constant lengths for all array sections and avoid
11577 // the VLA.
11578 bool ConstantLengthOASE = false;
11579 if (OASE) {
11580 bool SingleElement;
11581 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011582 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011583 Context, OASE, SingleElement, ArraySizes);
11584
11585 // If we don't have a single element, we must emit a constant array type.
11586 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011587 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011588 PrivateTy = Context.getConstantArrayType(
11589 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011590 }
11591 }
11592
11593 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011594 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011595 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011596 if (!Context.getTargetInfo().isVLASupported() &&
11597 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11598 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11599 S.Diag(ELoc, diag::note_vla_unsupported);
11600 continue;
11601 }
David Majnemer9d168222016-08-05 17:44:54 +000011602 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011603 // Create pseudo array type for private copy. The size for this array will
11604 // be generated during codegen.
11605 // For array subscripts or single variables Private Ty is the same as Type
11606 // (type of the variable or single array element).
11607 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011608 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011609 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011610 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011611 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011612 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011613 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011614 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011615 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011616 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011617 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11618 D->hasAttrs() ? &D->getAttrs() : nullptr,
11619 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011620 // Add initializer for private variable.
11621 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011622 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11623 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011624 if (DeclareReductionRef.isUsable()) {
11625 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11626 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11627 if (DRD->getInitializer()) {
11628 Init = DRDRef;
11629 RHSVD->setInit(DRDRef);
11630 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011631 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011632 } else {
11633 switch (BOK) {
11634 case BO_Add:
11635 case BO_Xor:
11636 case BO_Or:
11637 case BO_LOr:
11638 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11639 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011640 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011641 break;
11642 case BO_Mul:
11643 case BO_LAnd:
11644 if (Type->isScalarType() || Type->isAnyComplexType()) {
11645 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011646 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011647 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011648 break;
11649 case BO_And: {
11650 // '&' reduction op - initializer is '~0'.
11651 QualType OrigType = Type;
11652 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11653 Type = ComplexTy->getElementType();
11654 if (Type->isRealFloatingType()) {
11655 llvm::APFloat InitValue =
11656 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11657 /*isIEEE=*/true);
11658 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11659 Type, ELoc);
11660 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011661 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011662 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11663 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11664 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11665 }
11666 if (Init && OrigType->isAnyComplexType()) {
11667 // Init = 0xFFFF + 0xFFFFi;
11668 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011669 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011670 }
11671 Type = OrigType;
11672 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011673 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011674 case BO_LT:
11675 case BO_GT: {
11676 // 'min' reduction op - initializer is 'Largest representable number in
11677 // the reduction list item type'.
11678 // 'max' reduction op - initializer is 'Least representable number in
11679 // the reduction list item type'.
11680 if (Type->isIntegerType() || Type->isPointerType()) {
11681 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011682 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011683 QualType IntTy =
11684 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11685 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011686 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11687 : llvm::APInt::getMinValue(Size)
11688 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11689 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011690 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11691 if (Type->isPointerType()) {
11692 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011693 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011694 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011695 if (CastExpr.isInvalid())
11696 continue;
11697 Init = CastExpr.get();
11698 }
11699 } else if (Type->isRealFloatingType()) {
11700 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11701 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11702 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11703 Type, ELoc);
11704 }
11705 break;
11706 }
11707 case BO_PtrMemD:
11708 case BO_PtrMemI:
11709 case BO_MulAssign:
11710 case BO_Div:
11711 case BO_Rem:
11712 case BO_Sub:
11713 case BO_Shl:
11714 case BO_Shr:
11715 case BO_LE:
11716 case BO_GE:
11717 case BO_EQ:
11718 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011719 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011720 case BO_AndAssign:
11721 case BO_XorAssign:
11722 case BO_OrAssign:
11723 case BO_Assign:
11724 case BO_AddAssign:
11725 case BO_SubAssign:
11726 case BO_DivAssign:
11727 case BO_RemAssign:
11728 case BO_ShlAssign:
11729 case BO_ShrAssign:
11730 case BO_Comma:
11731 llvm_unreachable("Unexpected reduction operation");
11732 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011733 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011734 if (Init && DeclareReductionRef.isUnset())
11735 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11736 else if (!Init)
11737 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011738 if (RHSVD->isInvalidDecl())
11739 continue;
11740 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011741 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11742 << Type << ReductionIdRange;
11743 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11744 VarDecl::DeclarationOnly;
11745 S.Diag(D->getLocation(),
11746 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011747 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011748 continue;
11749 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011750 // Store initializer for single element in private copy. Will be used during
11751 // codegen.
11752 PrivateVD->setInit(RHSVD->getInit());
11753 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011754 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011755 ExprResult ReductionOp;
11756 if (DeclareReductionRef.isUsable()) {
11757 QualType RedTy = DeclareReductionRef.get()->getType();
11758 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011759 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11760 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011761 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011762 LHS = S.DefaultLvalueConversion(LHS.get());
11763 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011764 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11765 CK_UncheckedDerivedToBase, LHS.get(),
11766 &BasePath, LHS.get()->getValueKind());
11767 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11768 CK_UncheckedDerivedToBase, RHS.get(),
11769 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011770 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011771 FunctionProtoType::ExtProtoInfo EPI;
11772 QualType Params[] = {PtrRedTy, PtrRedTy};
11773 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11774 auto *OVE = new (Context) OpaqueValueExpr(
11775 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011776 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011777 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011778 ReductionOp =
11779 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011780 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011781 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011782 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011783 if (ReductionOp.isUsable()) {
11784 if (BOK != BO_LT && BOK != BO_GT) {
11785 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011786 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011787 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011788 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011789 auto *ConditionalOp = new (Context)
11790 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11791 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011792 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011793 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011794 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011795 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011796 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011797 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11798 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011799 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011800 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011801 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011802 }
11803
Alexey Bataevfa312f32017-07-21 18:48:21 +000011804 // OpenMP [2.15.4.6, Restrictions, p.2]
11805 // A list item that appears in an in_reduction clause of a task construct
11806 // must appear in a task_reduction clause of a construct associated with a
11807 // taskgroup region that includes the participating task in its taskgroup
11808 // set. The construct associated with the innermost region that meets this
11809 // condition must specify the same reduction-identifier as the in_reduction
11810 // clause.
11811 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011812 SourceRange ParentSR;
11813 BinaryOperatorKind ParentBOK;
11814 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011815 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011816 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011817 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11818 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011819 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011820 Stack->getTopMostTaskgroupReductionData(
11821 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011822 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11823 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11824 if (!IsParentBOK && !IsParentReductionOp) {
11825 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11826 continue;
11827 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011828 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11829 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11830 IsParentReductionOp) {
11831 bool EmitError = true;
11832 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11833 llvm::FoldingSetNodeID RedId, ParentRedId;
11834 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11835 DeclareReductionRef.get()->Profile(RedId, Context,
11836 /*Canonical=*/true);
11837 EmitError = RedId != ParentRedId;
11838 }
11839 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011840 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011841 diag::err_omp_reduction_identifier_mismatch)
11842 << ReductionIdRange << RefExpr->getSourceRange();
11843 S.Diag(ParentSR.getBegin(),
11844 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011845 << ParentSR
11846 << (IsParentBOK ? ParentBOKDSA.RefExpr
11847 : ParentReductionOpDSA.RefExpr)
11848 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011849 continue;
11850 }
11851 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011852 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11853 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011854 }
11855
Alexey Bataev60da77e2016-02-29 05:54:20 +000011856 DeclRefExpr *Ref = nullptr;
11857 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011858 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011859 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011860 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011861 VarsExpr =
11862 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11863 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011864 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011865 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011866 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011867 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011868 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011869 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011870 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011871 if (!RefRes.isUsable())
11872 continue;
11873 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011874 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11875 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011876 if (!PostUpdateRes.isUsable())
11877 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011878 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11879 Stack->getCurrentDirective() == OMPD_taskgroup) {
11880 S.Diag(RefExpr->getExprLoc(),
11881 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011882 << RefExpr->getSourceRange();
11883 continue;
11884 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011885 RD.ExprPostUpdates.emplace_back(
11886 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011887 }
11888 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011889 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011890 // All reduction items are still marked as reduction (to do not increase
11891 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011892 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011893 if (CurrDir == OMPD_taskgroup) {
11894 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011895 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11896 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011897 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011898 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011899 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011900 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11901 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011902 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011903 return RD.Vars.empty();
11904}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011905
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011906OMPClause *Sema::ActOnOpenMPReductionClause(
11907 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11908 SourceLocation ColonLoc, SourceLocation EndLoc,
11909 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11910 ArrayRef<Expr *> UnresolvedReductions) {
11911 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011912 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011913 StartLoc, LParenLoc, ColonLoc, EndLoc,
11914 ReductionIdScopeSpec, ReductionId,
11915 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011916 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011917
Alexey Bataevc5e02582014-06-16 07:08:35 +000011918 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011919 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11920 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11921 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11922 buildPreInits(Context, RD.ExprCaptures),
11923 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011924}
11925
Alexey Bataev169d96a2017-07-18 20:17:46 +000011926OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11927 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11928 SourceLocation ColonLoc, SourceLocation EndLoc,
11929 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11930 ArrayRef<Expr *> UnresolvedReductions) {
11931 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011932 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11933 StartLoc, LParenLoc, ColonLoc, EndLoc,
11934 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011935 UnresolvedReductions, RD))
11936 return nullptr;
11937
11938 return OMPTaskReductionClause::Create(
11939 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11940 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11941 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11942 buildPreInits(Context, RD.ExprCaptures),
11943 buildPostUpdate(*this, RD.ExprPostUpdates));
11944}
11945
Alexey Bataevfa312f32017-07-21 18:48:21 +000011946OMPClause *Sema::ActOnOpenMPInReductionClause(
11947 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11948 SourceLocation ColonLoc, SourceLocation EndLoc,
11949 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11950 ArrayRef<Expr *> UnresolvedReductions) {
11951 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011952 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011953 StartLoc, LParenLoc, ColonLoc, EndLoc,
11954 ReductionIdScopeSpec, ReductionId,
11955 UnresolvedReductions, RD))
11956 return nullptr;
11957
11958 return OMPInReductionClause::Create(
11959 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11960 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011961 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011962 buildPreInits(Context, RD.ExprCaptures),
11963 buildPostUpdate(*this, RD.ExprPostUpdates));
11964}
11965
Alexey Bataevecba70f2016-04-12 11:02:11 +000011966bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11967 SourceLocation LinLoc) {
11968 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11969 LinKind == OMPC_LINEAR_unknown) {
11970 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11971 return true;
11972 }
11973 return false;
11974}
11975
Alexey Bataeve3727102018-04-18 15:57:46 +000011976bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011977 OpenMPLinearClauseKind LinKind,
11978 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011979 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011980 // A variable must not have an incomplete type or a reference type.
11981 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11982 return true;
11983 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11984 !Type->isReferenceType()) {
11985 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11986 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11987 return true;
11988 }
11989 Type = Type.getNonReferenceType();
11990
Joel E. Dennybae586f2019-01-04 22:12:13 +000011991 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11992 // A variable that is privatized must not have a const-qualified type
11993 // unless it is of class type with a mutable member. This restriction does
11994 // not apply to the firstprivate clause.
11995 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011996 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011997
11998 // A list item must be of integral or pointer type.
11999 Type = Type.getUnqualifiedType().getCanonicalType();
12000 const auto *Ty = Type.getTypePtrOrNull();
12001 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12002 !Ty->isPointerType())) {
12003 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12004 if (D) {
12005 bool IsDecl =
12006 !VD ||
12007 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12008 Diag(D->getLocation(),
12009 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12010 << D;
12011 }
12012 return true;
12013 }
12014 return false;
12015}
12016
Alexey Bataev182227b2015-08-20 10:54:39 +000012017OMPClause *Sema::ActOnOpenMPLinearClause(
12018 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12019 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12020 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012021 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012022 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012023 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012024 SmallVector<Decl *, 4> ExprCaptures;
12025 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012026 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012027 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012028 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012029 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012030 SourceLocation ELoc;
12031 SourceRange ERange;
12032 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012033 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012034 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012035 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012036 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012037 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012038 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012039 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012040 ValueDecl *D = Res.first;
12041 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012042 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012043
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012044 QualType Type = D->getType();
12045 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012046
12047 // OpenMP [2.14.3.7, linear clause]
12048 // A list-item cannot appear in more than one linear clause.
12049 // A list-item that appears in a linear clause cannot appear in any
12050 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012051 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012052 if (DVar.RefExpr) {
12053 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12054 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012055 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012056 continue;
12057 }
12058
Alexey Bataevecba70f2016-04-12 11:02:11 +000012059 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012060 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012061 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012062
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012063 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012064 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012065 buildVarDecl(*this, ELoc, Type, D->getName(),
12066 D->hasAttrs() ? &D->getAttrs() : nullptr,
12067 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012068 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012069 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012070 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012071 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012072 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012073 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012074 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012075 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012076 ExprCaptures.push_back(Ref->getDecl());
12077 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12078 ExprResult RefRes = DefaultLvalueConversion(Ref);
12079 if (!RefRes.isUsable())
12080 continue;
12081 ExprResult PostUpdateRes =
12082 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12083 SimpleRefExpr, RefRes.get());
12084 if (!PostUpdateRes.isUsable())
12085 continue;
12086 ExprPostUpdates.push_back(
12087 IgnoredValueConversions(PostUpdateRes.get()).get());
12088 }
12089 }
12090 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012091 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012092 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012093 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012094 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012095 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012096 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012097 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012098
12099 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012100 Vars.push_back((VD || CurContext->isDependentContext())
12101 ? RefExpr->IgnoreParens()
12102 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012103 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012104 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012105 }
12106
12107 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012108 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012109
12110 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012111 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012112 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12113 !Step->isInstantiationDependent() &&
12114 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012115 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012116 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012117 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012118 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012119 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012120
Alexander Musman3276a272015-03-21 10:12:56 +000012121 // Build var to save the step value.
12122 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012123 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012124 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012125 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012126 ExprResult CalcStep =
12127 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012128 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012129
Alexander Musman8dba6642014-04-22 13:09:42 +000012130 // Warn about zero linear step (it would be probably better specified as
12131 // making corresponding variables 'const').
12132 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012133 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12134 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012135 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12136 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012137 if (!IsConstant && CalcStep.isUsable()) {
12138 // Calculate the step beforehand instead of doing this on each iteration.
12139 // (This is not used if the number of iterations may be kfold-ed).
12140 CalcStepExpr = CalcStep.get();
12141 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012142 }
12143
Alexey Bataev182227b2015-08-20 10:54:39 +000012144 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12145 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012146 StepExpr, CalcStepExpr,
12147 buildPreInits(Context, ExprCaptures),
12148 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012149}
12150
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012151static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12152 Expr *NumIterations, Sema &SemaRef,
12153 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012154 // Walk the vars and build update/final expressions for the CodeGen.
12155 SmallVector<Expr *, 8> Updates;
12156 SmallVector<Expr *, 8> Finals;
12157 Expr *Step = Clause.getStep();
12158 Expr *CalcStep = Clause.getCalcStep();
12159 // OpenMP [2.14.3.7, linear clause]
12160 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012161 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012162 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012163 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012164 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12165 bool HasErrors = false;
12166 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012167 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012168 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12169 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012170 SourceLocation ELoc;
12171 SourceRange ERange;
12172 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012173 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012174 ValueDecl *D = Res.first;
12175 if (Res.second || !D) {
12176 Updates.push_back(nullptr);
12177 Finals.push_back(nullptr);
12178 HasErrors = true;
12179 continue;
12180 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012181 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012182 // OpenMP [2.15.11, distribute simd Construct]
12183 // A list item may not appear in a linear clause, unless it is the loop
12184 // iteration variable.
12185 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12186 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12187 SemaRef.Diag(ELoc,
12188 diag::err_omp_linear_distribute_var_non_loop_iteration);
12189 Updates.push_back(nullptr);
12190 Finals.push_back(nullptr);
12191 HasErrors = true;
12192 continue;
12193 }
Alexander Musman3276a272015-03-21 10:12:56 +000012194 Expr *InitExpr = *CurInit;
12195
12196 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012197 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012198 Expr *CapturedRef;
12199 if (LinKind == OMPC_LINEAR_uval)
12200 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12201 else
12202 CapturedRef =
12203 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12204 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12205 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012206
12207 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012208 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012209 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012210 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012211 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012212 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012213 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012214 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012215 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012216 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012217
12218 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012219 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012220 if (!Info.first)
12221 Final =
12222 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12223 InitExpr, NumIterations, Step, /*Subtract=*/false);
12224 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012225 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012226 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012227 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012228
Alexander Musman3276a272015-03-21 10:12:56 +000012229 if (!Update.isUsable() || !Final.isUsable()) {
12230 Updates.push_back(nullptr);
12231 Finals.push_back(nullptr);
12232 HasErrors = true;
12233 } else {
12234 Updates.push_back(Update.get());
12235 Finals.push_back(Final.get());
12236 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012237 ++CurInit;
12238 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012239 }
12240 Clause.setUpdates(Updates);
12241 Clause.setFinals(Finals);
12242 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012243}
12244
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012245OMPClause *Sema::ActOnOpenMPAlignedClause(
12246 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12247 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012248 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012249 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012250 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12251 SourceLocation ELoc;
12252 SourceRange ERange;
12253 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012254 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012255 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012256 // It will be analyzed later.
12257 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012258 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012259 ValueDecl *D = Res.first;
12260 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012261 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012262
Alexey Bataev1efd1662016-03-29 10:59:56 +000012263 QualType QType = D->getType();
12264 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012265
12266 // OpenMP [2.8.1, simd construct, Restrictions]
12267 // The type of list items appearing in the aligned clause must be
12268 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012269 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012270 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012271 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012272 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012273 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012274 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012275 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012277 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012279 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012280 continue;
12281 }
12282
12283 // OpenMP [2.8.1, simd construct, Restrictions]
12284 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012285 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012286 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012287 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12288 << getOpenMPClauseName(OMPC_aligned);
12289 continue;
12290 }
12291
Alexey Bataev1efd1662016-03-29 10:59:56 +000012292 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012293 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012294 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12295 Vars.push_back(DefaultFunctionArrayConversion(
12296 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12297 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012298 }
12299
12300 // OpenMP [2.8.1, simd construct, Description]
12301 // The parameter of the aligned clause, alignment, must be a constant
12302 // positive integer expression.
12303 // If no optional parameter is specified, implementation-defined default
12304 // alignments for SIMD instructions on the target platforms are assumed.
12305 if (Alignment != nullptr) {
12306 ExprResult AlignResult =
12307 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12308 if (AlignResult.isInvalid())
12309 return nullptr;
12310 Alignment = AlignResult.get();
12311 }
12312 if (Vars.empty())
12313 return nullptr;
12314
12315 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12316 EndLoc, Vars, Alignment);
12317}
12318
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012319OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12320 SourceLocation StartLoc,
12321 SourceLocation LParenLoc,
12322 SourceLocation EndLoc) {
12323 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012324 SmallVector<Expr *, 8> SrcExprs;
12325 SmallVector<Expr *, 8> DstExprs;
12326 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012327 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012328 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12329 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012330 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012331 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012332 SrcExprs.push_back(nullptr);
12333 DstExprs.push_back(nullptr);
12334 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012335 continue;
12336 }
12337
Alexey Bataeved09d242014-05-28 05:53:51 +000012338 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012339 // OpenMP [2.1, C/C++]
12340 // A list item is a variable name.
12341 // OpenMP [2.14.4.1, Restrictions, p.1]
12342 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012343 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012344 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012345 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12346 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012347 continue;
12348 }
12349
12350 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012351 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012352
12353 QualType Type = VD->getType();
12354 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12355 // It will be analyzed later.
12356 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012357 SrcExprs.push_back(nullptr);
12358 DstExprs.push_back(nullptr);
12359 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012360 continue;
12361 }
12362
12363 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12364 // A list item that appears in a copyin clause must be threadprivate.
12365 if (!DSAStack->isThreadPrivate(VD)) {
12366 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012367 << getOpenMPClauseName(OMPC_copyin)
12368 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012369 continue;
12370 }
12371
12372 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12373 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012374 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012375 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012376 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12377 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012378 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012379 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012380 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012381 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012382 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012383 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012384 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012385 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012386 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012387 // For arrays generate assignment operation for single element and replace
12388 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012389 ExprResult AssignmentOp =
12390 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12391 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012392 if (AssignmentOp.isInvalid())
12393 continue;
12394 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012395 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012396 if (AssignmentOp.isInvalid())
12397 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012398
12399 DSAStack->addDSA(VD, DE, OMPC_copyin);
12400 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012401 SrcExprs.push_back(PseudoSrcExpr);
12402 DstExprs.push_back(PseudoDstExpr);
12403 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012404 }
12405
Alexey Bataeved09d242014-05-28 05:53:51 +000012406 if (Vars.empty())
12407 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012408
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012409 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12410 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012411}
12412
Alexey Bataevbae9a792014-06-27 10:37:06 +000012413OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12414 SourceLocation StartLoc,
12415 SourceLocation LParenLoc,
12416 SourceLocation EndLoc) {
12417 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012418 SmallVector<Expr *, 8> SrcExprs;
12419 SmallVector<Expr *, 8> DstExprs;
12420 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012421 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012422 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12423 SourceLocation ELoc;
12424 SourceRange ERange;
12425 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012426 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012427 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012428 // It will be analyzed later.
12429 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012430 SrcExprs.push_back(nullptr);
12431 DstExprs.push_back(nullptr);
12432 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012433 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012434 ValueDecl *D = Res.first;
12435 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012436 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012437
Alexey Bataeve122da12016-03-17 10:50:17 +000012438 QualType Type = D->getType();
12439 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012440
12441 // OpenMP [2.14.4.2, Restrictions, p.2]
12442 // A list item that appears in a copyprivate clause may not appear in a
12443 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012444 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012445 DSAStackTy::DSAVarData DVar =
12446 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012447 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12448 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012449 Diag(ELoc, diag::err_omp_wrong_dsa)
12450 << getOpenMPClauseName(DVar.CKind)
12451 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012452 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012453 continue;
12454 }
12455
12456 // OpenMP [2.11.4.2, Restrictions, p.1]
12457 // All list items that appear in a copyprivate clause must be either
12458 // threadprivate or private in the enclosing context.
12459 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012460 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012461 if (DVar.CKind == OMPC_shared) {
12462 Diag(ELoc, diag::err_omp_required_access)
12463 << getOpenMPClauseName(OMPC_copyprivate)
12464 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012465 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012466 continue;
12467 }
12468 }
12469 }
12470
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012471 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012472 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012473 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012474 << getOpenMPClauseName(OMPC_copyprivate) << Type
12475 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012476 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012477 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012478 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012479 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012480 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012481 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012482 continue;
12483 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012484
Alexey Bataevbae9a792014-06-27 10:37:06 +000012485 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12486 // A variable of class type (or array thereof) that appears in a
12487 // copyin clause requires an accessible, unambiguous copy assignment
12488 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012489 Type = Context.getBaseElementType(Type.getNonReferenceType())
12490 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012491 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012492 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012493 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012494 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12495 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012496 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012497 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012498 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12499 ExprResult AssignmentOp = BuildBinOp(
12500 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012501 if (AssignmentOp.isInvalid())
12502 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012503 AssignmentOp =
12504 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012505 if (AssignmentOp.isInvalid())
12506 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012507
12508 // No need to mark vars as copyprivate, they are already threadprivate or
12509 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012510 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012511 Vars.push_back(
12512 VD ? RefExpr->IgnoreParens()
12513 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012514 SrcExprs.push_back(PseudoSrcExpr);
12515 DstExprs.push_back(PseudoDstExpr);
12516 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012517 }
12518
12519 if (Vars.empty())
12520 return nullptr;
12521
Alexey Bataeva63048e2015-03-23 06:18:07 +000012522 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12523 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012524}
12525
Alexey Bataev6125da92014-07-21 11:26:11 +000012526OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12527 SourceLocation StartLoc,
12528 SourceLocation LParenLoc,
12529 SourceLocation EndLoc) {
12530 if (VarList.empty())
12531 return nullptr;
12532
12533 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12534}
Alexey Bataevdea47612014-07-23 07:46:59 +000012535
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012536OMPClause *
12537Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12538 SourceLocation DepLoc, SourceLocation ColonLoc,
12539 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12540 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012541 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012542 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012543 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012544 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012545 return nullptr;
12546 }
12547 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012548 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12549 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012550 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012551 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012552 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12553 /*Last=*/OMPC_DEPEND_unknown, Except)
12554 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012555 return nullptr;
12556 }
12557 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012558 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012559 llvm::APSInt DepCounter(/*BitWidth=*/32);
12560 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012561 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12562 if (const Expr *OrderedCountExpr =
12563 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012564 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12565 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012566 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012567 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012568 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012569 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12570 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12571 // It will be analyzed later.
12572 Vars.push_back(RefExpr);
12573 continue;
12574 }
12575
12576 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012577 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012578 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012579 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012580 DepCounter >= TotalDepCount) {
12581 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12582 continue;
12583 }
12584 ++DepCounter;
12585 // OpenMP [2.13.9, Summary]
12586 // depend(dependence-type : vec), where dependence-type is:
12587 // 'sink' and where vec is the iteration vector, which has the form:
12588 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12589 // where n is the value specified by the ordered clause in the loop
12590 // directive, xi denotes the loop iteration variable of the i-th nested
12591 // loop associated with the loop directive, and di is a constant
12592 // non-negative integer.
12593 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012594 // It will be analyzed later.
12595 Vars.push_back(RefExpr);
12596 continue;
12597 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012598 SimpleExpr = SimpleExpr->IgnoreImplicit();
12599 OverloadedOperatorKind OOK = OO_None;
12600 SourceLocation OOLoc;
12601 Expr *LHS = SimpleExpr;
12602 Expr *RHS = nullptr;
12603 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12604 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12605 OOLoc = BO->getOperatorLoc();
12606 LHS = BO->getLHS()->IgnoreParenImpCasts();
12607 RHS = BO->getRHS()->IgnoreParenImpCasts();
12608 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12609 OOK = OCE->getOperator();
12610 OOLoc = OCE->getOperatorLoc();
12611 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12612 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12613 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12614 OOK = MCE->getMethodDecl()
12615 ->getNameInfo()
12616 .getName()
12617 .getCXXOverloadedOperator();
12618 OOLoc = MCE->getCallee()->getExprLoc();
12619 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12620 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012621 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012622 SourceLocation ELoc;
12623 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012624 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012625 if (Res.second) {
12626 // It will be analyzed later.
12627 Vars.push_back(RefExpr);
12628 }
12629 ValueDecl *D = Res.first;
12630 if (!D)
12631 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012632
Alexey Bataev17daedf2018-02-15 22:42:57 +000012633 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12634 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12635 continue;
12636 }
12637 if (RHS) {
12638 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12639 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12640 if (RHSRes.isInvalid())
12641 continue;
12642 }
12643 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012644 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012645 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012646 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012647 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012648 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012649 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12650 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012651 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012652 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012653 continue;
12654 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012655 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012656 } else {
12657 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12658 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12659 (ASE &&
12660 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12661 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12662 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12663 << RefExpr->getSourceRange();
12664 continue;
12665 }
12666 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12667 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12668 ExprResult Res =
12669 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12670 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12671 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12672 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12673 << RefExpr->getSourceRange();
12674 continue;
12675 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012676 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012677 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012678 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012679
12680 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12681 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012682 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012683 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12684 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12685 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12686 }
12687 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12688 Vars.empty())
12689 return nullptr;
12690
Alexey Bataev8b427062016-05-25 12:36:08 +000012691 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012692 DepKind, DepLoc, ColonLoc, Vars,
12693 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012694 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12695 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012696 DSAStack->addDoacrossDependClause(C, OpsOffs);
12697 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012698}
Michael Wonge710d542015-08-07 16:16:36 +000012699
12700OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12701 SourceLocation LParenLoc,
12702 SourceLocation EndLoc) {
12703 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012704 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012705
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012706 // OpenMP [2.9.1, Restrictions]
12707 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012708 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012709 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012710 return nullptr;
12711
Alexey Bataev931e19b2017-10-02 16:32:39 +000012712 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012713 OpenMPDirectiveKind CaptureRegion =
12714 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12715 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012716 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012717 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012718 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12719 HelperValStmt = buildPreInits(Context, Captures);
12720 }
12721
Alexey Bataev8451efa2018-01-15 19:06:12 +000012722 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12723 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012724}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012725
Alexey Bataeve3727102018-04-18 15:57:46 +000012726static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012727 DSAStackTy *Stack, QualType QTy,
12728 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012729 NamedDecl *ND;
12730 if (QTy->isIncompleteType(&ND)) {
12731 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12732 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012733 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012734 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12735 !QTy.isTrivialType(SemaRef.Context))
12736 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012737 return true;
12738}
12739
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012740/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012741/// (array section or array subscript) does NOT specify the whole size of the
12742/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012743static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012744 const Expr *E,
12745 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012746 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012747
12748 // If this is an array subscript, it refers to the whole size if the size of
12749 // the dimension is constant and equals 1. Also, an array section assumes the
12750 // format of an array subscript if no colon is used.
12751 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012752 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012753 return ATy->getSize().getSExtValue() != 1;
12754 // Size can't be evaluated statically.
12755 return false;
12756 }
12757
12758 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012759 const Expr *LowerBound = OASE->getLowerBound();
12760 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012761
12762 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012763 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012764 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012765 Expr::EvalResult Result;
12766 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012767 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012768
12769 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012770 if (ConstLowerBound.getSExtValue())
12771 return true;
12772 }
12773
12774 // If we don't have a length we covering the whole dimension.
12775 if (!Length)
12776 return false;
12777
12778 // If the base is a pointer, we don't have a way to get the size of the
12779 // pointee.
12780 if (BaseQTy->isPointerType())
12781 return false;
12782
12783 // We can only check if the length is the same as the size of the dimension
12784 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012785 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012786 if (!CATy)
12787 return false;
12788
Fangrui Song407659a2018-11-30 23:41:18 +000012789 Expr::EvalResult Result;
12790 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012791 return false; // Can't get the integer value as a constant.
12792
Fangrui Song407659a2018-11-30 23:41:18 +000012793 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012794 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12795}
12796
12797// Return true if it can be proven that the provided array expression (array
12798// section or array subscript) does NOT specify a single element of the array
12799// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012800static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012801 const Expr *E,
12802 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012803 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012804
12805 // An array subscript always refer to a single element. Also, an array section
12806 // assumes the format of an array subscript if no colon is used.
12807 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12808 return false;
12809
12810 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012811 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012812
12813 // If we don't have a length we have to check if the array has unitary size
12814 // for this dimension. Also, we should always expect a length if the base type
12815 // is pointer.
12816 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012817 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012818 return ATy->getSize().getSExtValue() != 1;
12819 // We cannot assume anything.
12820 return false;
12821 }
12822
12823 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012824 Expr::EvalResult Result;
12825 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012826 return false; // Can't get the integer value as a constant.
12827
Fangrui Song407659a2018-11-30 23:41:18 +000012828 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012829 return ConstLength.getSExtValue() != 1;
12830}
12831
Samuel Antao661c0902016-05-26 17:39:58 +000012832// Return the expression of the base of the mappable expression or null if it
12833// cannot be determined and do all the necessary checks to see if the expression
12834// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012835// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012836static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012837 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012838 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012839 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012840 SourceLocation ELoc = E->getExprLoc();
12841 SourceRange ERange = E->getSourceRange();
12842
12843 // The base of elements of list in a map clause have to be either:
12844 // - a reference to variable or field.
12845 // - a member expression.
12846 // - an array expression.
12847 //
12848 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12849 // reference to 'r'.
12850 //
12851 // If we have:
12852 //
12853 // struct SS {
12854 // Bla S;
12855 // foo() {
12856 // #pragma omp target map (S.Arr[:12]);
12857 // }
12858 // }
12859 //
12860 // We want to retrieve the member expression 'this->S';
12861
Alexey Bataeve3727102018-04-18 15:57:46 +000012862 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012863
Samuel Antao5de996e2016-01-22 20:21:36 +000012864 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12865 // If a list item is an array section, it must specify contiguous storage.
12866 //
12867 // For this restriction it is sufficient that we make sure only references
12868 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012869 // exist except in the rightmost expression (unless they cover the whole
12870 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012871 //
12872 // r.ArrS[3:5].Arr[6:7]
12873 //
12874 // r.ArrS[3:5].x
12875 //
12876 // but these would be valid:
12877 // r.ArrS[3].Arr[6:7]
12878 //
12879 // r.ArrS[3].x
12880
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012881 bool AllowUnitySizeArraySection = true;
12882 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012883
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012884 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012885 E = E->IgnoreParenImpCasts();
12886
12887 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12888 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012889 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012890
12891 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012892
12893 // If we got a reference to a declaration, we should not expect any array
12894 // section before that.
12895 AllowUnitySizeArraySection = false;
12896 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012897
12898 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012899 CurComponents.emplace_back(CurE, CurE->getDecl());
12900 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012901 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012902
12903 if (isa<CXXThisExpr>(BaseE))
12904 // We found a base expression: this->Val.
12905 RelevantExpr = CurE;
12906 else
12907 E = BaseE;
12908
12909 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012910 if (!NoDiagnose) {
12911 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12912 << CurE->getSourceRange();
12913 return nullptr;
12914 }
12915 if (RelevantExpr)
12916 return nullptr;
12917 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012918 }
12919
12920 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12921
12922 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12923 // A bit-field cannot appear in a map clause.
12924 //
12925 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012926 if (!NoDiagnose) {
12927 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12928 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12929 return nullptr;
12930 }
12931 if (RelevantExpr)
12932 return nullptr;
12933 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012934 }
12935
12936 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12937 // If the type of a list item is a reference to a type T then the type
12938 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012939 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012940
12941 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12942 // A list item cannot be a variable that is a member of a structure with
12943 // a union type.
12944 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012945 if (CurType->isUnionType()) {
12946 if (!NoDiagnose) {
12947 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12948 << CurE->getSourceRange();
12949 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012950 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012951 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012952 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012953
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012954 // If we got a member expression, we should not expect any array section
12955 // before that:
12956 //
12957 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12958 // If a list item is an element of a structure, only the rightmost symbol
12959 // of the variable reference can be an array section.
12960 //
12961 AllowUnitySizeArraySection = false;
12962 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012963
12964 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012965 CurComponents.emplace_back(CurE, FD);
12966 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012967 E = CurE->getBase()->IgnoreParenImpCasts();
12968
12969 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012970 if (!NoDiagnose) {
12971 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12972 << 0 << CurE->getSourceRange();
12973 return nullptr;
12974 }
12975 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012976 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012977
12978 // If we got an array subscript that express the whole dimension we
12979 // can have any array expressions before. If it only expressing part of
12980 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012981 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012982 E->getType()))
12983 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012984
Patrick Lystere13b1e32019-01-02 19:28:48 +000012985 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12986 Expr::EvalResult Result;
12987 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12988 if (!Result.Val.getInt().isNullValue()) {
12989 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12990 diag::err_omp_invalid_map_this_expr);
12991 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12992 diag::note_omp_invalid_subscript_on_this_ptr_map);
12993 }
12994 }
12995 RelevantExpr = TE;
12996 }
12997
Samuel Antao90927002016-04-26 14:54:23 +000012998 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012999 CurComponents.emplace_back(CurE, nullptr);
13000 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013001 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013002 E = CurE->getBase()->IgnoreParenImpCasts();
13003
Alexey Bataev27041fa2017-12-05 15:22:49 +000013004 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013005 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13006
Samuel Antao5de996e2016-01-22 20:21:36 +000013007 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13008 // If the type of a list item is a reference to a type T then the type
13009 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013010 if (CurType->isReferenceType())
13011 CurType = CurType->getPointeeType();
13012
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013013 bool IsPointer = CurType->isAnyPointerType();
13014
13015 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013016 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13017 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013018 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013019 }
13020
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013021 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013022 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013023 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013025
Samuel Antaodab51bb2016-07-18 23:22:11 +000013026 if (AllowWholeSizeArraySection) {
13027 // Any array section is currently allowed. Allowing a whole size array
13028 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013029 //
13030 // If this array section refers to the whole dimension we can still
13031 // accept other array sections before this one, except if the base is a
13032 // pointer. Otherwise, only unitary sections are accepted.
13033 if (NotWhole || IsPointer)
13034 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013035 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013036 // A unity or whole array section is not allowed and that is not
13037 // compatible with the properties of the current array section.
13038 SemaRef.Diag(
13039 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13040 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013041 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013042 }
Samuel Antao90927002016-04-26 14:54:23 +000013043
Patrick Lystere13b1e32019-01-02 19:28:48 +000013044 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13045 Expr::EvalResult ResultR;
13046 Expr::EvalResult ResultL;
13047 if (CurE->getLength()->EvaluateAsInt(ResultR,
13048 SemaRef.getASTContext())) {
13049 if (!ResultR.Val.getInt().isOneValue()) {
13050 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13051 diag::err_omp_invalid_map_this_expr);
13052 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13053 diag::note_omp_invalid_length_on_this_ptr_mapping);
13054 }
13055 }
13056 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13057 ResultL, SemaRef.getASTContext())) {
13058 if (!ResultL.Val.getInt().isNullValue()) {
13059 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13060 diag::err_omp_invalid_map_this_expr);
13061 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13062 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13063 }
13064 }
13065 RelevantExpr = TE;
13066 }
13067
Samuel Antao90927002016-04-26 14:54:23 +000013068 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013069 CurComponents.emplace_back(CurE, nullptr);
13070 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013071 if (!NoDiagnose) {
13072 // If nothing else worked, this is not a valid map clause expression.
13073 SemaRef.Diag(
13074 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13075 << ERange;
13076 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013077 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013078 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013079 }
13080
13081 return RelevantExpr;
13082}
13083
13084// Return true if expression E associated with value VD has conflicts with other
13085// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013086static bool checkMapConflicts(
13087 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013088 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013089 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13090 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013091 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013092 SourceLocation ELoc = E->getExprLoc();
13093 SourceRange ERange = E->getSourceRange();
13094
13095 // In order to easily check the conflicts we need to match each component of
13096 // the expression under test with the components of the expressions that are
13097 // already in the stack.
13098
Samuel Antao5de996e2016-01-22 20:21:36 +000013099 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013100 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013101 "Map clause expression with unexpected base!");
13102
13103 // Variables to help detecting enclosing problems in data environment nests.
13104 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013105 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013106
Samuel Antao90927002016-04-26 14:54:23 +000013107 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13108 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013109 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13110 ERange, CKind, &EnclosingExpr,
13111 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13112 StackComponents,
13113 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013114 assert(!StackComponents.empty() &&
13115 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013116 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013117 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013118 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013119
Samuel Antao90927002016-04-26 14:54:23 +000013120 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013121 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013122
Samuel Antao5de996e2016-01-22 20:21:36 +000013123 // Expressions must start from the same base. Here we detect at which
13124 // point both expressions diverge from each other and see if we can
13125 // detect if the memory referred to both expressions is contiguous and
13126 // do not overlap.
13127 auto CI = CurComponents.rbegin();
13128 auto CE = CurComponents.rend();
13129 auto SI = StackComponents.rbegin();
13130 auto SE = StackComponents.rend();
13131 for (; CI != CE && SI != SE; ++CI, ++SI) {
13132
13133 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13134 // At most one list item can be an array item derived from a given
13135 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013136 if (CurrentRegionOnly &&
13137 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13138 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13139 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13140 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13141 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013142 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013143 << CI->getAssociatedExpression()->getSourceRange();
13144 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13145 diag::note_used_here)
13146 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013147 return true;
13148 }
13149
13150 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013151 if (CI->getAssociatedExpression()->getStmtClass() !=
13152 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013153 break;
13154
13155 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013156 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013157 break;
13158 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013159 // Check if the extra components of the expressions in the enclosing
13160 // data environment are redundant for the current base declaration.
13161 // If they are, the maps completely overlap, which is legal.
13162 for (; SI != SE; ++SI) {
13163 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013164 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013165 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013166 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013167 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013168 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013169 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013170 Type =
13171 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13172 }
13173 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013174 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013175 SemaRef, SI->getAssociatedExpression(), Type))
13176 break;
13177 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013178
13179 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13180 // List items of map clauses in the same construct must not share
13181 // original storage.
13182 //
13183 // If the expressions are exactly the same or one is a subset of the
13184 // other, it means they are sharing storage.
13185 if (CI == CE && SI == SE) {
13186 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013187 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013188 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013189 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013190 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013191 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13192 << ERange;
13193 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013194 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13195 << RE->getSourceRange();
13196 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013197 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013198 // If we find the same expression in the enclosing data environment,
13199 // that is legal.
13200 IsEnclosedByDataEnvironmentExpr = true;
13201 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013202 }
13203
Samuel Antao90927002016-04-26 14:54:23 +000013204 QualType DerivedType =
13205 std::prev(CI)->getAssociatedDeclaration()->getType();
13206 SourceLocation DerivedLoc =
13207 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013208
13209 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13210 // If the type of a list item is a reference to a type T then the type
13211 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013212 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013213
13214 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13215 // A variable for which the type is pointer and an array section
13216 // derived from that variable must not appear as list items of map
13217 // clauses of the same construct.
13218 //
13219 // Also, cover one of the cases in:
13220 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13221 // If any part of the original storage of a list item has corresponding
13222 // storage in the device data environment, all of the original storage
13223 // must have corresponding storage in the device data environment.
13224 //
13225 if (DerivedType->isAnyPointerType()) {
13226 if (CI == CE || SI == SE) {
13227 SemaRef.Diag(
13228 DerivedLoc,
13229 diag::err_omp_pointer_mapped_along_with_derived_section)
13230 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013231 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13232 << RE->getSourceRange();
13233 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013234 }
13235 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013236 SI->getAssociatedExpression()->getStmtClass() ||
13237 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13238 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013239 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013240 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013241 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013242 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13243 << RE->getSourceRange();
13244 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013245 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013246 }
13247
13248 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13249 // List items of map clauses in the same construct must not share
13250 // original storage.
13251 //
13252 // An expression is a subset of the other.
13253 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013254 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013255 if (CI != CE || SI != SE) {
13256 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13257 // a pointer.
13258 auto Begin =
13259 CI != CE ? CurComponents.begin() : StackComponents.begin();
13260 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13261 auto It = Begin;
13262 while (It != End && !It->getAssociatedDeclaration())
13263 std::advance(It, 1);
13264 assert(It != End &&
13265 "Expected at least one component with the declaration.");
13266 if (It != Begin && It->getAssociatedDeclaration()
13267 ->getType()
13268 .getCanonicalType()
13269 ->isAnyPointerType()) {
13270 IsEnclosedByDataEnvironmentExpr = false;
13271 EnclosingExpr = nullptr;
13272 return false;
13273 }
13274 }
Samuel Antao661c0902016-05-26 17:39:58 +000013275 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013276 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013277 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013278 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13279 << ERange;
13280 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013281 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13282 << RE->getSourceRange();
13283 return true;
13284 }
13285
13286 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013287 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013288 if (!CurrentRegionOnly && SI != SE)
13289 EnclosingExpr = RE;
13290
13291 // The current expression is a subset of the expression in the data
13292 // environment.
13293 IsEnclosedByDataEnvironmentExpr |=
13294 (!CurrentRegionOnly && CI != CE && SI == SE);
13295
13296 return false;
13297 });
13298
13299 if (CurrentRegionOnly)
13300 return FoundError;
13301
13302 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13303 // If any part of the original storage of a list item has corresponding
13304 // storage in the device data environment, all of the original storage must
13305 // have corresponding storage in the device data environment.
13306 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13307 // If a list item is an element of a structure, and a different element of
13308 // the structure has a corresponding list item in the device data environment
13309 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013310 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013311 // data environment prior to the task encountering the construct.
13312 //
13313 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13314 SemaRef.Diag(ELoc,
13315 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13316 << ERange;
13317 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13318 << EnclosingExpr->getSourceRange();
13319 return true;
13320 }
13321
13322 return FoundError;
13323}
13324
Michael Kruse4304e9d2019-02-19 16:38:20 +000013325// Look up the user-defined mapper given the mapper name and mapped type, and
13326// build a reference to it.
13327ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13328 CXXScopeSpec &MapperIdScopeSpec,
13329 const DeclarationNameInfo &MapperId,
13330 QualType Type, Expr *UnresolvedMapper) {
13331 if (MapperIdScopeSpec.isInvalid())
13332 return ExprError();
13333 // Find all user-defined mappers with the given MapperId.
13334 SmallVector<UnresolvedSet<8>, 4> Lookups;
13335 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13336 Lookup.suppressDiagnostics();
13337 if (S) {
13338 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13339 NamedDecl *D = Lookup.getRepresentativeDecl();
13340 while (S && !S->isDeclScope(D))
13341 S = S->getParent();
13342 if (S)
13343 S = S->getParent();
13344 Lookups.emplace_back();
13345 Lookups.back().append(Lookup.begin(), Lookup.end());
13346 Lookup.clear();
13347 }
13348 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13349 // Extract the user-defined mappers with the given MapperId.
13350 Lookups.push_back(UnresolvedSet<8>());
13351 for (NamedDecl *D : ULE->decls()) {
13352 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13353 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13354 Lookups.back().addDecl(DMD);
13355 }
13356 }
13357 // Defer the lookup for dependent types. The results will be passed through
13358 // UnresolvedMapper on instantiation.
13359 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13360 Type->isInstantiationDependentType() ||
13361 Type->containsUnexpandedParameterPack() ||
13362 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13363 return !D->isInvalidDecl() &&
13364 (D->getType()->isDependentType() ||
13365 D->getType()->isInstantiationDependentType() ||
13366 D->getType()->containsUnexpandedParameterPack());
13367 })) {
13368 UnresolvedSet<8> URS;
13369 for (const UnresolvedSet<8> &Set : Lookups) {
13370 if (Set.empty())
13371 continue;
13372 URS.append(Set.begin(), Set.end());
13373 }
13374 return UnresolvedLookupExpr::Create(
13375 SemaRef.Context, /*NamingClass=*/nullptr,
13376 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13377 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13378 }
13379 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13380 // The type must be of struct, union or class type in C and C++
13381 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13382 return ExprEmpty();
13383 SourceLocation Loc = MapperId.getLoc();
13384 // Perform argument dependent lookup.
13385 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13386 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13387 // Return the first user-defined mapper with the desired type.
13388 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13389 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13390 if (!D->isInvalidDecl() &&
13391 SemaRef.Context.hasSameType(D->getType(), Type))
13392 return D;
13393 return nullptr;
13394 }))
13395 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13396 // Find the first user-defined mapper with a type derived from the desired
13397 // type.
13398 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13399 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13400 if (!D->isInvalidDecl() &&
13401 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13402 !Type.isMoreQualifiedThan(D->getType()))
13403 return D;
13404 return nullptr;
13405 })) {
13406 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13407 /*DetectVirtual=*/false);
13408 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13409 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13410 VD->getType().getUnqualifiedType()))) {
13411 if (SemaRef.CheckBaseClassAccess(
13412 Loc, VD->getType(), Type, Paths.front(),
13413 /*DiagID=*/0) != Sema::AR_inaccessible) {
13414 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13415 }
13416 }
13417 }
13418 }
13419 // Report error if a mapper is specified, but cannot be found.
13420 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13421 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13422 << Type << MapperId.getName();
13423 return ExprError();
13424 }
13425 return ExprEmpty();
13426}
13427
Samuel Antao661c0902016-05-26 17:39:58 +000013428namespace {
13429// Utility struct that gathers all the related lists associated with a mappable
13430// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013431struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013432 // The list of expressions.
13433 ArrayRef<Expr *> VarList;
13434 // The list of processed expressions.
13435 SmallVector<Expr *, 16> ProcessedVarList;
13436 // The mappble components for each expression.
13437 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13438 // The base declaration of the variable.
13439 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013440 // The reference to the user-defined mapper associated with every expression.
13441 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013442
13443 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13444 // We have a list of components and base declarations for each entry in the
13445 // variable list.
13446 VarComponents.reserve(VarList.size());
13447 VarBaseDeclarations.reserve(VarList.size());
13448 }
13449};
13450}
13451
13452// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013453// \a CKind. In the check process the valid expressions, mappable expression
13454// components, variables, and user-defined mappers are extracted and used to
13455// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13456// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13457// and \a MapperId are expected to be valid if the clause kind is 'map'.
13458static void checkMappableExpressionList(
13459 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13460 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013461 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13462 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013463 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013464 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013465 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13466 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013467 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013468
13469 // If the identifier of user-defined mapper is not specified, it is "default".
13470 // We do not change the actual name in this clause to distinguish whether a
13471 // mapper is specified explicitly, i.e., it is not explicitly specified when
13472 // MapperId.getName() is empty.
13473 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13474 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13475 MapperId.setName(DeclNames.getIdentifier(
13476 &SemaRef.getASTContext().Idents.get("default")));
13477 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013478
13479 // Iterators to find the current unresolved mapper expression.
13480 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13481 bool UpdateUMIt = false;
13482 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013483
Samuel Antao90927002016-04-26 14:54:23 +000013484 // Keep track of the mappable components and base declarations in this clause.
13485 // Each entry in the list is going to have a list of components associated. We
13486 // record each set of the components so that we can build the clause later on.
13487 // In the end we should have the same amount of declarations and component
13488 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013489
Alexey Bataeve3727102018-04-18 15:57:46 +000013490 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013491 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013492 SourceLocation ELoc = RE->getExprLoc();
13493
Michael Kruse4304e9d2019-02-19 16:38:20 +000013494 // Find the current unresolved mapper expression.
13495 if (UpdateUMIt && UMIt != UMEnd) {
13496 UMIt++;
13497 assert(
13498 UMIt != UMEnd &&
13499 "Expect the size of UnresolvedMappers to match with that of VarList");
13500 }
13501 UpdateUMIt = true;
13502 if (UMIt != UMEnd)
13503 UnresolvedMapper = *UMIt;
13504
Alexey Bataeve3727102018-04-18 15:57:46 +000013505 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013506
13507 if (VE->isValueDependent() || VE->isTypeDependent() ||
13508 VE->isInstantiationDependent() ||
13509 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013510 // Try to find the associated user-defined mapper.
13511 ExprResult ER = buildUserDefinedMapperRef(
13512 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13513 VE->getType().getCanonicalType(), UnresolvedMapper);
13514 if (ER.isInvalid())
13515 continue;
13516 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013517 // We can only analyze this information once the missing information is
13518 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013519 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013520 continue;
13521 }
13522
Alexey Bataeve3727102018-04-18 15:57:46 +000013523 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013524
Samuel Antao5de996e2016-01-22 20:21:36 +000013525 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013526 SemaRef.Diag(ELoc,
13527 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013528 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013529 continue;
13530 }
13531
Samuel Antao90927002016-04-26 14:54:23 +000013532 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13533 ValueDecl *CurDeclaration = nullptr;
13534
13535 // Obtain the array or member expression bases if required. Also, fill the
13536 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013537 const Expr *BE = checkMapClauseExpressionBase(
13538 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013539 if (!BE)
13540 continue;
13541
Samuel Antao90927002016-04-26 14:54:23 +000013542 assert(!CurComponents.empty() &&
13543 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013544
Patrick Lystere13b1e32019-01-02 19:28:48 +000013545 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13546 // Add store "this" pointer to class in DSAStackTy for future checking
13547 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013548 // Try to find the associated user-defined mapper.
13549 ExprResult ER = buildUserDefinedMapperRef(
13550 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13551 VE->getType().getCanonicalType(), UnresolvedMapper);
13552 if (ER.isInvalid())
13553 continue;
13554 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013555 // Skip restriction checking for variable or field declarations
13556 MVLI.ProcessedVarList.push_back(RE);
13557 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13558 MVLI.VarComponents.back().append(CurComponents.begin(),
13559 CurComponents.end());
13560 MVLI.VarBaseDeclarations.push_back(nullptr);
13561 continue;
13562 }
13563
Samuel Antao90927002016-04-26 14:54:23 +000013564 // For the following checks, we rely on the base declaration which is
13565 // expected to be associated with the last component. The declaration is
13566 // expected to be a variable or a field (if 'this' is being mapped).
13567 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13568 assert(CurDeclaration && "Null decl on map clause.");
13569 assert(
13570 CurDeclaration->isCanonicalDecl() &&
13571 "Expecting components to have associated only canonical declarations.");
13572
13573 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013574 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013575
13576 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013577 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013578
13579 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013580 // threadprivate variables cannot appear in a map clause.
13581 // OpenMP 4.5 [2.10.5, target update Construct]
13582 // threadprivate variables cannot appear in a from clause.
13583 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013584 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013585 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13586 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013587 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013588 continue;
13589 }
13590
Samuel Antao5de996e2016-01-22 20:21:36 +000013591 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13592 // A list item cannot appear in both a map clause and a data-sharing
13593 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013594
Samuel Antao5de996e2016-01-22 20:21:36 +000013595 // Check conflicts with other map clause expressions. We check the conflicts
13596 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013597 // environment, because the restrictions are different. We only have to
13598 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013599 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013600 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013601 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013602 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013603 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013604 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013605 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013606
Samuel Antao661c0902016-05-26 17:39:58 +000013607 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013608 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13609 // If the type of a list item is a reference to a type T then the type will
13610 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013611 auto I = llvm::find_if(
13612 CurComponents,
13613 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13614 return MC.getAssociatedDeclaration();
13615 });
13616 assert(I != CurComponents.end() && "Null decl on map clause.");
13617 QualType Type =
13618 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013619
Samuel Antao661c0902016-05-26 17:39:58 +000013620 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13621 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013622 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013623 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013624 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013625 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013626 continue;
13627
Samuel Antao661c0902016-05-26 17:39:58 +000013628 if (CKind == OMPC_map) {
13629 // target enter data
13630 // OpenMP [2.10.2, Restrictions, p. 99]
13631 // A map-type must be specified in all map clauses and must be either
13632 // to or alloc.
13633 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13634 if (DKind == OMPD_target_enter_data &&
13635 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13636 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13637 << (IsMapTypeImplicit ? 1 : 0)
13638 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13639 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013640 continue;
13641 }
Samuel Antao661c0902016-05-26 17:39:58 +000013642
13643 // target exit_data
13644 // OpenMP [2.10.3, Restrictions, p. 102]
13645 // A map-type must be specified in all map clauses and must be either
13646 // from, release, or delete.
13647 if (DKind == OMPD_target_exit_data &&
13648 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13649 MapType == OMPC_MAP_delete)) {
13650 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13651 << (IsMapTypeImplicit ? 1 : 0)
13652 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13653 << getOpenMPDirectiveName(DKind);
13654 continue;
13655 }
13656
13657 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13658 // A list item cannot appear in both a map clause and a data-sharing
13659 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013660 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13661 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013662 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013663 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013664 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013665 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013666 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013667 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013668 continue;
13669 }
13670 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013671 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013672
Michael Kruse01f670d2019-02-22 22:29:42 +000013673 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013674 ExprResult ER = buildUserDefinedMapperRef(
13675 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13676 Type.getCanonicalType(), UnresolvedMapper);
13677 if (ER.isInvalid())
13678 continue;
13679 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013680
Samuel Antao90927002016-04-26 14:54:23 +000013681 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013682 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013683
13684 // Store the components in the stack so that they can be used to check
13685 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013686 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13687 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013688
13689 // Save the components and declaration to create the clause. For purposes of
13690 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013691 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013692 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13693 MVLI.VarComponents.back().append(CurComponents.begin(),
13694 CurComponents.end());
13695 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13696 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013697 }
Samuel Antao661c0902016-05-26 17:39:58 +000013698}
13699
Michael Kruse4304e9d2019-02-19 16:38:20 +000013700OMPClause *Sema::ActOnOpenMPMapClause(
13701 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13702 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13703 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13704 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13705 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13706 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13707 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13708 OMPC_MAP_MODIFIER_unknown,
13709 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013710 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13711
13712 // Process map-type-modifiers, flag errors for duplicate modifiers.
13713 unsigned Count = 0;
13714 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13715 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13716 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13717 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13718 continue;
13719 }
13720 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013721 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013722 Modifiers[Count] = MapTypeModifiers[I];
13723 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13724 ++Count;
13725 }
13726
Michael Kruse4304e9d2019-02-19 16:38:20 +000013727 MappableVarListInfo MVLI(VarList);
13728 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013729 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13730 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013731
Samuel Antao5de996e2016-01-22 20:21:36 +000013732 // We need to produce a map clause even if we don't have variables so that
13733 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013734 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13735 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13736 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13737 MapperIdScopeSpec.getWithLocInContext(Context),
13738 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013739}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013740
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013741QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13742 TypeResult ParsedType) {
13743 assert(ParsedType.isUsable());
13744
13745 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13746 if (ReductionType.isNull())
13747 return QualType();
13748
13749 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13750 // A type name in a declare reduction directive cannot be a function type, an
13751 // array type, a reference type, or a type qualified with const, volatile or
13752 // restrict.
13753 if (ReductionType.hasQualifiers()) {
13754 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13755 return QualType();
13756 }
13757
13758 if (ReductionType->isFunctionType()) {
13759 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13760 return QualType();
13761 }
13762 if (ReductionType->isReferenceType()) {
13763 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13764 return QualType();
13765 }
13766 if (ReductionType->isArrayType()) {
13767 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13768 return QualType();
13769 }
13770 return ReductionType;
13771}
13772
13773Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13774 Scope *S, DeclContext *DC, DeclarationName Name,
13775 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13776 AccessSpecifier AS, Decl *PrevDeclInScope) {
13777 SmallVector<Decl *, 8> Decls;
13778 Decls.reserve(ReductionTypes.size());
13779
13780 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013781 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013782 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13783 // A reduction-identifier may not be re-declared in the current scope for the
13784 // same type or for a type that is compatible according to the base language
13785 // rules.
13786 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13787 OMPDeclareReductionDecl *PrevDRD = nullptr;
13788 bool InCompoundScope = true;
13789 if (S != nullptr) {
13790 // Find previous declaration with the same name not referenced in other
13791 // declarations.
13792 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13793 InCompoundScope =
13794 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13795 LookupName(Lookup, S);
13796 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13797 /*AllowInlineNamespace=*/false);
13798 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013799 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013800 while (Filter.hasNext()) {
13801 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13802 if (InCompoundScope) {
13803 auto I = UsedAsPrevious.find(PrevDecl);
13804 if (I == UsedAsPrevious.end())
13805 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013806 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013807 UsedAsPrevious[D] = true;
13808 }
13809 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13810 PrevDecl->getLocation();
13811 }
13812 Filter.done();
13813 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013814 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013815 if (!PrevData.second) {
13816 PrevDRD = PrevData.first;
13817 break;
13818 }
13819 }
13820 }
13821 } else if (PrevDeclInScope != nullptr) {
13822 auto *PrevDRDInScope = PrevDRD =
13823 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13824 do {
13825 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13826 PrevDRDInScope->getLocation();
13827 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13828 } while (PrevDRDInScope != nullptr);
13829 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013830 for (const auto &TyData : ReductionTypes) {
13831 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013832 bool Invalid = false;
13833 if (I != PreviousRedeclTypes.end()) {
13834 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13835 << TyData.first;
13836 Diag(I->second, diag::note_previous_definition);
13837 Invalid = true;
13838 }
13839 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13840 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13841 Name, TyData.first, PrevDRD);
13842 DC->addDecl(DRD);
13843 DRD->setAccess(AS);
13844 Decls.push_back(DRD);
13845 if (Invalid)
13846 DRD->setInvalidDecl();
13847 else
13848 PrevDRD = DRD;
13849 }
13850
13851 return DeclGroupPtrTy::make(
13852 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13853}
13854
13855void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13856 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13857
13858 // Enter new function scope.
13859 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013860 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013861 getCurFunction()->setHasOMPDeclareReductionCombiner();
13862
13863 if (S != nullptr)
13864 PushDeclContext(S, DRD);
13865 else
13866 CurContext = DRD;
13867
Faisal Valid143a0c2017-04-01 21:30:49 +000013868 PushExpressionEvaluationContext(
13869 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013870
13871 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013872 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13873 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13874 // uses semantics of argument handles by value, but it should be passed by
13875 // reference. C lang does not support references, so pass all parameters as
13876 // pointers.
13877 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013878 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013879 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013880 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13881 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13882 // uses semantics of argument handles by value, but it should be passed by
13883 // reference. C lang does not support references, so pass all parameters as
13884 // pointers.
13885 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013886 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013887 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13888 if (S != nullptr) {
13889 PushOnScopeChains(OmpInParm, S);
13890 PushOnScopeChains(OmpOutParm, S);
13891 } else {
13892 DRD->addDecl(OmpInParm);
13893 DRD->addDecl(OmpOutParm);
13894 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013895 Expr *InE =
13896 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13897 Expr *OutE =
13898 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13899 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013900}
13901
13902void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13903 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13904 DiscardCleanupsInEvaluationContext();
13905 PopExpressionEvaluationContext();
13906
13907 PopDeclContext();
13908 PopFunctionScopeInfo();
13909
13910 if (Combiner != nullptr)
13911 DRD->setCombiner(Combiner);
13912 else
13913 DRD->setInvalidDecl();
13914}
13915
Alexey Bataev070f43a2017-09-06 14:49:58 +000013916VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013917 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13918
13919 // Enter new function scope.
13920 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013921 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013922
13923 if (S != nullptr)
13924 PushDeclContext(S, DRD);
13925 else
13926 CurContext = DRD;
13927
Faisal Valid143a0c2017-04-01 21:30:49 +000013928 PushExpressionEvaluationContext(
13929 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013930
13931 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013932 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13933 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13934 // uses semantics of argument handles by value, but it should be passed by
13935 // reference. C lang does not support references, so pass all parameters as
13936 // pointers.
13937 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013938 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013939 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013940 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13941 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13942 // uses semantics of argument handles by value, but it should be passed by
13943 // reference. C lang does not support references, so pass all parameters as
13944 // pointers.
13945 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013946 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013947 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013948 if (S != nullptr) {
13949 PushOnScopeChains(OmpPrivParm, S);
13950 PushOnScopeChains(OmpOrigParm, S);
13951 } else {
13952 DRD->addDecl(OmpPrivParm);
13953 DRD->addDecl(OmpOrigParm);
13954 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013955 Expr *OrigE =
13956 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13957 Expr *PrivE =
13958 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13959 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013960 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013961}
13962
Alexey Bataev070f43a2017-09-06 14:49:58 +000013963void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13964 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013965 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13966 DiscardCleanupsInEvaluationContext();
13967 PopExpressionEvaluationContext();
13968
13969 PopDeclContext();
13970 PopFunctionScopeInfo();
13971
Alexey Bataev070f43a2017-09-06 14:49:58 +000013972 if (Initializer != nullptr) {
13973 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13974 } else if (OmpPrivParm->hasInit()) {
13975 DRD->setInitializer(OmpPrivParm->getInit(),
13976 OmpPrivParm->isDirectInit()
13977 ? OMPDeclareReductionDecl::DirectInit
13978 : OMPDeclareReductionDecl::CopyInit);
13979 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013980 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013981 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013982}
13983
13984Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13985 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013986 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013987 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013988 if (S)
13989 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13990 /*AddToContext=*/false);
13991 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013992 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013993 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013994 }
13995 return DeclReductions;
13996}
13997
Michael Kruse251e1482019-02-01 20:25:04 +000013998TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13999 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14000 QualType T = TInfo->getType();
14001 if (D.isInvalidType())
14002 return true;
14003
14004 if (getLangOpts().CPlusPlus) {
14005 // Check that there are no default arguments (C++ only).
14006 CheckExtraCXXDefaultArguments(D);
14007 }
14008
14009 return CreateParsedType(T, TInfo);
14010}
14011
14012QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14013 TypeResult ParsedType) {
14014 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14015
14016 QualType MapperType = GetTypeFromParser(ParsedType.get());
14017 assert(!MapperType.isNull() && "Expect valid mapper type");
14018
14019 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14020 // The type must be of struct, union or class type in C and C++
14021 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14022 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14023 return QualType();
14024 }
14025 return MapperType;
14026}
14027
14028OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14029 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14030 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14031 Decl *PrevDeclInScope) {
14032 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14033 forRedeclarationInCurContext());
14034 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14035 // A mapper-identifier may not be redeclared in the current scope for the
14036 // same type or for a type that is compatible according to the base language
14037 // rules.
14038 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14039 OMPDeclareMapperDecl *PrevDMD = nullptr;
14040 bool InCompoundScope = true;
14041 if (S != nullptr) {
14042 // Find previous declaration with the same name not referenced in other
14043 // declarations.
14044 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14045 InCompoundScope =
14046 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14047 LookupName(Lookup, S);
14048 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14049 /*AllowInlineNamespace=*/false);
14050 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14051 LookupResult::Filter Filter = Lookup.makeFilter();
14052 while (Filter.hasNext()) {
14053 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14054 if (InCompoundScope) {
14055 auto I = UsedAsPrevious.find(PrevDecl);
14056 if (I == UsedAsPrevious.end())
14057 UsedAsPrevious[PrevDecl] = false;
14058 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14059 UsedAsPrevious[D] = true;
14060 }
14061 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14062 PrevDecl->getLocation();
14063 }
14064 Filter.done();
14065 if (InCompoundScope) {
14066 for (const auto &PrevData : UsedAsPrevious) {
14067 if (!PrevData.second) {
14068 PrevDMD = PrevData.first;
14069 break;
14070 }
14071 }
14072 }
14073 } else if (PrevDeclInScope) {
14074 auto *PrevDMDInScope = PrevDMD =
14075 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14076 do {
14077 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14078 PrevDMDInScope->getLocation();
14079 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14080 } while (PrevDMDInScope != nullptr);
14081 }
14082 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14083 bool Invalid = false;
14084 if (I != PreviousRedeclTypes.end()) {
14085 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14086 << MapperType << Name;
14087 Diag(I->second, diag::note_previous_definition);
14088 Invalid = true;
14089 }
14090 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14091 MapperType, VN, PrevDMD);
14092 DC->addDecl(DMD);
14093 DMD->setAccess(AS);
14094 if (Invalid)
14095 DMD->setInvalidDecl();
14096
14097 // Enter new function scope.
14098 PushFunctionScope();
14099 setFunctionHasBranchProtectedScope();
14100
14101 CurContext = DMD;
14102
14103 return DMD;
14104}
14105
14106void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14107 Scope *S,
14108 QualType MapperType,
14109 SourceLocation StartLoc,
14110 DeclarationName VN) {
14111 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14112 if (S)
14113 PushOnScopeChains(VD, S);
14114 else
14115 DMD->addDecl(VD);
14116 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14117 DMD->setMapperVarRef(MapperVarRefExpr);
14118}
14119
14120Sema::DeclGroupPtrTy
14121Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14122 ArrayRef<OMPClause *> ClauseList) {
14123 PopDeclContext();
14124 PopFunctionScopeInfo();
14125
14126 if (D) {
14127 if (S)
14128 PushOnScopeChains(D, S, /*AddToContext=*/false);
14129 D->CreateClauses(Context, ClauseList);
14130 }
14131
14132 return DeclGroupPtrTy::make(DeclGroupRef(D));
14133}
14134
David Majnemer9d168222016-08-05 17:44:54 +000014135OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014136 SourceLocation StartLoc,
14137 SourceLocation LParenLoc,
14138 SourceLocation EndLoc) {
14139 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014140 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014141
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014142 // OpenMP [teams Constrcut, Restrictions]
14143 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014144 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014145 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014146 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014147
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014148 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014149 OpenMPDirectiveKind CaptureRegion =
14150 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14151 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014152 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014153 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014154 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14155 HelperValStmt = buildPreInits(Context, Captures);
14156 }
14157
14158 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14159 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014160}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014161
14162OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14163 SourceLocation StartLoc,
14164 SourceLocation LParenLoc,
14165 SourceLocation EndLoc) {
14166 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014167 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014168
14169 // OpenMP [teams Constrcut, Restrictions]
14170 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014171 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014172 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014173 return nullptr;
14174
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014175 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014176 OpenMPDirectiveKind CaptureRegion =
14177 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14178 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014179 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014180 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014181 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14182 HelperValStmt = buildPreInits(Context, Captures);
14183 }
14184
14185 return new (Context) OMPThreadLimitClause(
14186 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014187}
Alexey Bataeva0569352015-12-01 10:17:31 +000014188
14189OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14190 SourceLocation StartLoc,
14191 SourceLocation LParenLoc,
14192 SourceLocation EndLoc) {
14193 Expr *ValExpr = Priority;
14194
14195 // OpenMP [2.9.1, task Constrcut]
14196 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014197 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014198 /*StrictlyPositive=*/false))
14199 return nullptr;
14200
14201 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14202}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014203
14204OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14205 SourceLocation StartLoc,
14206 SourceLocation LParenLoc,
14207 SourceLocation EndLoc) {
14208 Expr *ValExpr = Grainsize;
14209
14210 // OpenMP [2.9.2, taskloop Constrcut]
14211 // The parameter of the grainsize clause must be a positive integer
14212 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014213 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014214 /*StrictlyPositive=*/true))
14215 return nullptr;
14216
14217 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14218}
Alexey Bataev382967a2015-12-08 12:06:20 +000014219
14220OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14221 SourceLocation StartLoc,
14222 SourceLocation LParenLoc,
14223 SourceLocation EndLoc) {
14224 Expr *ValExpr = NumTasks;
14225
14226 // OpenMP [2.9.2, taskloop Constrcut]
14227 // The parameter of the num_tasks clause must be a positive integer
14228 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014229 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014230 /*StrictlyPositive=*/true))
14231 return nullptr;
14232
14233 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14234}
14235
Alexey Bataev28c75412015-12-15 08:19:24 +000014236OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14237 SourceLocation LParenLoc,
14238 SourceLocation EndLoc) {
14239 // OpenMP [2.13.2, critical construct, Description]
14240 // ... where hint-expression is an integer constant expression that evaluates
14241 // to a valid lock hint.
14242 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14243 if (HintExpr.isInvalid())
14244 return nullptr;
14245 return new (Context)
14246 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14247}
14248
Carlo Bertollib4adf552016-01-15 18:50:31 +000014249OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14250 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14251 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14252 SourceLocation EndLoc) {
14253 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14254 std::string Values;
14255 Values += "'";
14256 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14257 Values += "'";
14258 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14259 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14260 return nullptr;
14261 }
14262 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014263 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014264 if (ChunkSize) {
14265 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14266 !ChunkSize->isInstantiationDependent() &&
14267 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014268 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014269 ExprResult Val =
14270 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14271 if (Val.isInvalid())
14272 return nullptr;
14273
14274 ValExpr = Val.get();
14275
14276 // OpenMP [2.7.1, Restrictions]
14277 // chunk_size must be a loop invariant integer expression with a positive
14278 // value.
14279 llvm::APSInt Result;
14280 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14281 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14282 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14283 << "dist_schedule" << ChunkSize->getSourceRange();
14284 return nullptr;
14285 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014286 } else if (getOpenMPCaptureRegionForClause(
14287 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14288 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014289 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014290 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014291 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014292 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14293 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014294 }
14295 }
14296 }
14297
14298 return new (Context)
14299 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014300 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014301}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014302
14303OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14304 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14305 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14306 SourceLocation KindLoc, SourceLocation EndLoc) {
14307 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014308 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014309 std::string Value;
14310 SourceLocation Loc;
14311 Value += "'";
14312 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14313 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014314 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014315 Loc = MLoc;
14316 } else {
14317 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014318 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014319 Loc = KindLoc;
14320 }
14321 Value += "'";
14322 Diag(Loc, diag::err_omp_unexpected_clause_value)
14323 << Value << getOpenMPClauseName(OMPC_defaultmap);
14324 return nullptr;
14325 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014326 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014327
14328 return new (Context)
14329 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14330}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014331
14332bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14333 DeclContext *CurLexicalContext = getCurLexicalContext();
14334 if (!CurLexicalContext->isFileContext() &&
14335 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014336 !CurLexicalContext->isExternCXXContext() &&
14337 !isa<CXXRecordDecl>(CurLexicalContext) &&
14338 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14339 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14340 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014341 Diag(Loc, diag::err_omp_region_not_file_context);
14342 return false;
14343 }
Kelvin Libc38e632018-09-10 02:07:09 +000014344 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014345 return true;
14346}
14347
14348void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014349 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014350 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014351 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014352}
14353
David Majnemer9d168222016-08-05 17:44:54 +000014354void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14355 CXXScopeSpec &ScopeSpec,
14356 const DeclarationNameInfo &Id,
14357 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14358 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014359 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14360 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14361
14362 if (Lookup.isAmbiguous())
14363 return;
14364 Lookup.suppressDiagnostics();
14365
14366 if (!Lookup.isSingleResult()) {
14367 if (TypoCorrection Corrected =
14368 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14369 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14370 CTK_ErrorRecovery)) {
14371 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14372 << Id.getName());
14373 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14374 return;
14375 }
14376
14377 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14378 return;
14379 }
14380
14381 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014382 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14383 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014384 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14385 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014386 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14387 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14388 cast<ValueDecl>(ND));
14389 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014390 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014391 ND->addAttr(A);
14392 if (ASTMutationListener *ML = Context.getASTMutationListener())
14393 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014394 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014395 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014396 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14397 << Id.getName();
14398 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014399 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014400 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014401 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014402}
14403
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014404static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14405 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014406 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014407 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014408 auto *VD = cast<VarDecl>(D);
14409 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14410 return;
14411 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14412 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014413}
14414
14415static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14416 Sema &SemaRef, DSAStackTy *Stack,
14417 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014418 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14419 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14420 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014421}
14422
Kelvin Li1ce87c72017-12-12 20:08:12 +000014423void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14424 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014425 if (!D || D->isInvalidDecl())
14426 return;
14427 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014428 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014429 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014430 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014431 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14432 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014433 return;
14434 // 2.10.6: threadprivate variable cannot appear in a declare target
14435 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014436 if (DSAStack->isThreadPrivate(VD)) {
14437 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014438 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014439 return;
14440 }
14441 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014442 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14443 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014444 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014445 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14446 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14447 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014448 assert(IdLoc.isValid() && "Source location is expected");
14449 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14450 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14451 return;
14452 }
14453 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014454 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14455 // Problem if any with var declared with incomplete type will be reported
14456 // as normal, so no need to check it here.
14457 if ((E || !VD->getType()->isIncompleteType()) &&
14458 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14459 return;
14460 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14461 // Checking declaration inside declare target region.
14462 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14463 isa<FunctionTemplateDecl>(D)) {
14464 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14465 Context, OMPDeclareTargetDeclAttr::MT_To);
14466 D->addAttr(A);
14467 if (ASTMutationListener *ML = Context.getASTMutationListener())
14468 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14469 }
14470 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014471 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014472 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014473 if (!E)
14474 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014475 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14476}
Samuel Antao661c0902016-05-26 17:39:58 +000014477
14478OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014479 CXXScopeSpec &MapperIdScopeSpec,
14480 DeclarationNameInfo &MapperId,
14481 const OMPVarListLocTy &Locs,
14482 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014483 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014484 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14485 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014486 if (MVLI.ProcessedVarList.empty())
14487 return nullptr;
14488
Michael Kruse01f670d2019-02-22 22:29:42 +000014489 return OMPToClause::Create(
14490 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14491 MVLI.VarComponents, MVLI.UDMapperList,
14492 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014493}
Samuel Antaoec172c62016-05-26 17:49:04 +000014494
14495OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014496 CXXScopeSpec &MapperIdScopeSpec,
14497 DeclarationNameInfo &MapperId,
14498 const OMPVarListLocTy &Locs,
14499 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014500 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014501 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14502 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014503 if (MVLI.ProcessedVarList.empty())
14504 return nullptr;
14505
Michael Kruse0336c752019-02-25 20:34:15 +000014506 return OMPFromClause::Create(
14507 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14508 MVLI.VarComponents, MVLI.UDMapperList,
14509 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014510}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014511
14512OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014513 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014514 MappableVarListInfo MVLI(VarList);
14515 SmallVector<Expr *, 8> PrivateCopies;
14516 SmallVector<Expr *, 8> Inits;
14517
Alexey Bataeve3727102018-04-18 15:57:46 +000014518 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014519 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14520 SourceLocation ELoc;
14521 SourceRange ERange;
14522 Expr *SimpleRefExpr = RefExpr;
14523 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14524 if (Res.second) {
14525 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014526 MVLI.ProcessedVarList.push_back(RefExpr);
14527 PrivateCopies.push_back(nullptr);
14528 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014529 }
14530 ValueDecl *D = Res.first;
14531 if (!D)
14532 continue;
14533
14534 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014535 Type = Type.getNonReferenceType().getUnqualifiedType();
14536
14537 auto *VD = dyn_cast<VarDecl>(D);
14538
14539 // Item should be a pointer or reference to pointer.
14540 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014541 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14542 << 0 << RefExpr->getSourceRange();
14543 continue;
14544 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014545
14546 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014547 auto VDPrivate =
14548 buildVarDecl(*this, ELoc, Type, D->getName(),
14549 D->hasAttrs() ? &D->getAttrs() : nullptr,
14550 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014551 if (VDPrivate->isInvalidDecl())
14552 continue;
14553
14554 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014555 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014556 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14557
14558 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014559 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014560 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014561 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14562 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014563 AddInitializerToDecl(VDPrivate,
14564 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014565 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014566
14567 // If required, build a capture to implement the privatization initialized
14568 // with the current list item value.
14569 DeclRefExpr *Ref = nullptr;
14570 if (!VD)
14571 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14572 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14573 PrivateCopies.push_back(VDPrivateRefExpr);
14574 Inits.push_back(VDInitRefExpr);
14575
14576 // We need to add a data sharing attribute for this variable to make sure it
14577 // is correctly captured. A variable that shows up in a use_device_ptr has
14578 // similar properties of a first private variable.
14579 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14580
14581 // Create a mappable component for the list item. List items in this clause
14582 // only need a component.
14583 MVLI.VarBaseDeclarations.push_back(D);
14584 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14585 MVLI.VarComponents.back().push_back(
14586 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014587 }
14588
Samuel Antaocc10b852016-07-28 14:23:26 +000014589 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014590 return nullptr;
14591
Samuel Antaocc10b852016-07-28 14:23:26 +000014592 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014593 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14594 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014595}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014596
14597OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014598 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014599 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014600 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014601 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014602 SourceLocation ELoc;
14603 SourceRange ERange;
14604 Expr *SimpleRefExpr = RefExpr;
14605 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14606 if (Res.second) {
14607 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014608 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014609 }
14610 ValueDecl *D = Res.first;
14611 if (!D)
14612 continue;
14613
14614 QualType Type = D->getType();
14615 // item should be a pointer or array or reference to pointer or array
14616 if (!Type.getNonReferenceType()->isPointerType() &&
14617 !Type.getNonReferenceType()->isArrayType()) {
14618 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14619 << 0 << RefExpr->getSourceRange();
14620 continue;
14621 }
Samuel Antao6890b092016-07-28 14:25:09 +000014622
14623 // Check if the declaration in the clause does not show up in any data
14624 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014625 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014626 if (isOpenMPPrivate(DVar.CKind)) {
14627 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14628 << getOpenMPClauseName(DVar.CKind)
14629 << getOpenMPClauseName(OMPC_is_device_ptr)
14630 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014631 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014632 continue;
14633 }
14634
Alexey Bataeve3727102018-04-18 15:57:46 +000014635 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014636 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014637 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014638 [&ConflictExpr](
14639 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14640 OpenMPClauseKind) -> bool {
14641 ConflictExpr = R.front().getAssociatedExpression();
14642 return true;
14643 })) {
14644 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14645 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14646 << ConflictExpr->getSourceRange();
14647 continue;
14648 }
14649
14650 // Store the components in the stack so that they can be used to check
14651 // against other clauses later on.
14652 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14653 DSAStack->addMappableExpressionComponents(
14654 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14655
14656 // Record the expression we've just processed.
14657 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14658
14659 // Create a mappable component for the list item. List items in this clause
14660 // only need a component. We use a null declaration to signal fields in
14661 // 'this'.
14662 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14663 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14664 "Unexpected device pointer expression!");
14665 MVLI.VarBaseDeclarations.push_back(
14666 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14667 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14668 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014669 }
14670
Samuel Antao6890b092016-07-28 14:25:09 +000014671 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014672 return nullptr;
14673
Michael Kruse4304e9d2019-02-19 16:38:20 +000014674 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14675 MVLI.VarBaseDeclarations,
14676 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014677}