blob: 5d7ad8c5be6d3085b1de8e464d210d2d21ad969e [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() ||
2222 Allocator->containsUnexpandedParameterPack() ||
2223 !Allocator->isEvaluatable(S.getASTContext()))
2224 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2225 bool Suppress = S.getDiagnostics().getSuppressAllDiagnostics();
2226 S.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
2227 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2228 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2229 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2230 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2231 Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
2232 // Compare allocator with the predefined allocator and if true - return
2233 // predefined allocator kind.
2234 ExprResult DefAllocRes = S.DefaultLvalueConversion(DefAllocator);
2235 ExprResult AllocRes = S.DefaultLvalueConversion(Allocator);
2236 ExprResult CompareRes = S.CreateBuiltinBinOp(
2237 Allocator->getExprLoc(), BO_EQ, DefAllocRes.get(), AllocRes.get());
2238 if (!CompareRes.isUsable())
2239 continue;
2240 bool Result;
2241 if (!CompareRes.get()->EvaluateAsBooleanCondition(Result,
2242 S.getASTContext()))
2243 continue;
2244 if (Result) {
2245 AllocatorKindRes = AllocatorKind;
2246 break;
2247 }
2248
2249 }
2250 S.getDiagnostics().setSuppressAllDiagnostics(Suppress);
2251 return AllocatorKindRes;
2252}
2253
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002254Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2255 SourceLocation Loc, ArrayRef<Expr *> VarList,
2256 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2257 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2258 Expr *Allocator = nullptr;
2259 if (!Clauses.empty())
2260 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002261 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2262 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002263 SmallVector<Expr *, 8> Vars;
2264 for (Expr *RefExpr : VarList) {
2265 auto *DE = cast<DeclRefExpr>(RefExpr);
2266 auto *VD = cast<VarDecl>(DE->getDecl());
2267
2268 // Check if this is a TLS variable or global register.
2269 if (VD->getTLSKind() != VarDecl::TLS_None ||
2270 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2271 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2272 !VD->isLocalVarDecl()))
2273 continue;
2274 // Do not apply for parameters.
2275 if (isa<ParmVarDecl>(VD))
2276 continue;
2277
Alexey Bataev282555a2019-03-19 20:33:44 +00002278 // If the used several times in the allocate directive, the same allocator
2279 // must be used.
2280 if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2281 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002282 Expr *PrevAllocator = A->getAllocator();
2283 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2284 getAllocatorKind(*this, DSAStack, PrevAllocator);
2285 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2286 if (AllocatorsMatch && Allocator && PrevAllocator) {
Alexey Bataev282555a2019-03-19 20:33:44 +00002287 const Expr *AE = Allocator->IgnoreParenImpCasts();
2288 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2289 llvm::FoldingSetNodeID AEId, PAEId;
2290 AE->Profile(AEId, Context, /*Canonical=*/true);
2291 PAE->Profile(PAEId, Context, /*Canonical=*/true);
2292 AllocatorsMatch = AEId == PAEId;
Alexey Bataev282555a2019-03-19 20:33:44 +00002293 }
2294 if (!AllocatorsMatch) {
2295 SmallString<256> AllocatorBuffer;
2296 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2297 if (Allocator)
2298 Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2299 SmallString<256> PrevAllocatorBuffer;
2300 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2301 if (PrevAllocator)
2302 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2303 getPrintingPolicy());
2304
2305 SourceLocation AllocatorLoc =
2306 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2307 SourceRange AllocatorRange =
2308 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2309 SourceLocation PrevAllocatorLoc =
2310 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2311 SourceRange PrevAllocatorRange =
2312 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2313 Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2314 << (Allocator ? 1 : 0) << AllocatorStream.str()
2315 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2316 << AllocatorRange;
2317 Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2318 << PrevAllocatorRange;
2319 continue;
2320 }
2321 }
2322
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002323 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2324 // If a list item has a static storage type, the allocator expression in the
2325 // allocator clause must be a constant expression that evaluates to one of
2326 // the predefined memory allocator values.
2327 if (Allocator && VD->hasGlobalStorage()) {
2328 bool IsPredefinedAllocator = false;
2329 if (const auto *DRE =
2330 dyn_cast<DeclRefExpr>(Allocator->IgnoreParenImpCasts())) {
2331 if (DRE->getType().isConstant(getASTContext())) {
2332 DeclarationName DN = DRE->getDecl()->getDeclName();
2333 if (DN.isIdentifier()) {
2334 StringRef PredefinedAllocators[] = {
2335 "omp_default_mem_alloc", "omp_large_cap_mem_alloc",
2336 "omp_const_mem_alloc", "omp_high_bw_mem_alloc",
2337 "omp_low_lat_mem_alloc", "omp_cgroup_mem_alloc",
2338 "omp_pteam_mem_alloc", "omp_thread_mem_alloc",
2339 };
2340 IsPredefinedAllocator =
2341 llvm::any_of(PredefinedAllocators, [&DN](StringRef S) {
2342 return DN.getAsIdentifierInfo()->isStr(S);
2343 });
2344 }
2345 }
2346 }
2347 if (!IsPredefinedAllocator) {
2348 Diag(Allocator->getExprLoc(),
2349 diag::err_omp_expected_predefined_allocator)
2350 << Allocator->getSourceRange();
2351 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2352 VarDecl::DeclarationOnly;
2353 Diag(VD->getLocation(),
2354 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2355 << VD;
2356 continue;
2357 }
2358 }
2359
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002360 Vars.push_back(RefExpr);
Alexey Bataev282555a2019-03-19 20:33:44 +00002361 if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2362 !Allocator->isValueDependent() &&
2363 !Allocator->isInstantiationDependent() &&
2364 !Allocator->containsUnexpandedParameterPack())) &&
2365 !VD->hasAttr<OMPAllocateDeclAttr>()) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002366 Attr *A = OMPAllocateDeclAttr::CreateImplicit(
2367 Context, AllocatorKind, Allocator, DE->getSourceRange());
Alexey Bataev282555a2019-03-19 20:33:44 +00002368 VD->addAttr(A);
2369 if (ASTMutationListener *ML = Context.getASTMutationListener())
2370 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2371 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002372 }
2373 if (Vars.empty())
2374 return nullptr;
2375 if (!Owner)
2376 Owner = getCurLexicalContext();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002377 OMPAllocateDecl *D =
2378 OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002379 D->setAccess(AS_public);
2380 Owner->addDecl(D);
2381 return DeclGroupPtrTy::make(DeclGroupRef(D));
2382}
2383
2384Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002385Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2386 ArrayRef<OMPClause *> ClauseList) {
2387 OMPRequiresDecl *D = nullptr;
2388 if (!CurContext->isFileContext()) {
2389 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2390 } else {
2391 D = CheckOMPRequiresDecl(Loc, ClauseList);
2392 if (D) {
2393 CurContext->addDecl(D);
2394 DSAStack->addRequiresDecl(D);
2395 }
2396 }
2397 return DeclGroupPtrTy::make(DeclGroupRef(D));
2398}
2399
2400OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2401 ArrayRef<OMPClause *> ClauseList) {
2402 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2403 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2404 ClauseList);
2405 return nullptr;
2406}
2407
Alexey Bataeve3727102018-04-18 15:57:46 +00002408static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2409 const ValueDecl *D,
2410 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002411 bool IsLoopIterVar = false) {
2412 if (DVar.RefExpr) {
2413 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2414 << getOpenMPClauseName(DVar.CKind);
2415 return;
2416 }
2417 enum {
2418 PDSA_StaticMemberShared,
2419 PDSA_StaticLocalVarShared,
2420 PDSA_LoopIterVarPrivate,
2421 PDSA_LoopIterVarLinear,
2422 PDSA_LoopIterVarLastprivate,
2423 PDSA_ConstVarShared,
2424 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002425 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002426 PDSA_LocalVarPrivate,
2427 PDSA_Implicit
2428 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002429 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002430 auto ReportLoc = D->getLocation();
2431 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002432 if (IsLoopIterVar) {
2433 if (DVar.CKind == OMPC_private)
2434 Reason = PDSA_LoopIterVarPrivate;
2435 else if (DVar.CKind == OMPC_lastprivate)
2436 Reason = PDSA_LoopIterVarLastprivate;
2437 else
2438 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002439 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2440 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002441 Reason = PDSA_TaskVarFirstprivate;
2442 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002443 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002444 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002445 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002446 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002447 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002448 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002449 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002450 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002451 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002452 ReportHint = true;
2453 Reason = PDSA_LocalVarPrivate;
2454 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002455 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002456 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002457 << Reason << ReportHint
2458 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2459 } else if (DVar.ImplicitDSALoc.isValid()) {
2460 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2461 << getOpenMPClauseName(DVar.CKind);
2462 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002463}
2464
Alexey Bataev758e55e2013-09-06 18:03:48 +00002465namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002466class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002467 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002468 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002469 bool ErrorFound = false;
2470 CapturedStmt *CS = nullptr;
2471 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2472 llvm::SmallVector<Expr *, 4> ImplicitMap;
2473 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2474 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002475
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002476 void VisitSubCaptures(OMPExecutableDirective *S) {
2477 // Check implicitly captured variables.
2478 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2479 return;
2480 for (const CapturedStmt::Capture &Cap :
2481 S->getInnermostCapturedStmt()->captures()) {
2482 if (!Cap.capturesVariable())
2483 continue;
2484 VarDecl *VD = Cap.getCapturedVar();
2485 // Do not try to map the variable if it or its sub-component was mapped
2486 // already.
2487 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2488 Stack->checkMappableExprComponentListsForDecl(
2489 VD, /*CurrentRegionOnly=*/true,
2490 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2491 OpenMPClauseKind) { return true; }))
2492 continue;
2493 DeclRefExpr *DRE = buildDeclRefExpr(
2494 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2495 Cap.getLocation(), /*RefersToCapture=*/true);
2496 Visit(DRE);
2497 }
2498 }
2499
Alexey Bataev758e55e2013-09-06 18:03:48 +00002500public:
2501 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002502 if (E->isTypeDependent() || E->isValueDependent() ||
2503 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2504 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002505 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002506 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002507 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002508 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002509 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002510
Alexey Bataeve3727102018-04-18 15:57:46 +00002511 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002512 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002513 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002514 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002515
Alexey Bataevafe50572017-10-06 17:00:28 +00002516 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002517 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002518 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002519 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2520 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002521 return;
2522
Alexey Bataeve3727102018-04-18 15:57:46 +00002523 SourceLocation ELoc = E->getExprLoc();
2524 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002525 // The default(none) clause requires that each variable that is referenced
2526 // in the construct, and does not have a predetermined data-sharing
2527 // attribute, must have its data-sharing attribute explicitly determined
2528 // by being listed in a data-sharing attribute clause.
2529 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002530 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002531 VarsWithInheritedDSA.count(VD) == 0) {
2532 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002533 return;
2534 }
2535
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002536 if (isOpenMPTargetExecutionDirective(DKind) &&
2537 !Stack->isLoopControlVariable(VD).first) {
2538 if (!Stack->checkMappableExprComponentListsForDecl(
2539 VD, /*CurrentRegionOnly=*/true,
2540 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2541 StackComponents,
2542 OpenMPClauseKind) {
2543 // Variable is used if it has been marked as an array, array
2544 // section or the variable iself.
2545 return StackComponents.size() == 1 ||
2546 std::all_of(
2547 std::next(StackComponents.rbegin()),
2548 StackComponents.rend(),
2549 [](const OMPClauseMappableExprCommon::
2550 MappableComponent &MC) {
2551 return MC.getAssociatedDeclaration() ==
2552 nullptr &&
2553 (isa<OMPArraySectionExpr>(
2554 MC.getAssociatedExpression()) ||
2555 isa<ArraySubscriptExpr>(
2556 MC.getAssociatedExpression()));
2557 });
2558 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002559 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002560 // By default lambdas are captured as firstprivates.
2561 if (const auto *RD =
2562 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002563 IsFirstprivate = RD->isLambda();
2564 IsFirstprivate =
2565 IsFirstprivate ||
2566 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002567 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002568 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002569 ImplicitFirstprivate.emplace_back(E);
2570 else
2571 ImplicitMap.emplace_back(E);
2572 return;
2573 }
2574 }
2575
Alexey Bataev758e55e2013-09-06 18:03:48 +00002576 // OpenMP [2.9.3.6, Restrictions, p.2]
2577 // A list item that appears in a reduction clause of the innermost
2578 // enclosing worksharing or parallel construct may not be accessed in an
2579 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002580 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002581 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2582 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002583 return isOpenMPParallelDirective(K) ||
2584 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2585 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002586 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002587 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002588 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002589 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002590 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002591 return;
2592 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002593
2594 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002595 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002596 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002597 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002598 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002599 return;
2600 }
2601
2602 // Store implicitly used globals with declare target link for parent
2603 // target.
2604 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2605 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2606 Stack->addToParentTargetRegionLinkGlobals(E);
2607 return;
2608 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002609 }
2610 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002611 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002612 if (E->isTypeDependent() || E->isValueDependent() ||
2613 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2614 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002615 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002616 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002617 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002618 if (!FD)
2619 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002620 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002621 // Check if the variable has explicit DSA set and stop analysis if it
2622 // so.
2623 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2624 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002625
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002626 if (isOpenMPTargetExecutionDirective(DKind) &&
2627 !Stack->isLoopControlVariable(FD).first &&
2628 !Stack->checkMappableExprComponentListsForDecl(
2629 FD, /*CurrentRegionOnly=*/true,
2630 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2631 StackComponents,
2632 OpenMPClauseKind) {
2633 return isa<CXXThisExpr>(
2634 cast<MemberExpr>(
2635 StackComponents.back().getAssociatedExpression())
2636 ->getBase()
2637 ->IgnoreParens());
2638 })) {
2639 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2640 // A bit-field cannot appear in a map clause.
2641 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002642 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002643 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002644
2645 // Check to see if the member expression is referencing a class that
2646 // has already been explicitly mapped
2647 if (Stack->isClassPreviouslyMapped(TE->getType()))
2648 return;
2649
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002650 ImplicitMap.emplace_back(E);
2651 return;
2652 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002653
Alexey Bataeve3727102018-04-18 15:57:46 +00002654 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002655 // OpenMP [2.9.3.6, Restrictions, p.2]
2656 // A list item that appears in a reduction clause of the innermost
2657 // enclosing worksharing or parallel construct may not be accessed in
2658 // an explicit task.
2659 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002660 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2661 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002662 return isOpenMPParallelDirective(K) ||
2663 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2664 },
2665 /*FromParent=*/true);
2666 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2667 ErrorFound = true;
2668 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002669 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002670 return;
2671 }
2672
2673 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002674 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002675 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002676 !Stack->isLoopControlVariable(FD).first) {
2677 // Check if there is a captured expression for the current field in the
2678 // region. Do not mark it as firstprivate unless there is no captured
2679 // expression.
2680 // TODO: try to make it firstprivate.
2681 if (DVar.CKind != OMPC_unknown)
2682 ImplicitFirstprivate.push_back(E);
2683 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002684 return;
2685 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002686 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002687 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002688 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002689 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002690 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002691 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002692 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2693 if (!Stack->checkMappableExprComponentListsForDecl(
2694 VD, /*CurrentRegionOnly=*/true,
2695 [&CurComponents](
2696 OMPClauseMappableExprCommon::MappableExprComponentListRef
2697 StackComponents,
2698 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002699 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002700 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002701 for (const auto &SC : llvm::reverse(StackComponents)) {
2702 // Do both expressions have the same kind?
2703 if (CCI->getAssociatedExpression()->getStmtClass() !=
2704 SC.getAssociatedExpression()->getStmtClass())
2705 if (!(isa<OMPArraySectionExpr>(
2706 SC.getAssociatedExpression()) &&
2707 isa<ArraySubscriptExpr>(
2708 CCI->getAssociatedExpression())))
2709 return false;
2710
Alexey Bataeve3727102018-04-18 15:57:46 +00002711 const Decl *CCD = CCI->getAssociatedDeclaration();
2712 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002713 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2714 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2715 if (SCD != CCD)
2716 return false;
2717 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002718 if (CCI == CCE)
2719 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002720 }
2721 return true;
2722 })) {
2723 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002724 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002725 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002726 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002727 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002728 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002729 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002730 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002731 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002732 // for task|target directives.
2733 // Skip analysis of arguments of implicitly defined map clause for target
2734 // directives.
2735 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2736 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002737 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002738 if (CC)
2739 Visit(CC);
2740 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002741 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002742 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002743 // Check implicitly captured variables.
2744 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002745 }
2746 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002747 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002748 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002749 // Check implicitly captured variables in the task-based directives to
2750 // check if they must be firstprivatized.
2751 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002752 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002753 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002754 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002755
Alexey Bataeve3727102018-04-18 15:57:46 +00002756 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002757 ArrayRef<Expr *> getImplicitFirstprivate() const {
2758 return ImplicitFirstprivate;
2759 }
2760 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002761 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002762 return VarsWithInheritedDSA;
2763 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002764
Alexey Bataev7ff55242014-06-19 09:13:45 +00002765 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002766 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2767 // Process declare target link variables for the target directives.
2768 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2769 for (DeclRefExpr *E : Stack->getLinkGlobals())
2770 Visit(E);
2771 }
2772 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002773};
Alexey Bataeved09d242014-05-28 05:53:51 +00002774} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002775
Alexey Bataevbae9a792014-06-27 10:37:06 +00002776void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002777 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002778 case OMPD_parallel:
2779 case OMPD_parallel_for:
2780 case OMPD_parallel_for_simd:
2781 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002782 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002783 case OMPD_teams_distribute:
2784 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002785 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002786 QualType KmpInt32PtrTy =
2787 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002788 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002789 std::make_pair(".global_tid.", KmpInt32PtrTy),
2790 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2791 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002792 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002793 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2794 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002795 break;
2796 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002797 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002798 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002799 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002800 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002801 case OMPD_target_teams_distribute:
2802 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002803 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2804 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2805 QualType KmpInt32PtrTy =
2806 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2807 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002808 FunctionProtoType::ExtProtoInfo EPI;
2809 EPI.Variadic = true;
2810 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2811 Sema::CapturedParamNameType Params[] = {
2812 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002813 std::make_pair(".part_id.", KmpInt32PtrTy),
2814 std::make_pair(".privates.", VoidPtrTy),
2815 std::make_pair(
2816 ".copy_fn.",
2817 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002818 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2819 std::make_pair(StringRef(), QualType()) // __context with shared vars
2820 };
2821 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2822 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002823 // Mark this captured region as inlined, because we don't use outlined
2824 // function directly.
2825 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2826 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002827 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002828 Sema::CapturedParamNameType ParamsTarget[] = {
2829 std::make_pair(StringRef(), QualType()) // __context with shared vars
2830 };
2831 // Start a captured region for 'target' with no implicit parameters.
2832 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2833 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002834 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002835 std::make_pair(".global_tid.", KmpInt32PtrTy),
2836 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2837 std::make_pair(StringRef(), QualType()) // __context with shared vars
2838 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002839 // Start a captured region for 'teams' or 'parallel'. Both regions have
2840 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002841 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002842 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002843 break;
2844 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002845 case OMPD_target:
2846 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002847 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2848 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2849 QualType KmpInt32PtrTy =
2850 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2851 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002852 FunctionProtoType::ExtProtoInfo EPI;
2853 EPI.Variadic = true;
2854 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2855 Sema::CapturedParamNameType Params[] = {
2856 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002857 std::make_pair(".part_id.", KmpInt32PtrTy),
2858 std::make_pair(".privates.", VoidPtrTy),
2859 std::make_pair(
2860 ".copy_fn.",
2861 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002862 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2863 std::make_pair(StringRef(), QualType()) // __context with shared vars
2864 };
2865 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2866 Params);
2867 // Mark this captured region as inlined, because we don't use outlined
2868 // function directly.
2869 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2870 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002871 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002872 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2873 std::make_pair(StringRef(), QualType()));
2874 break;
2875 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002876 case OMPD_simd:
2877 case OMPD_for:
2878 case OMPD_for_simd:
2879 case OMPD_sections:
2880 case OMPD_section:
2881 case OMPD_single:
2882 case OMPD_master:
2883 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002884 case OMPD_taskgroup:
2885 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002886 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002887 case OMPD_ordered:
2888 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002889 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002890 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002891 std::make_pair(StringRef(), QualType()) // __context with shared vars
2892 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002893 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2894 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002895 break;
2896 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002897 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002898 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2899 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2900 QualType KmpInt32PtrTy =
2901 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2902 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002903 FunctionProtoType::ExtProtoInfo EPI;
2904 EPI.Variadic = true;
2905 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002906 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002907 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002908 std::make_pair(".part_id.", KmpInt32PtrTy),
2909 std::make_pair(".privates.", VoidPtrTy),
2910 std::make_pair(
2911 ".copy_fn.",
2912 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002913 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002914 std::make_pair(StringRef(), QualType()) // __context with shared vars
2915 };
2916 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2917 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002918 // Mark this captured region as inlined, because we don't use outlined
2919 // function directly.
2920 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2921 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002922 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002923 break;
2924 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002925 case OMPD_taskloop:
2926 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002927 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002928 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2929 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002930 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002931 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2932 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002933 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002934 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2935 .withConst();
2936 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2937 QualType KmpInt32PtrTy =
2938 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2939 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002940 FunctionProtoType::ExtProtoInfo EPI;
2941 EPI.Variadic = true;
2942 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002943 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002944 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002945 std::make_pair(".part_id.", KmpInt32PtrTy),
2946 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002947 std::make_pair(
2948 ".copy_fn.",
2949 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2950 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2951 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002952 std::make_pair(".ub.", KmpUInt64Ty),
2953 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002954 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002955 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002956 std::make_pair(StringRef(), QualType()) // __context with shared vars
2957 };
2958 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2959 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002960 // Mark this captured region as inlined, because we don't use outlined
2961 // function directly.
2962 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2963 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002964 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002965 break;
2966 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002967 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002968 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002969 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002970 QualType KmpInt32PtrTy =
2971 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2972 Sema::CapturedParamNameType Params[] = {
2973 std::make_pair(".global_tid.", KmpInt32PtrTy),
2974 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002975 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2976 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002977 std::make_pair(StringRef(), QualType()) // __context with shared vars
2978 };
2979 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2980 Params);
2981 break;
2982 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002983 case OMPD_target_teams_distribute_parallel_for:
2984 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002985 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002986 QualType KmpInt32PtrTy =
2987 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002988 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002989
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002990 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002991 FunctionProtoType::ExtProtoInfo EPI;
2992 EPI.Variadic = true;
2993 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2994 Sema::CapturedParamNameType Params[] = {
2995 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002996 std::make_pair(".part_id.", KmpInt32PtrTy),
2997 std::make_pair(".privates.", VoidPtrTy),
2998 std::make_pair(
2999 ".copy_fn.",
3000 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003001 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3002 std::make_pair(StringRef(), QualType()) // __context with shared vars
3003 };
3004 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3005 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003006 // Mark this captured region as inlined, because we don't use outlined
3007 // function directly.
3008 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3009 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003010 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003011 Sema::CapturedParamNameType ParamsTarget[] = {
3012 std::make_pair(StringRef(), QualType()) // __context with shared vars
3013 };
3014 // Start a captured region for 'target' with no implicit parameters.
3015 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3016 ParamsTarget);
3017
3018 Sema::CapturedParamNameType ParamsTeams[] = {
3019 std::make_pair(".global_tid.", KmpInt32PtrTy),
3020 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3021 std::make_pair(StringRef(), QualType()) // __context with shared vars
3022 };
3023 // Start a captured region for 'target' with no implicit parameters.
3024 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3025 ParamsTeams);
3026
3027 Sema::CapturedParamNameType ParamsParallel[] = {
3028 std::make_pair(".global_tid.", KmpInt32PtrTy),
3029 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003030 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3031 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003032 std::make_pair(StringRef(), QualType()) // __context with shared vars
3033 };
3034 // Start a captured region for 'teams' or 'parallel'. Both regions have
3035 // the same implicit parameters.
3036 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3037 ParamsParallel);
3038 break;
3039 }
3040
Alexey Bataev46506272017-12-05 17:41:34 +00003041 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003042 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003043 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003044 QualType KmpInt32PtrTy =
3045 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3046
3047 Sema::CapturedParamNameType ParamsTeams[] = {
3048 std::make_pair(".global_tid.", KmpInt32PtrTy),
3049 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3050 std::make_pair(StringRef(), QualType()) // __context with shared vars
3051 };
3052 // Start a captured region for 'target' with no implicit parameters.
3053 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3054 ParamsTeams);
3055
3056 Sema::CapturedParamNameType ParamsParallel[] = {
3057 std::make_pair(".global_tid.", KmpInt32PtrTy),
3058 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003059 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3060 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003061 std::make_pair(StringRef(), QualType()) // __context with shared vars
3062 };
3063 // Start a captured region for 'teams' or 'parallel'. Both regions have
3064 // the same implicit parameters.
3065 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3066 ParamsParallel);
3067 break;
3068 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003069 case OMPD_target_update:
3070 case OMPD_target_enter_data:
3071 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003072 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3073 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3074 QualType KmpInt32PtrTy =
3075 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3076 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003077 FunctionProtoType::ExtProtoInfo EPI;
3078 EPI.Variadic = true;
3079 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3080 Sema::CapturedParamNameType Params[] = {
3081 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003082 std::make_pair(".part_id.", KmpInt32PtrTy),
3083 std::make_pair(".privates.", VoidPtrTy),
3084 std::make_pair(
3085 ".copy_fn.",
3086 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003087 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3088 std::make_pair(StringRef(), QualType()) // __context with shared vars
3089 };
3090 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3091 Params);
3092 // Mark this captured region as inlined, because we don't use outlined
3093 // function directly.
3094 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3095 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003096 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003097 break;
3098 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003099 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003100 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003101 case OMPD_taskyield:
3102 case OMPD_barrier:
3103 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003104 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003105 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003106 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003107 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003108 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003109 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003110 case OMPD_declare_target:
3111 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003112 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003113 llvm_unreachable("OpenMP Directive is not allowed");
3114 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003115 llvm_unreachable("Unknown OpenMP directive");
3116 }
3117}
3118
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003119int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3120 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3121 getOpenMPCaptureRegions(CaptureRegions, DKind);
3122 return CaptureRegions.size();
3123}
3124
Alexey Bataev3392d762016-02-16 11:18:12 +00003125static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003126 Expr *CaptureExpr, bool WithInit,
3127 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003128 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003129 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003130 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003131 QualType Ty = Init->getType();
3132 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003133 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003134 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003135 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003136 Ty = C.getPointerType(Ty);
3137 ExprResult Res =
3138 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3139 if (!Res.isUsable())
3140 return nullptr;
3141 Init = Res.get();
3142 }
Alexey Bataev61205072016-03-02 04:57:40 +00003143 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003144 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003145 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003146 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003147 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003148 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003149 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003150 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003151 return CED;
3152}
3153
Alexey Bataev61205072016-03-02 04:57:40 +00003154static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3155 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003156 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003157 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003158 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003159 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003160 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3161 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003162 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003163 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003164}
3165
Alexey Bataev5a3af132016-03-29 08:58:54 +00003166static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003167 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003168 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003169 OMPCapturedExprDecl *CD = buildCaptureDecl(
3170 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3171 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003172 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3173 CaptureExpr->getExprLoc());
3174 }
3175 ExprResult Res = Ref;
3176 if (!S.getLangOpts().CPlusPlus &&
3177 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003178 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003179 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003180 if (!Res.isUsable())
3181 return ExprError();
3182 }
3183 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003184}
3185
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003186namespace {
3187// OpenMP directives parsed in this section are represented as a
3188// CapturedStatement with an associated statement. If a syntax error
3189// is detected during the parsing of the associated statement, the
3190// compiler must abort processing and close the CapturedStatement.
3191//
3192// Combined directives such as 'target parallel' have more than one
3193// nested CapturedStatements. This RAII ensures that we unwind out
3194// of all the nested CapturedStatements when an error is found.
3195class CaptureRegionUnwinderRAII {
3196private:
3197 Sema &S;
3198 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003199 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003200
3201public:
3202 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3203 OpenMPDirectiveKind DKind)
3204 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3205 ~CaptureRegionUnwinderRAII() {
3206 if (ErrorFound) {
3207 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3208 while (--ThisCaptureLevel >= 0)
3209 S.ActOnCapturedRegionError();
3210 }
3211 }
3212};
3213} // namespace
3214
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003215StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3216 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003217 bool ErrorFound = false;
3218 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3219 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003220 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003221 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003222 return StmtError();
3223 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003224
Alexey Bataev2ba67042017-11-28 21:11:44 +00003225 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3226 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003227 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003228 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003229 SmallVector<const OMPLinearClause *, 4> LCs;
3230 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003231 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003232 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003233 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3234 Clause->getClauseKind() == OMPC_in_reduction) {
3235 // Capture taskgroup task_reduction descriptors inside the tasking regions
3236 // with the corresponding in_reduction items.
3237 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003238 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003239 if (E)
3240 MarkDeclarationsReferencedInExpr(E);
3241 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003242 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003243 Clause->getClauseKind() == OMPC_copyprivate ||
3244 (getLangOpts().OpenMPUseTLS &&
3245 getASTContext().getTargetInfo().isTLSSupported() &&
3246 Clause->getClauseKind() == OMPC_copyin)) {
3247 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003248 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003249 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003250 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003251 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003252 }
3253 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003254 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003255 } else if (CaptureRegions.size() > 1 ||
3256 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003257 if (auto *C = OMPClauseWithPreInit::get(Clause))
3258 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003259 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003260 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003261 MarkDeclarationsReferencedInExpr(E);
3262 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003263 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003264 if (Clause->getClauseKind() == OMPC_schedule)
3265 SC = cast<OMPScheduleClause>(Clause);
3266 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003267 OC = cast<OMPOrderedClause>(Clause);
3268 else if (Clause->getClauseKind() == OMPC_linear)
3269 LCs.push_back(cast<OMPLinearClause>(Clause));
3270 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003271 // OpenMP, 2.7.1 Loop Construct, Restrictions
3272 // The nonmonotonic modifier cannot be specified if an ordered clause is
3273 // specified.
3274 if (SC &&
3275 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3276 SC->getSecondScheduleModifier() ==
3277 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3278 OC) {
3279 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3280 ? SC->getFirstScheduleModifierLoc()
3281 : SC->getSecondScheduleModifierLoc(),
3282 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003283 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003284 ErrorFound = true;
3285 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003286 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003287 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003288 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003289 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003290 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003291 ErrorFound = true;
3292 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003293 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3294 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3295 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003296 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003297 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3298 ErrorFound = true;
3299 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003300 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003301 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003302 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003303 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003304 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003305 // Mark all variables in private list clauses as used in inner region.
3306 // Required for proper codegen of combined directives.
3307 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003308 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003309 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003310 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3311 // Find the particular capture region for the clause if the
3312 // directive is a combined one with multiple capture regions.
3313 // If the directive is not a combined one, the capture region
3314 // associated with the clause is OMPD_unknown and is generated
3315 // only once.
3316 if (CaptureRegion == ThisCaptureRegion ||
3317 CaptureRegion == OMPD_unknown) {
3318 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003319 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003320 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3321 }
3322 }
3323 }
3324 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003325 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003326 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003327 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003328}
3329
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003330static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3331 OpenMPDirectiveKind CancelRegion,
3332 SourceLocation StartLoc) {
3333 // CancelRegion is only needed for cancel and cancellation_point.
3334 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3335 return false;
3336
3337 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3338 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3339 return false;
3340
3341 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3342 << getOpenMPDirectiveName(CancelRegion);
3343 return true;
3344}
3345
Alexey Bataeve3727102018-04-18 15:57:46 +00003346static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003347 OpenMPDirectiveKind CurrentRegion,
3348 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003349 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003350 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003351 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003352 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3353 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003354 bool NestingProhibited = false;
3355 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003356 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003357 enum {
3358 NoRecommend,
3359 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003360 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003361 ShouldBeInTargetRegion,
3362 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003363 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003364 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003365 // OpenMP [2.16, Nesting of Regions]
3366 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003367 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003368 // An ordered construct with the simd clause is the only OpenMP
3369 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003370 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003371 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3372 // message.
3373 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3374 ? diag::err_omp_prohibited_region_simd
3375 : diag::warn_omp_nesting_simd);
3376 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003377 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003378 if (ParentRegion == OMPD_atomic) {
3379 // OpenMP [2.16, Nesting of Regions]
3380 // OpenMP constructs may not be nested inside an atomic region.
3381 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3382 return true;
3383 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003384 if (CurrentRegion == OMPD_section) {
3385 // OpenMP [2.7.2, sections Construct, Restrictions]
3386 // Orphaned section directives are prohibited. That is, the section
3387 // directives must appear within the sections construct and must not be
3388 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003389 if (ParentRegion != OMPD_sections &&
3390 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003391 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3392 << (ParentRegion != OMPD_unknown)
3393 << getOpenMPDirectiveName(ParentRegion);
3394 return true;
3395 }
3396 return false;
3397 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003398 // Allow some constructs (except teams and cancellation constructs) to be
3399 // orphaned (they could be used in functions, called from OpenMP regions
3400 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003401 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003402 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3403 CurrentRegion != OMPD_cancellation_point &&
3404 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003405 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003406 if (CurrentRegion == OMPD_cancellation_point ||
3407 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003408 // OpenMP [2.16, Nesting of Regions]
3409 // A cancellation point construct for which construct-type-clause is
3410 // taskgroup must be nested inside a task construct. A cancellation
3411 // point construct for which construct-type-clause is not taskgroup must
3412 // be closely nested inside an OpenMP construct that matches the type
3413 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003414 // A cancel construct for which construct-type-clause is taskgroup must be
3415 // nested inside a task construct. A cancel construct for which
3416 // construct-type-clause is not taskgroup must be closely nested inside an
3417 // OpenMP construct that matches the type specified in
3418 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003419 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003420 !((CancelRegion == OMPD_parallel &&
3421 (ParentRegion == OMPD_parallel ||
3422 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003423 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003424 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003425 ParentRegion == OMPD_target_parallel_for ||
3426 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003427 ParentRegion == OMPD_teams_distribute_parallel_for ||
3428 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003429 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3430 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003431 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3432 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003433 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003434 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003435 // OpenMP [2.16, Nesting of Regions]
3436 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003437 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003438 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003439 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003440 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3441 // OpenMP [2.16, Nesting of Regions]
3442 // A critical region may not be nested (closely or otherwise) inside a
3443 // critical region with the same name. Note that this restriction is not
3444 // sufficient to prevent deadlock.
3445 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003446 bool DeadLock = Stack->hasDirective(
3447 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3448 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003449 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003450 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3451 PreviousCriticalLoc = Loc;
3452 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003453 }
3454 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003455 },
3456 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003457 if (DeadLock) {
3458 SemaRef.Diag(StartLoc,
3459 diag::err_omp_prohibited_region_critical_same_name)
3460 << CurrentName.getName();
3461 if (PreviousCriticalLoc.isValid())
3462 SemaRef.Diag(PreviousCriticalLoc,
3463 diag::note_omp_previous_critical_region);
3464 return true;
3465 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003466 } else if (CurrentRegion == OMPD_barrier) {
3467 // OpenMP [2.16, Nesting of Regions]
3468 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003469 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003470 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3471 isOpenMPTaskingDirective(ParentRegion) ||
3472 ParentRegion == OMPD_master ||
3473 ParentRegion == OMPD_critical ||
3474 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003475 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003476 !isOpenMPParallelDirective(CurrentRegion) &&
3477 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003478 // OpenMP [2.16, Nesting of Regions]
3479 // A worksharing region may not be closely nested inside a worksharing,
3480 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003481 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3482 isOpenMPTaskingDirective(ParentRegion) ||
3483 ParentRegion == OMPD_master ||
3484 ParentRegion == OMPD_critical ||
3485 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003486 Recommend = ShouldBeInParallelRegion;
3487 } else if (CurrentRegion == OMPD_ordered) {
3488 // OpenMP [2.16, Nesting of Regions]
3489 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003490 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003491 // An ordered region must be closely nested inside a loop region (or
3492 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003493 // OpenMP [2.8.1,simd Construct, Restrictions]
3494 // An ordered construct with the simd clause is the only OpenMP construct
3495 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003496 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003497 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003498 !(isOpenMPSimdDirective(ParentRegion) ||
3499 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003500 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003501 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003502 // OpenMP [2.16, Nesting of Regions]
3503 // If specified, a teams construct must be contained within a target
3504 // construct.
3505 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003506 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003507 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003508 }
Kelvin Libf594a52016-12-17 05:48:59 +00003509 if (!NestingProhibited &&
3510 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3511 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3512 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003513 // OpenMP [2.16, Nesting of Regions]
3514 // distribute, parallel, parallel sections, parallel workshare, and the
3515 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3516 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003517 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3518 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003519 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003520 }
David Majnemer9d168222016-08-05 17:44:54 +00003521 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003522 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003523 // OpenMP 4.5 [2.17 Nesting of Regions]
3524 // The region associated with the distribute construct must be strictly
3525 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003526 NestingProhibited =
3527 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003528 Recommend = ShouldBeInTeamsRegion;
3529 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003530 if (!NestingProhibited &&
3531 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3532 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3533 // OpenMP 4.5 [2.17 Nesting of Regions]
3534 // If a target, target update, target data, target enter data, or
3535 // target exit data construct is encountered during execution of a
3536 // target region, the behavior is unspecified.
3537 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003538 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003539 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003540 if (isOpenMPTargetExecutionDirective(K)) {
3541 OffendingRegion = K;
3542 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003543 }
3544 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003545 },
3546 false /* don't skip top directive */);
3547 CloseNesting = false;
3548 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003549 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003550 if (OrphanSeen) {
3551 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3552 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3553 } else {
3554 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3555 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3556 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3557 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003558 return true;
3559 }
3560 }
3561 return false;
3562}
3563
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003564static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3565 ArrayRef<OMPClause *> Clauses,
3566 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3567 bool ErrorFound = false;
3568 unsigned NamedModifiersNumber = 0;
3569 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3570 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003571 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003572 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003573 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3574 // At most one if clause without a directive-name-modifier can appear on
3575 // the directive.
3576 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3577 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003578 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003579 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3580 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3581 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003582 } else if (CurNM != OMPD_unknown) {
3583 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003584 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003585 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003586 FoundNameModifiers[CurNM] = IC;
3587 if (CurNM == OMPD_unknown)
3588 continue;
3589 // Check if the specified name modifier is allowed for the current
3590 // directive.
3591 // At most one if clause with the particular directive-name-modifier can
3592 // appear on the directive.
3593 bool MatchFound = false;
3594 for (auto NM : AllowedNameModifiers) {
3595 if (CurNM == NM) {
3596 MatchFound = true;
3597 break;
3598 }
3599 }
3600 if (!MatchFound) {
3601 S.Diag(IC->getNameModifierLoc(),
3602 diag::err_omp_wrong_if_directive_name_modifier)
3603 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3604 ErrorFound = true;
3605 }
3606 }
3607 }
3608 // If any if clause on the directive includes a directive-name-modifier then
3609 // all if clauses on the directive must include a directive-name-modifier.
3610 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3611 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003612 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003613 diag::err_omp_no_more_if_clause);
3614 } else {
3615 std::string Values;
3616 std::string Sep(", ");
3617 unsigned AllowedCnt = 0;
3618 unsigned TotalAllowedNum =
3619 AllowedNameModifiers.size() - NamedModifiersNumber;
3620 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3621 ++Cnt) {
3622 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3623 if (!FoundNameModifiers[NM]) {
3624 Values += "'";
3625 Values += getOpenMPDirectiveName(NM);
3626 Values += "'";
3627 if (AllowedCnt + 2 == TotalAllowedNum)
3628 Values += " or ";
3629 else if (AllowedCnt + 1 != TotalAllowedNum)
3630 Values += Sep;
3631 ++AllowedCnt;
3632 }
3633 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003634 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003635 diag::err_omp_unnamed_if_clause)
3636 << (TotalAllowedNum > 1) << Values;
3637 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003638 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003639 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3640 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003641 ErrorFound = true;
3642 }
3643 return ErrorFound;
3644}
3645
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003646StmtResult Sema::ActOnOpenMPExecutableDirective(
3647 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3648 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3649 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003650 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003651 // First check CancelRegion which is then used in checkNestingOfRegions.
3652 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3653 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003654 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003655 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003656
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003657 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003658 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003659 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003660 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003661 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003662 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3663
3664 // Check default data sharing attributes for referenced variables.
3665 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003666 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3667 Stmt *S = AStmt;
3668 while (--ThisCaptureLevel >= 0)
3669 S = cast<CapturedStmt>(S)->getCapturedStmt();
3670 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003671 if (DSAChecker.isErrorFound())
3672 return StmtError();
3673 // Generate list of implicitly defined firstprivate variables.
3674 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003675
Alexey Bataev88202be2017-07-27 13:20:36 +00003676 SmallVector<Expr *, 4> ImplicitFirstprivates(
3677 DSAChecker.getImplicitFirstprivate().begin(),
3678 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003679 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3680 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003681 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003682 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003683 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003684 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003685 if (E)
3686 ImplicitFirstprivates.emplace_back(E);
3687 }
3688 }
3689 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003690 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003691 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3692 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003693 ClausesWithImplicit.push_back(Implicit);
3694 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003695 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003696 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003697 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003698 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003699 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003700 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003701 CXXScopeSpec MapperIdScopeSpec;
3702 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003703 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003704 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3705 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3706 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003707 ClausesWithImplicit.emplace_back(Implicit);
3708 ErrorFound |=
3709 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003710 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003711 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003712 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003713 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003714 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003715
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003716 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003717 switch (Kind) {
3718 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003719 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3720 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003721 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003722 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003723 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003724 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3725 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003726 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003727 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003728 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3729 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003730 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003731 case OMPD_for_simd:
3732 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3733 EndLoc, VarsWithInheritedDSA);
3734 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003735 case OMPD_sections:
3736 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3737 EndLoc);
3738 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003739 case OMPD_section:
3740 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003741 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003742 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3743 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003744 case OMPD_single:
3745 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3746 EndLoc);
3747 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003748 case OMPD_master:
3749 assert(ClausesWithImplicit.empty() &&
3750 "No clauses are allowed for 'omp master' directive");
3751 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3752 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003753 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003754 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3755 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003756 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003757 case OMPD_parallel_for:
3758 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3759 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003760 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003761 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003762 case OMPD_parallel_for_simd:
3763 Res = ActOnOpenMPParallelForSimdDirective(
3764 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003765 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003766 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003767 case OMPD_parallel_sections:
3768 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3769 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003770 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003771 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003772 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003773 Res =
3774 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003775 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003776 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003777 case OMPD_taskyield:
3778 assert(ClausesWithImplicit.empty() &&
3779 "No clauses are allowed for 'omp taskyield' directive");
3780 assert(AStmt == nullptr &&
3781 "No associated statement allowed for 'omp taskyield' directive");
3782 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3783 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003784 case OMPD_barrier:
3785 assert(ClausesWithImplicit.empty() &&
3786 "No clauses are allowed for 'omp barrier' directive");
3787 assert(AStmt == nullptr &&
3788 "No associated statement allowed for 'omp barrier' directive");
3789 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3790 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003791 case OMPD_taskwait:
3792 assert(ClausesWithImplicit.empty() &&
3793 "No clauses are allowed for 'omp taskwait' directive");
3794 assert(AStmt == nullptr &&
3795 "No associated statement allowed for 'omp taskwait' directive");
3796 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3797 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003798 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003799 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3800 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003801 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003802 case OMPD_flush:
3803 assert(AStmt == nullptr &&
3804 "No associated statement allowed for 'omp flush' directive");
3805 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3806 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003807 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003808 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3809 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003810 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003811 case OMPD_atomic:
3812 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3813 EndLoc);
3814 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003815 case OMPD_teams:
3816 Res =
3817 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3818 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003819 case OMPD_target:
3820 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3821 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003822 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003823 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003824 case OMPD_target_parallel:
3825 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3826 StartLoc, EndLoc);
3827 AllowedNameModifiers.push_back(OMPD_target);
3828 AllowedNameModifiers.push_back(OMPD_parallel);
3829 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003830 case OMPD_target_parallel_for:
3831 Res = ActOnOpenMPTargetParallelForDirective(
3832 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3833 AllowedNameModifiers.push_back(OMPD_target);
3834 AllowedNameModifiers.push_back(OMPD_parallel);
3835 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003836 case OMPD_cancellation_point:
3837 assert(ClausesWithImplicit.empty() &&
3838 "No clauses are allowed for 'omp cancellation point' directive");
3839 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3840 "cancellation point' directive");
3841 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3842 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003843 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003844 assert(AStmt == nullptr &&
3845 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003846 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3847 CancelRegion);
3848 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003849 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003850 case OMPD_target_data:
3851 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3852 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003853 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003854 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003855 case OMPD_target_enter_data:
3856 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003857 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003858 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3859 break;
Samuel Antao72590762016-01-19 20:04:50 +00003860 case OMPD_target_exit_data:
3861 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003862 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003863 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3864 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003865 case OMPD_taskloop:
3866 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3867 EndLoc, VarsWithInheritedDSA);
3868 AllowedNameModifiers.push_back(OMPD_taskloop);
3869 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003870 case OMPD_taskloop_simd:
3871 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3872 EndLoc, VarsWithInheritedDSA);
3873 AllowedNameModifiers.push_back(OMPD_taskloop);
3874 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003875 case OMPD_distribute:
3876 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3877 EndLoc, VarsWithInheritedDSA);
3878 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003879 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003880 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3881 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003882 AllowedNameModifiers.push_back(OMPD_target_update);
3883 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003884 case OMPD_distribute_parallel_for:
3885 Res = ActOnOpenMPDistributeParallelForDirective(
3886 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3887 AllowedNameModifiers.push_back(OMPD_parallel);
3888 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003889 case OMPD_distribute_parallel_for_simd:
3890 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3891 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3892 AllowedNameModifiers.push_back(OMPD_parallel);
3893 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003894 case OMPD_distribute_simd:
3895 Res = ActOnOpenMPDistributeSimdDirective(
3896 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3897 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003898 case OMPD_target_parallel_for_simd:
3899 Res = ActOnOpenMPTargetParallelForSimdDirective(
3900 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3901 AllowedNameModifiers.push_back(OMPD_target);
3902 AllowedNameModifiers.push_back(OMPD_parallel);
3903 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003904 case OMPD_target_simd:
3905 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3906 EndLoc, VarsWithInheritedDSA);
3907 AllowedNameModifiers.push_back(OMPD_target);
3908 break;
Kelvin Li02532872016-08-05 14:37:37 +00003909 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003910 Res = ActOnOpenMPTeamsDistributeDirective(
3911 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003912 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003913 case OMPD_teams_distribute_simd:
3914 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3915 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3916 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003917 case OMPD_teams_distribute_parallel_for_simd:
3918 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3919 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3920 AllowedNameModifiers.push_back(OMPD_parallel);
3921 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003922 case OMPD_teams_distribute_parallel_for:
3923 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3924 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3925 AllowedNameModifiers.push_back(OMPD_parallel);
3926 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003927 case OMPD_target_teams:
3928 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3929 EndLoc);
3930 AllowedNameModifiers.push_back(OMPD_target);
3931 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003932 case OMPD_target_teams_distribute:
3933 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3934 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3935 AllowedNameModifiers.push_back(OMPD_target);
3936 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003937 case OMPD_target_teams_distribute_parallel_for:
3938 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3939 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3940 AllowedNameModifiers.push_back(OMPD_target);
3941 AllowedNameModifiers.push_back(OMPD_parallel);
3942 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003943 case OMPD_target_teams_distribute_parallel_for_simd:
3944 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3945 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3946 AllowedNameModifiers.push_back(OMPD_target);
3947 AllowedNameModifiers.push_back(OMPD_parallel);
3948 break;
Kelvin Lida681182017-01-10 18:08:18 +00003949 case OMPD_target_teams_distribute_simd:
3950 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3951 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3952 AllowedNameModifiers.push_back(OMPD_target);
3953 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003954 case OMPD_declare_target:
3955 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003956 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003957 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003958 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003959 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003960 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003961 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003962 llvm_unreachable("OpenMP Directive is not allowed");
3963 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003964 llvm_unreachable("Unknown OpenMP directive");
3965 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003966
Roman Lebedevb5700602019-03-20 16:32:36 +00003967 ErrorFound = Res.isInvalid() || ErrorFound;
3968
Alexey Bataeve3727102018-04-18 15:57:46 +00003969 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003970 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3971 << P.first << P.second->getSourceRange();
3972 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003973 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3974
3975 if (!AllowedNameModifiers.empty())
3976 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3977 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003978
Alexey Bataeved09d242014-05-28 05:53:51 +00003979 if (ErrorFound)
3980 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00003981
3982 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3983 Res.getAs<OMPExecutableDirective>()
3984 ->getStructuredBlock()
3985 ->setIsOMPStructuredBlock(true);
3986 }
3987
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003988 return Res;
3989}
3990
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003991Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3992 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003993 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003994 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3995 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003996 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003997 assert(Linears.size() == LinModifiers.size());
3998 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003999 if (!DG || DG.get().isNull())
4000 return DeclGroupPtrTy();
4001
4002 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00004003 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004004 return DG;
4005 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004006 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004007 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4008 ADecl = FTD->getTemplatedDecl();
4009
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004010 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4011 if (!FD) {
4012 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004013 return DeclGroupPtrTy();
4014 }
4015
Alexey Bataev2af33e32016-04-07 12:45:37 +00004016 // OpenMP [2.8.2, declare simd construct, Description]
4017 // The parameter of the simdlen clause must be a constant positive integer
4018 // expression.
4019 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004020 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004021 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004022 // OpenMP [2.8.2, declare simd construct, Description]
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 uniform clause declares one or more arguments to have an invariant
4026 // value for all concurrent invocations of the function in the execution of a
4027 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004028 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4029 const Expr *UniformedLinearThis = nullptr;
4030 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004031 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004032 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4033 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004034 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4035 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004036 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004037 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004038 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004039 }
4040 if (isa<CXXThisExpr>(E)) {
4041 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004042 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004043 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004044 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4045 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004046 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004047 // OpenMP [2.8.2, declare simd construct, Description]
4048 // The aligned clause declares that the object to which each list item points
4049 // is aligned to the number of bytes expressed in the optional parameter of
4050 // the aligned clause.
4051 // The special this pointer can be used as if was one of the arguments to the
4052 // function in any of the linear, aligned, or uniform clauses.
4053 // The type of list items appearing in the aligned clause must be array,
4054 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004055 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4056 const Expr *AlignedThis = nullptr;
4057 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004058 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004059 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4060 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4061 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004062 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4063 FD->getParamDecl(PVD->getFunctionScopeIndex())
4064 ->getCanonicalDecl() == CanonPVD) {
4065 // OpenMP [2.8.1, simd construct, Restrictions]
4066 // A list-item cannot appear in more than one aligned clause.
4067 if (AlignedArgs.count(CanonPVD) > 0) {
4068 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4069 << 1 << E->getSourceRange();
4070 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4071 diag::note_omp_explicit_dsa)
4072 << getOpenMPClauseName(OMPC_aligned);
4073 continue;
4074 }
4075 AlignedArgs[CanonPVD] = E;
4076 QualType QTy = PVD->getType()
4077 .getNonReferenceType()
4078 .getUnqualifiedType()
4079 .getCanonicalType();
4080 const Type *Ty = QTy.getTypePtrOrNull();
4081 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4082 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4083 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4084 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4085 }
4086 continue;
4087 }
4088 }
4089 if (isa<CXXThisExpr>(E)) {
4090 if (AlignedThis) {
4091 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4092 << 2 << E->getSourceRange();
4093 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4094 << getOpenMPClauseName(OMPC_aligned);
4095 }
4096 AlignedThis = E;
4097 continue;
4098 }
4099 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4100 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4101 }
4102 // The optional parameter of the aligned clause, alignment, must be a constant
4103 // positive integer expression. If no optional parameter is specified,
4104 // implementation-defined default alignments for SIMD instructions on the
4105 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004106 SmallVector<const Expr *, 4> NewAligns;
4107 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004108 ExprResult Align;
4109 if (E)
4110 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4111 NewAligns.push_back(Align.get());
4112 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004113 // OpenMP [2.8.2, declare simd construct, Description]
4114 // The linear clause declares one or more list items to be private to a SIMD
4115 // lane and to have a linear relationship with respect to the iteration space
4116 // of a loop.
4117 // The special this pointer can be used as if was one of the arguments to the
4118 // function in any of the linear, aligned, or uniform clauses.
4119 // When a linear-step expression is specified in a linear clause it must be
4120 // either a constant integer expression or an integer-typed parameter that is
4121 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004122 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004123 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4124 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004125 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004126 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4127 ++MI;
4128 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004129 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4130 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4131 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004132 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4133 FD->getParamDecl(PVD->getFunctionScopeIndex())
4134 ->getCanonicalDecl() == CanonPVD) {
4135 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4136 // A list-item cannot appear in more than one linear clause.
4137 if (LinearArgs.count(CanonPVD) > 0) {
4138 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4139 << getOpenMPClauseName(OMPC_linear)
4140 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4141 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4142 diag::note_omp_explicit_dsa)
4143 << getOpenMPClauseName(OMPC_linear);
4144 continue;
4145 }
4146 // Each argument can appear in at most one uniform or linear clause.
4147 if (UniformedArgs.count(CanonPVD) > 0) {
4148 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4149 << getOpenMPClauseName(OMPC_linear)
4150 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4151 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4152 diag::note_omp_explicit_dsa)
4153 << getOpenMPClauseName(OMPC_uniform);
4154 continue;
4155 }
4156 LinearArgs[CanonPVD] = E;
4157 if (E->isValueDependent() || E->isTypeDependent() ||
4158 E->isInstantiationDependent() ||
4159 E->containsUnexpandedParameterPack())
4160 continue;
4161 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4162 PVD->getOriginalType());
4163 continue;
4164 }
4165 }
4166 if (isa<CXXThisExpr>(E)) {
4167 if (UniformedLinearThis) {
4168 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4169 << getOpenMPClauseName(OMPC_linear)
4170 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4171 << E->getSourceRange();
4172 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4173 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4174 : OMPC_linear);
4175 continue;
4176 }
4177 UniformedLinearThis = E;
4178 if (E->isValueDependent() || E->isTypeDependent() ||
4179 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4180 continue;
4181 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4182 E->getType());
4183 continue;
4184 }
4185 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4186 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4187 }
4188 Expr *Step = nullptr;
4189 Expr *NewStep = nullptr;
4190 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004191 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004192 // Skip the same step expression, it was checked already.
4193 if (Step == E || !E) {
4194 NewSteps.push_back(E ? NewStep : nullptr);
4195 continue;
4196 }
4197 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004198 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4199 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4200 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004201 if (UniformedArgs.count(CanonPVD) == 0) {
4202 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4203 << Step->getSourceRange();
4204 } else if (E->isValueDependent() || E->isTypeDependent() ||
4205 E->isInstantiationDependent() ||
4206 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004207 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004208 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004209 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004210 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4211 << Step->getSourceRange();
4212 }
4213 continue;
4214 }
4215 NewStep = Step;
4216 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4217 !Step->isInstantiationDependent() &&
4218 !Step->containsUnexpandedParameterPack()) {
4219 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4220 .get();
4221 if (NewStep)
4222 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4223 }
4224 NewSteps.push_back(NewStep);
4225 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004226 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4227 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004228 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004229 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4230 const_cast<Expr **>(Linears.data()), Linears.size(),
4231 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4232 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004233 ADecl->addAttr(NewAttr);
4234 return ConvertDeclToDeclGroup(ADecl);
4235}
4236
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004237StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4238 Stmt *AStmt,
4239 SourceLocation StartLoc,
4240 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004241 if (!AStmt)
4242 return StmtError();
4243
Alexey Bataeve3727102018-04-18 15:57:46 +00004244 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004245 // 1.2.2 OpenMP Language Terminology
4246 // Structured block - An executable statement with a single entry at the
4247 // top and a single exit at the bottom.
4248 // The point of exit cannot be a branch out of the structured block.
4249 // longjmp() and throw() must not violate the entry/exit criteria.
4250 CS->getCapturedDecl()->setNothrow();
4251
Reid Kleckner87a31802018-03-12 21:43:02 +00004252 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004253
Alexey Bataev25e5b442015-09-15 12:52:43 +00004254 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4255 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004256}
4257
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004258namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004259/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004260/// extracting iteration space of each loop in the loop nest, that will be used
4261/// for IR generation.
4262class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004263 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004264 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004265 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004266 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004267 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004268 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004269 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004270 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004271 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004272 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004273 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004274 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004275 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004276 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004277 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004278 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004279 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004280 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004281 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004282 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004283 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004284 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004285 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004286 /// Var < UB
4287 /// Var <= UB
4288 /// UB > Var
4289 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004290 /// This will have no value when the condition is !=
4291 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004292 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004293 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004294 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004295 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004296
4297public:
4298 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004299 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004300 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004301 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004302 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004303 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004304 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004306 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004307 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004308 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004309 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004310 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004311 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004312 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004313 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004314 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004315 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004316 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004317 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004318 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004319 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004320 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004321 /// True, if the compare operator is strict (<, > or !=).
4322 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004323 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004324 Expr *buildNumIterations(
4325 Scope *S, const bool LimitedType,
4326 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004327 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004328 Expr *
4329 buildPreCond(Scope *S, Expr *Cond,
4330 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004331 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004332 DeclRefExpr *
4333 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4334 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004335 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004336 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004337 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004338 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004339 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004340 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004341 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004342 /// Build loop data with counter value for depend clauses in ordered
4343 /// directives.
4344 Expr *
4345 buildOrderedLoopData(Scope *S, Expr *Counter,
4346 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4347 SourceLocation Loc, Expr *Inc = nullptr,
4348 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004349 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004350 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004351
4352private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004353 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004354 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004355 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004356 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004357 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004358 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004359 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4360 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004361 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004362 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004363};
4364
Alexey Bataeve3727102018-04-18 15:57:46 +00004365bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004366 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004367 assert(!LB && !UB && !Step);
4368 return false;
4369 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004370 return LCDecl->getType()->isDependentType() ||
4371 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4372 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004373}
4374
Alexey Bataeve3727102018-04-18 15:57:46 +00004375bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004376 Expr *NewLCRefExpr,
4377 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004378 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004379 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004380 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004381 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004382 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004383 LCDecl = getCanonicalDecl(NewLCDecl);
4384 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004385 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4386 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004387 if ((Ctor->isCopyOrMoveConstructor() ||
4388 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4389 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004390 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004391 LB = NewLB;
4392 return false;
4393}
4394
Alexey Bataev316ccf62019-01-29 18:51:58 +00004395bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4396 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004397 bool StrictOp, SourceRange SR,
4398 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004399 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004400 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4401 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004402 if (!NewUB)
4403 return true;
4404 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004405 if (LessOp)
4406 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004407 TestIsStrictOp = StrictOp;
4408 ConditionSrcRange = SR;
4409 ConditionLoc = SL;
4410 return false;
4411}
4412
Alexey Bataeve3727102018-04-18 15:57:46 +00004413bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004414 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004415 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004416 if (!NewStep)
4417 return true;
4418 if (!NewStep->isValueDependent()) {
4419 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004420 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004421 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4422 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004423 if (Val.isInvalid())
4424 return true;
4425 NewStep = Val.get();
4426
4427 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4428 // If test-expr is of form var relational-op b and relational-op is < or
4429 // <= then incr-expr must cause var to increase on each iteration of the
4430 // loop. If test-expr is of form var relational-op b and relational-op is
4431 // > or >= then incr-expr must cause var to decrease on each iteration of
4432 // the loop.
4433 // If test-expr is of form b relational-op var and relational-op is < or
4434 // <= then incr-expr must cause var to decrease on each iteration of the
4435 // loop. If test-expr is of form b relational-op var and relational-op is
4436 // > or >= then incr-expr must cause var to increase on each iteration of
4437 // the loop.
4438 llvm::APSInt Result;
4439 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4440 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4441 bool IsConstNeg =
4442 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004443 bool IsConstPos =
4444 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004445 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004446
4447 // != with increment is treated as <; != with decrement is treated as >
4448 if (!TestIsLessOp.hasValue())
4449 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004450 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004451 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004452 (IsConstNeg || (IsUnsigned && Subtract)) :
4453 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004454 SemaRef.Diag(NewStep->getExprLoc(),
4455 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004456 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004457 SemaRef.Diag(ConditionLoc,
4458 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004459 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004460 return true;
4461 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004462 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004463 NewStep =
4464 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4465 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004466 Subtract = !Subtract;
4467 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004468 }
4469
4470 Step = NewStep;
4471 SubtractStep = Subtract;
4472 return false;
4473}
4474
Alexey Bataeve3727102018-04-18 15:57:46 +00004475bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004476 // Check init-expr for canonical loop form and save loop counter
4477 // variable - #Var and its initialization value - #LB.
4478 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4479 // var = lb
4480 // integer-type var = lb
4481 // random-access-iterator-type var = lb
4482 // pointer-type var = lb
4483 //
4484 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004485 if (EmitDiags) {
4486 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4487 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004488 return true;
4489 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004490 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4491 if (!ExprTemp->cleanupsHaveSideEffects())
4492 S = ExprTemp->getSubExpr();
4493
Alexander Musmana5f070a2014-10-01 06:03:56 +00004494 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004495 if (Expr *E = dyn_cast<Expr>(S))
4496 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004497 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004498 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004499 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004500 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4501 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4502 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004503 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4504 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004505 }
4506 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4507 if (ME->isArrow() &&
4508 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004509 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004510 }
4511 }
David Majnemer9d168222016-08-05 17:44:54 +00004512 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004513 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004514 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004515 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004516 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004517 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004518 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004519 diag::ext_omp_loop_not_canonical_init)
4520 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004521 return setLCDeclAndLB(
4522 Var,
4523 buildDeclRefExpr(SemaRef, Var,
4524 Var->getType().getNonReferenceType(),
4525 DS->getBeginLoc()),
4526 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004527 }
4528 }
4529 }
David Majnemer9d168222016-08-05 17:44:54 +00004530 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004531 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004532 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004533 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004534 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4535 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004536 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4537 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004538 }
4539 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4540 if (ME->isArrow() &&
4541 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004542 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004543 }
4544 }
4545 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004546
Alexey Bataeve3727102018-04-18 15:57:46 +00004547 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004548 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004549 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004550 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004551 << S->getSourceRange();
4552 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004553 return true;
4554}
4555
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004556/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004557/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004558static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004559 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004560 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004561 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004562 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004563 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004564 if ((Ctor->isCopyOrMoveConstructor() ||
4565 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4566 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004567 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004568 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4569 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004570 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004571 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004572 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004573 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4574 return getCanonicalDecl(ME->getMemberDecl());
4575 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004576}
4577
Alexey Bataeve3727102018-04-18 15:57:46 +00004578bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004579 // Check test-expr for canonical form, save upper-bound UB, flags for
4580 // less/greater and for strict/non-strict comparison.
4581 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4582 // var relational-op b
4583 // b relational-op var
4584 //
4585 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004586 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004587 return true;
4588 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004589 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004590 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004591 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004592 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004593 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4594 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004595 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4596 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4597 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004598 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4599 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004600 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4601 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4602 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004603 } else if (BO->getOpcode() == BO_NE)
4604 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4605 BO->getRHS() : BO->getLHS(),
4606 /*LessOp=*/llvm::None,
4607 /*StrictOp=*/true,
4608 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004609 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004610 if (CE->getNumArgs() == 2) {
4611 auto Op = CE->getOperator();
4612 switch (Op) {
4613 case OO_Greater:
4614 case OO_GreaterEqual:
4615 case OO_Less:
4616 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004617 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4618 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004619 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4620 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004621 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4622 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004623 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4624 CE->getOperatorLoc());
4625 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004626 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004627 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4628 CE->getArg(1) : CE->getArg(0),
4629 /*LessOp=*/llvm::None,
4630 /*StrictOp=*/true,
4631 CE->getSourceRange(),
4632 CE->getOperatorLoc());
4633 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004634 default:
4635 break;
4636 }
4637 }
4638 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004639 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004640 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004641 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004642 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004643 return true;
4644}
4645
Alexey Bataeve3727102018-04-18 15:57:46 +00004646bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004647 // RHS of canonical loop form increment can be:
4648 // var + incr
4649 // incr + var
4650 // var - incr
4651 //
4652 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004653 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004654 if (BO->isAdditiveOp()) {
4655 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004656 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4657 return setStep(BO->getRHS(), !IsAdd);
4658 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4659 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004660 }
David Majnemer9d168222016-08-05 17:44:54 +00004661 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004662 bool IsAdd = CE->getOperator() == OO_Plus;
4663 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004664 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4665 return setStep(CE->getArg(1), !IsAdd);
4666 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4667 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004668 }
4669 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004670 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004671 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004672 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004673 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004674 return true;
4675}
4676
Alexey Bataeve3727102018-04-18 15:57:46 +00004677bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004678 // Check incr-expr for canonical loop form and return true if it
4679 // does not conform.
4680 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4681 // ++var
4682 // var++
4683 // --var
4684 // var--
4685 // var += incr
4686 // var -= incr
4687 // var = var + incr
4688 // var = incr + var
4689 // var = var - incr
4690 //
4691 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004692 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004693 return true;
4694 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004695 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4696 if (!ExprTemp->cleanupsHaveSideEffects())
4697 S = ExprTemp->getSubExpr();
4698
Alexander Musmana5f070a2014-10-01 06:03:56 +00004699 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004700 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004701 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004702 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004703 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4704 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004705 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004706 (UO->isDecrementOp() ? -1 : 1))
4707 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004708 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004709 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004710 switch (BO->getOpcode()) {
4711 case BO_AddAssign:
4712 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004713 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4714 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004715 break;
4716 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004717 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4718 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004719 break;
4720 default:
4721 break;
4722 }
David Majnemer9d168222016-08-05 17:44:54 +00004723 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004724 switch (CE->getOperator()) {
4725 case OO_PlusPlus:
4726 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004727 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4728 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004729 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004730 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004731 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4732 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004733 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004734 break;
4735 case OO_PlusEqual:
4736 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004737 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4738 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004739 break;
4740 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004741 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4742 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004743 break;
4744 default:
4745 break;
4746 }
4747 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004748 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004749 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004750 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004751 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004752 return true;
4753}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004754
Alexey Bataev5a3af132016-03-29 08:58:54 +00004755static ExprResult
4756tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004757 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004758 if (SemaRef.CurContext->isDependentContext())
4759 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004760 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4761 return SemaRef.PerformImplicitConversion(
4762 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4763 /*AllowExplicit=*/true);
4764 auto I = Captures.find(Capture);
4765 if (I != Captures.end())
4766 return buildCapture(SemaRef, Capture, I->second);
4767 DeclRefExpr *Ref = nullptr;
4768 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4769 Captures[Capture] = Ref;
4770 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004771}
4772
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004773/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004774Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004775 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004776 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004777 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004778 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004779 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004780 SemaRef.getLangOpts().CPlusPlus) {
4781 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004782 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4783 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004784 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4785 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004786 if (!Upper || !Lower)
4787 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004788
4789 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4790
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004791 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004792 // BuildBinOp already emitted error, this one is to point user to upper
4793 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004794 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004795 << Upper->getSourceRange() << Lower->getSourceRange();
4796 return nullptr;
4797 }
4798 }
4799
4800 if (!Diff.isUsable())
4801 return nullptr;
4802
4803 // Upper - Lower [- 1]
4804 if (TestIsStrictOp)
4805 Diff = SemaRef.BuildBinOp(
4806 S, DefaultLoc, BO_Sub, Diff.get(),
4807 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4808 if (!Diff.isUsable())
4809 return nullptr;
4810
4811 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004812 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004813 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004814 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004815 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004816 if (!Diff.isUsable())
4817 return nullptr;
4818
4819 // Parentheses (for dumping/debugging purposes only).
4820 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4821 if (!Diff.isUsable())
4822 return nullptr;
4823
4824 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004825 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004826 if (!Diff.isUsable())
4827 return nullptr;
4828
Alexander Musman174b3ca2014-10-06 11:16:29 +00004829 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004830 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004831 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004832 bool UseVarType = VarType->hasIntegerRepresentation() &&
4833 C.getTypeSize(Type) > C.getTypeSize(VarType);
4834 if (!Type->isIntegerType() || UseVarType) {
4835 unsigned NewSize =
4836 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4837 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4838 : Type->hasSignedIntegerRepresentation();
4839 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004840 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4841 Diff = SemaRef.PerformImplicitConversion(
4842 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4843 if (!Diff.isUsable())
4844 return nullptr;
4845 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004846 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004847 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004848 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4849 if (NewSize != C.getTypeSize(Type)) {
4850 if (NewSize < C.getTypeSize(Type)) {
4851 assert(NewSize == 64 && "incorrect loop var size");
4852 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4853 << InitSrcRange << ConditionSrcRange;
4854 }
4855 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004856 NewSize, Type->hasSignedIntegerRepresentation() ||
4857 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004858 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4859 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4860 Sema::AA_Converting, true);
4861 if (!Diff.isUsable())
4862 return nullptr;
4863 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004864 }
4865 }
4866
Alexander Musmana5f070a2014-10-01 06:03:56 +00004867 return Diff.get();
4868}
4869
Alexey Bataeve3727102018-04-18 15:57:46 +00004870Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004871 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004872 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004873 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4874 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4875 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004876
Alexey Bataeve3727102018-04-18 15:57:46 +00004877 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4878 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004879 if (!NewLB.isUsable() || !NewUB.isUsable())
4880 return nullptr;
4881
Alexey Bataeve3727102018-04-18 15:57:46 +00004882 ExprResult CondExpr =
4883 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004884 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004885 (TestIsStrictOp ? BO_LT : BO_LE) :
4886 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004887 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004888 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004889 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4890 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004891 CondExpr = SemaRef.PerformImplicitConversion(
4892 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4893 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004894 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004895 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004896 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004897 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4898}
4899
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004900/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004901DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004902 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4903 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004904 auto *VD = dyn_cast<VarDecl>(LCDecl);
4905 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004906 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4907 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004908 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004909 const DSAStackTy::DSAVarData Data =
4910 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004911 // If the loop control decl is explicitly marked as private, do not mark it
4912 // as captured again.
4913 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4914 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004915 return Ref;
4916 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00004917 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00004918}
4919
Alexey Bataeve3727102018-04-18 15:57:46 +00004920Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004921 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004922 QualType Type = LCDecl->getType().getNonReferenceType();
4923 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004924 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4925 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4926 isa<VarDecl>(LCDecl)
4927 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4928 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004929 if (PrivateVar->isInvalidDecl())
4930 return nullptr;
4931 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4932 }
4933 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004934}
4935
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004936/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004937Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004938
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004939/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004940Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004941
Alexey Bataevf138fda2018-08-13 19:04:24 +00004942Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4943 Scope *S, Expr *Counter,
4944 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4945 Expr *Inc, OverloadedOperatorKind OOK) {
4946 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4947 if (!Cnt)
4948 return nullptr;
4949 if (Inc) {
4950 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4951 "Expected only + or - operations for depend clauses.");
4952 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4953 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4954 if (!Cnt)
4955 return nullptr;
4956 }
4957 ExprResult Diff;
4958 QualType VarType = LCDecl->getType().getNonReferenceType();
4959 if (VarType->isIntegerType() || VarType->isPointerType() ||
4960 SemaRef.getLangOpts().CPlusPlus) {
4961 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004962 Expr *Upper = TestIsLessOp.getValue()
4963 ? Cnt
4964 : tryBuildCapture(SemaRef, UB, Captures).get();
4965 Expr *Lower = TestIsLessOp.getValue()
4966 ? tryBuildCapture(SemaRef, LB, Captures).get()
4967 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004968 if (!Upper || !Lower)
4969 return nullptr;
4970
4971 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4972
4973 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4974 // BuildBinOp already emitted error, this one is to point user to upper
4975 // and lower bound, and to tell what is passed to 'operator-'.
4976 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4977 << Upper->getSourceRange() << Lower->getSourceRange();
4978 return nullptr;
4979 }
4980 }
4981
4982 if (!Diff.isUsable())
4983 return nullptr;
4984
4985 // Parentheses (for dumping/debugging purposes only).
4986 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4987 if (!Diff.isUsable())
4988 return nullptr;
4989
4990 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4991 if (!NewStep.isUsable())
4992 return nullptr;
4993 // (Upper - Lower) / Step
4994 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4995 if (!Diff.isUsable())
4996 return nullptr;
4997
4998 return Diff.get();
4999}
5000
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005001/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005002struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005003 /// True if the condition operator is the strict compare operator (<, > or
5004 /// !=).
5005 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005006 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005007 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005008 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005009 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005010 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005011 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005012 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005013 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005014 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005015 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00005016 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005017 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005018 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005019 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005020 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005021 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005022 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005023 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005024 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005025 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005026 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005027 SourceRange IncSrcRange;
5028};
5029
Alexey Bataev23b69422014-06-18 07:08:49 +00005030} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005031
Alexey Bataev9c821032015-04-30 04:23:23 +00005032void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5033 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5034 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005035 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5036 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005037 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005038 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00005039 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005040 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5041 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005042 auto *VD = dyn_cast<VarDecl>(D);
5043 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005044 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005045 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005046 } else {
5047 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5048 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005049 VD = cast<VarDecl>(Ref->getDecl());
5050 }
5051 }
5052 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005053 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5054 if (LD != D->getCanonicalDecl()) {
5055 DSAStack->resetPossibleLoopCounter();
5056 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5057 MarkDeclarationsReferencedInExpr(
5058 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5059 Var->getType().getNonLValueExprType(Context),
5060 ForLoc, /*RefersToCapture=*/true));
5061 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005062 }
5063 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005064 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005065 }
5066}
5067
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005068/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005069/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005070static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005071 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5072 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005073 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5074 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005075 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005076 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005077 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005078 // OpenMP [2.6, Canonical Loop Form]
5079 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005080 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005081 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005082 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005083 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005084 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005085 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005086 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005087 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5088 SemaRef.Diag(DSA.getConstructLoc(),
5089 diag::note_omp_collapse_ordered_expr)
5090 << 2 << CollapseLoopCountExpr->getSourceRange()
5091 << OrderedLoopCountExpr->getSourceRange();
5092 else if (CollapseLoopCountExpr)
5093 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5094 diag::note_omp_collapse_ordered_expr)
5095 << 0 << CollapseLoopCountExpr->getSourceRange();
5096 else
5097 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5098 diag::note_omp_collapse_ordered_expr)
5099 << 1 << OrderedLoopCountExpr->getSourceRange();
5100 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005101 return true;
5102 }
5103 assert(For->getBody());
5104
5105 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5106
5107 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005108 Stmt *Init = For->getInit();
5109 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005110 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005111
5112 bool HasErrors = false;
5113
5114 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005115 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5116 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005117
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005118 // OpenMP [2.6, Canonical Loop Form]
5119 // Var is one of the following:
5120 // A variable of signed or unsigned integer type.
5121 // For C++, a variable of a random access iterator type.
5122 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005123 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005124 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5125 !VarType->isPointerType() &&
5126 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005127 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005128 << SemaRef.getLangOpts().CPlusPlus;
5129 HasErrors = true;
5130 }
5131
5132 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5133 // a Construct
5134 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5135 // parallel for construct is (are) private.
5136 // The loop iteration variable in the associated for-loop of a simd
5137 // construct with just one associated for-loop is linear with a
5138 // constant-linear-step that is the increment of the associated for-loop.
5139 // Exclude loop var from the list of variables with implicitly defined data
5140 // sharing attributes.
5141 VarsWithImplicitDSA.erase(LCDecl);
5142
5143 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5144 // in a Construct, C/C++].
5145 // The loop iteration variable in the associated for-loop of a simd
5146 // construct with just one associated for-loop may be listed in a linear
5147 // clause with a constant-linear-step that is the increment of the
5148 // associated for-loop.
5149 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5150 // parallel for construct may be listed in a private or lastprivate clause.
5151 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5152 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5153 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005154 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005155 isOpenMPSimdDirective(DKind)
5156 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5157 : OMPC_private;
5158 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5159 DVar.CKind != PredeterminedCKind) ||
5160 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5161 isOpenMPDistributeDirective(DKind)) &&
5162 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5163 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5164 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005165 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005166 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5167 << getOpenMPClauseName(PredeterminedCKind);
5168 if (DVar.RefExpr == nullptr)
5169 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005170 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005171 HasErrors = true;
5172 } else if (LoopDeclRefExpr != nullptr) {
5173 // Make the loop iteration variable private (for worksharing constructs),
5174 // linear (for simd directives with the only one associated loop) or
5175 // lastprivate (for simd directives with several collapsed or ordered
5176 // loops).
5177 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005178 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005179 }
5180
5181 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5182
5183 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005184 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005185
5186 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005187 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005188 }
5189
Alexey Bataeve3727102018-04-18 15:57:46 +00005190 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005191 return HasErrors;
5192
Alexander Musmana5f070a2014-10-01 06:03:56 +00005193 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005194 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005195 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5196 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005197 DSA.getCurScope(),
5198 (isOpenMPWorksharingDirective(DKind) ||
5199 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5200 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005201 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5202 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5203 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5204 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5205 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5206 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5207 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5208 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005209 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005210
Alexey Bataev62dbb972015-04-22 11:59:37 +00005211 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5212 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005213 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005214 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005215 ResultIterSpace.CounterInit == nullptr ||
5216 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005217 if (!HasErrors && DSA.isOrderedRegion()) {
5218 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5219 if (CurrentNestedLoopCount <
5220 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5221 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5222 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5223 DSA.getOrderedRegionParam().second->setLoopCounter(
5224 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5225 }
5226 }
5227 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5228 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5229 // Erroneous case - clause has some problems.
5230 continue;
5231 }
5232 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5233 Pair.second.size() <= CurrentNestedLoopCount) {
5234 // Erroneous case - clause has some problems.
5235 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5236 continue;
5237 }
5238 Expr *CntValue;
5239 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5240 CntValue = ISC.buildOrderedLoopData(
5241 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5242 Pair.first->getDependencyLoc());
5243 else
5244 CntValue = ISC.buildOrderedLoopData(
5245 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5246 Pair.first->getDependencyLoc(),
5247 Pair.second[CurrentNestedLoopCount].first,
5248 Pair.second[CurrentNestedLoopCount].second);
5249 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5250 }
5251 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005252
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005253 return HasErrors;
5254}
5255
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005256/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005257static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005258buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005259 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005260 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005261 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005262 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005263 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005264 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005265 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005266 VarRef.get()->getType())) {
5267 NewStart = SemaRef.PerformImplicitConversion(
5268 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5269 /*AllowExplicit=*/true);
5270 if (!NewStart.isUsable())
5271 return ExprError();
5272 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005273
Alexey Bataeve3727102018-04-18 15:57:46 +00005274 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005275 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5276 return Init;
5277}
5278
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005279/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005280static ExprResult buildCounterUpdate(
5281 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5282 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5283 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005284 // Add parentheses (for debugging purposes only).
5285 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5286 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5287 !Step.isUsable())
5288 return ExprError();
5289
Alexey Bataev5a3af132016-03-29 08:58:54 +00005290 ExprResult NewStep = Step;
5291 if (Captures)
5292 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005293 if (NewStep.isInvalid())
5294 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005295 ExprResult Update =
5296 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005297 if (!Update.isUsable())
5298 return ExprError();
5299
Alexey Bataevc0214e02016-02-16 12:13:49 +00005300 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5301 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005302 ExprResult NewStart = Start;
5303 if (Captures)
5304 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005305 if (NewStart.isInvalid())
5306 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005307
Alexey Bataevc0214e02016-02-16 12:13:49 +00005308 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5309 ExprResult SavedUpdate = Update;
5310 ExprResult UpdateVal;
5311 if (VarRef.get()->getType()->isOverloadableType() ||
5312 NewStart.get()->getType()->isOverloadableType() ||
5313 Update.get()->getType()->isOverloadableType()) {
5314 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5315 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5316 Update =
5317 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5318 if (Update.isUsable()) {
5319 UpdateVal =
5320 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5321 VarRef.get(), SavedUpdate.get());
5322 if (UpdateVal.isUsable()) {
5323 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5324 UpdateVal.get());
5325 }
5326 }
5327 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5328 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005329
Alexey Bataevc0214e02016-02-16 12:13:49 +00005330 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5331 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5332 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5333 NewStart.get(), SavedUpdate.get());
5334 if (!Update.isUsable())
5335 return ExprError();
5336
Alexey Bataev11481f52016-02-17 10:29:05 +00005337 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5338 VarRef.get()->getType())) {
5339 Update = SemaRef.PerformImplicitConversion(
5340 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5341 if (!Update.isUsable())
5342 return ExprError();
5343 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005344
5345 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5346 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005347 return Update;
5348}
5349
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005350/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005351/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005352static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005353 if (E == nullptr)
5354 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005355 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005356 QualType OldType = E->getType();
5357 unsigned HasBits = C.getTypeSize(OldType);
5358 if (HasBits >= Bits)
5359 return ExprResult(E);
5360 // OK to convert to signed, because new type has more bits than old.
5361 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5362 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5363 true);
5364}
5365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005366/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005367/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005368static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005369 if (E == nullptr)
5370 return false;
5371 llvm::APSInt Result;
5372 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5373 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5374 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005375}
5376
Alexey Bataev5a3af132016-03-29 08:58:54 +00005377/// Build preinits statement for the given declarations.
5378static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005379 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005380 if (!PreInits.empty()) {
5381 return new (Context) DeclStmt(
5382 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5383 SourceLocation(), SourceLocation());
5384 }
5385 return nullptr;
5386}
5387
5388/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005389static Stmt *
5390buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005391 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005392 if (!Captures.empty()) {
5393 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005394 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005395 PreInits.push_back(Pair.second->getDecl());
5396 return buildPreInits(Context, PreInits);
5397 }
5398 return nullptr;
5399}
5400
5401/// Build postupdate expression for the given list of postupdates expressions.
5402static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5403 Expr *PostUpdate = nullptr;
5404 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005405 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005406 Expr *ConvE = S.BuildCStyleCastExpr(
5407 E->getExprLoc(),
5408 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5409 E->getExprLoc(), E)
5410 .get();
5411 PostUpdate = PostUpdate
5412 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5413 PostUpdate, ConvE)
5414 .get()
5415 : ConvE;
5416 }
5417 }
5418 return PostUpdate;
5419}
5420
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005421/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005422/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5423/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005424static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005425checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005426 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5427 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005428 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005429 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005430 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005431 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005432 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005433 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005434 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005435 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005436 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005437 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005438 if (OrderedLoopCountExpr) {
5439 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005440 Expr::EvalResult EVResult;
5441 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5442 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005443 if (Result.getLimitedValue() < NestedLoopCount) {
5444 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5445 diag::err_omp_wrong_ordered_loop_count)
5446 << OrderedLoopCountExpr->getSourceRange();
5447 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5448 diag::note_collapse_loop_count)
5449 << CollapseLoopCountExpr->getSourceRange();
5450 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005451 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005452 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005453 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005454 // This is helper routine for loop directives (e.g., 'for', 'simd',
5455 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005456 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005457 SmallVector<LoopIterationSpace, 4> IterSpaces(
5458 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005459 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005460 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005461 if (checkOpenMPIterationSpace(
5462 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5463 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5464 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5465 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005466 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005467 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005468 // OpenMP [2.8.1, simd construct, Restrictions]
5469 // All loops associated with the construct must be perfectly nested; that
5470 // is, there must be no intervening code nor any OpenMP directive between
5471 // any two loops.
5472 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005473 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005474 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5475 if (checkOpenMPIterationSpace(
5476 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5477 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5478 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5479 Captures))
5480 return 0;
5481 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5482 // Handle initialization of captured loop iterator variables.
5483 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5484 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5485 Captures[DRE] = DRE;
5486 }
5487 }
5488 // Move on to the next nested for loop, or to the loop body.
5489 // OpenMP [2.8.1, simd construct, Restrictions]
5490 // All loops associated with the construct must be perfectly nested; that
5491 // is, there must be no intervening code nor any OpenMP directive between
5492 // any two loops.
5493 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5494 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005495
Alexander Musmana5f070a2014-10-01 06:03:56 +00005496 Built.clear(/* size */ NestedLoopCount);
5497
5498 if (SemaRef.CurContext->isDependentContext())
5499 return NestedLoopCount;
5500
5501 // An example of what is generated for the following code:
5502 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005503 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005504 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005505 // for (k = 0; k < NK; ++k)
5506 // for (j = J0; j < NJ; j+=2) {
5507 // <loop body>
5508 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005509 //
5510 // We generate the code below.
5511 // Note: the loop body may be outlined in CodeGen.
5512 // Note: some counters may be C++ classes, operator- is used to find number of
5513 // iterations and operator+= to calculate counter value.
5514 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5515 // or i64 is currently supported).
5516 //
5517 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5518 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5519 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5520 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5521 // // similar updates for vars in clauses (e.g. 'linear')
5522 // <loop body (using local i and j)>
5523 // }
5524 // i = NI; // assign final values of counters
5525 // j = NJ;
5526 //
5527
5528 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5529 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005530 // Precondition tests if there is at least one iteration (all conditions are
5531 // true).
5532 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005533 Expr *N0 = IterSpaces[0].NumIterations;
5534 ExprResult LastIteration32 =
5535 widenIterationCount(/*Bits=*/32,
5536 SemaRef
5537 .PerformImplicitConversion(
5538 N0->IgnoreImpCasts(), N0->getType(),
5539 Sema::AA_Converting, /*AllowExplicit=*/true)
5540 .get(),
5541 SemaRef);
5542 ExprResult LastIteration64 = widenIterationCount(
5543 /*Bits=*/64,
5544 SemaRef
5545 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5546 Sema::AA_Converting,
5547 /*AllowExplicit=*/true)
5548 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005549 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005550
5551 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5552 return NestedLoopCount;
5553
Alexey Bataeve3727102018-04-18 15:57:46 +00005554 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005555 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5556
5557 Scope *CurScope = DSA.getCurScope();
5558 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005559 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005560 PreCond =
5561 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5562 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005563 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005564 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005565 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005566 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5567 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005568 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005569 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005570 SemaRef
5571 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5572 Sema::AA_Converting,
5573 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005574 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005575 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005576 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005577 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005578 SemaRef
5579 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5580 Sema::AA_Converting,
5581 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005582 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005583 }
5584
5585 // Choose either the 32-bit or 64-bit version.
5586 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005587 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5588 (LastIteration32.isUsable() &&
5589 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5590 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5591 fitsInto(
5592 /*Bits=*/32,
5593 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5594 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005595 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005596 QualType VType = LastIteration.get()->getType();
5597 QualType RealVType = VType;
5598 QualType StrideVType = VType;
5599 if (isOpenMPTaskLoopDirective(DKind)) {
5600 VType =
5601 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5602 StrideVType =
5603 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5604 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005605
5606 if (!LastIteration.isUsable())
5607 return 0;
5608
5609 // Save the number of iterations.
5610 ExprResult NumIterations = LastIteration;
5611 {
5612 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005613 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5614 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005615 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5616 if (!LastIteration.isUsable())
5617 return 0;
5618 }
5619
5620 // Calculate the last iteration number beforehand instead of doing this on
5621 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5622 llvm::APSInt Result;
5623 bool IsConstant =
5624 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5625 ExprResult CalcLastIteration;
5626 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005627 ExprResult SaveRef =
5628 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005629 LastIteration = SaveRef;
5630
5631 // Prepare SaveRef + 1.
5632 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005633 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005634 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5635 if (!NumIterations.isUsable())
5636 return 0;
5637 }
5638
5639 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5640
David Majnemer9d168222016-08-05 17:44:54 +00005641 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005642 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005643 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5644 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005645 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005646 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5647 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005648 SemaRef.AddInitializerToDecl(LBDecl,
5649 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5650 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005651
5652 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005653 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5654 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005655 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005656 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005657
5658 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5659 // This will be used to implement clause 'lastprivate'.
5660 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005661 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5662 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005663 SemaRef.AddInitializerToDecl(ILDecl,
5664 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5665 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005666
5667 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005668 VarDecl *STDecl =
5669 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5670 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005671 SemaRef.AddInitializerToDecl(STDecl,
5672 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5673 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005674
5675 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005676 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005677 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5678 UB.get(), LastIteration.get());
5679 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005680 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5681 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005682 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5683 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005684 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005685
5686 // If we have a combined directive that combines 'distribute', 'for' or
5687 // 'simd' we need to be able to access the bounds of the schedule of the
5688 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5689 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5690 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005691 // Lower bound variable, initialized with zero.
5692 VarDecl *CombLBDecl =
5693 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5694 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5695 SemaRef.AddInitializerToDecl(
5696 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5697 /*DirectInit*/ false);
5698
5699 // Upper bound variable, initialized with last iteration number.
5700 VarDecl *CombUBDecl =
5701 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5702 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5703 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5704 /*DirectInit*/ false);
5705
5706 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5707 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5708 ExprResult CombCondOp =
5709 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5710 LastIteration.get(), CombUB.get());
5711 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5712 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005713 CombEUB =
5714 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005715
Alexey Bataeve3727102018-04-18 15:57:46 +00005716 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005717 // We expect to have at least 2 more parameters than the 'parallel'
5718 // directive does - the lower and upper bounds of the previous schedule.
5719 assert(CD->getNumParams() >= 4 &&
5720 "Unexpected number of parameters in loop combined directive");
5721
5722 // Set the proper type for the bounds given what we learned from the
5723 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005724 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5725 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005726
5727 // Previous lower and upper bounds are obtained from the region
5728 // parameters.
5729 PrevLB =
5730 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5731 PrevUB =
5732 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5733 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005734 }
5735
5736 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005737 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005738 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005739 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005740 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5741 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005742 Expr *RHS =
5743 (isOpenMPWorksharingDirective(DKind) ||
5744 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5745 ? LB.get()
5746 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005747 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005748 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005749
5750 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5751 Expr *CombRHS =
5752 (isOpenMPWorksharingDirective(DKind) ||
5753 isOpenMPTaskLoopDirective(DKind) ||
5754 isOpenMPDistributeDirective(DKind))
5755 ? CombLB.get()
5756 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5757 CombInit =
5758 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005759 CombInit =
5760 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005761 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005762 }
5763
Alexey Bataev316ccf62019-01-29 18:51:58 +00005764 bool UseStrictCompare =
5765 RealVType->hasUnsignedIntegerRepresentation() &&
5766 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5767 return LIS.IsStrictCompare;
5768 });
5769 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5770 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005771 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005772 Expr *BoundUB = UB.get();
5773 if (UseStrictCompare) {
5774 BoundUB =
5775 SemaRef
5776 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5777 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5778 .get();
5779 BoundUB =
5780 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5781 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005782 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005783 (isOpenMPWorksharingDirective(DKind) ||
5784 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005785 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5786 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5787 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005788 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5789 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005790 ExprResult CombDistCond;
5791 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005792 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5793 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005794 }
5795
Carlo Bertolliffafe102017-04-20 00:39:39 +00005796 ExprResult CombCond;
5797 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005798 Expr *BoundCombUB = CombUB.get();
5799 if (UseStrictCompare) {
5800 BoundCombUB =
5801 SemaRef
5802 .BuildBinOp(
5803 CurScope, CondLoc, BO_Add, BoundCombUB,
5804 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5805 .get();
5806 BoundCombUB =
5807 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5808 .get();
5809 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005810 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005811 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5812 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005813 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005814 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005815 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005816 ExprResult Inc =
5817 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5818 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5819 if (!Inc.isUsable())
5820 return 0;
5821 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005822 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005823 if (!Inc.isUsable())
5824 return 0;
5825
5826 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5827 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005828 // In combined construct, add combined version that use CombLB and CombUB
5829 // base variables for the update
5830 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005831 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5832 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005833 // LB + ST
5834 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5835 if (!NextLB.isUsable())
5836 return 0;
5837 // LB = LB + ST
5838 NextLB =
5839 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005840 NextLB =
5841 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005842 if (!NextLB.isUsable())
5843 return 0;
5844 // UB + ST
5845 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5846 if (!NextUB.isUsable())
5847 return 0;
5848 // UB = UB + ST
5849 NextUB =
5850 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005851 NextUB =
5852 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005853 if (!NextUB.isUsable())
5854 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005855 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5856 CombNextLB =
5857 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5858 if (!NextLB.isUsable())
5859 return 0;
5860 // LB = LB + ST
5861 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5862 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005863 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5864 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005865 if (!CombNextLB.isUsable())
5866 return 0;
5867 // UB + ST
5868 CombNextUB =
5869 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5870 if (!CombNextUB.isUsable())
5871 return 0;
5872 // UB = UB + ST
5873 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5874 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005875 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5876 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005877 if (!CombNextUB.isUsable())
5878 return 0;
5879 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005880 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005881
Carlo Bertolliffafe102017-04-20 00:39:39 +00005882 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005883 // directive with for as IV = IV + ST; ensure upper bound expression based
5884 // on PrevUB instead of NumIterations - used to implement 'for' when found
5885 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005886 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005887 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005888 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005889 DistCond = SemaRef.BuildBinOp(
5890 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005891 assert(DistCond.isUsable() && "distribute cond expr was not built");
5892
5893 DistInc =
5894 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5895 assert(DistInc.isUsable() && "distribute inc expr was not built");
5896 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5897 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005898 DistInc =
5899 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005900 assert(DistInc.isUsable() && "distribute inc expr was not built");
5901
5902 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5903 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005904 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005905 ExprResult IsUBGreater =
5906 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5907 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5908 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5909 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5910 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005911 PrevEUB =
5912 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005913
Alexey Bataev316ccf62019-01-29 18:51:58 +00005914 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5915 // parallel for is in combination with a distribute directive with
5916 // schedule(static, 1)
5917 Expr *BoundPrevUB = PrevUB.get();
5918 if (UseStrictCompare) {
5919 BoundPrevUB =
5920 SemaRef
5921 .BuildBinOp(
5922 CurScope, CondLoc, BO_Add, BoundPrevUB,
5923 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5924 .get();
5925 BoundPrevUB =
5926 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5927 .get();
5928 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005929 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005930 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5931 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005932 }
5933
Alexander Musmana5f070a2014-10-01 06:03:56 +00005934 // Build updates and final values of the loop counters.
5935 bool HasErrors = false;
5936 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005937 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005938 Built.Updates.resize(NestedLoopCount);
5939 Built.Finals.resize(NestedLoopCount);
5940 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005941 // We implement the following algorithm for obtaining the
5942 // original loop iteration variable values based on the
5943 // value of the collapsed loop iteration variable IV.
5944 //
5945 // Let n+1 be the number of collapsed loops in the nest.
5946 // Iteration variables (I0, I1, .... In)
5947 // Iteration counts (N0, N1, ... Nn)
5948 //
5949 // Acc = IV;
5950 //
5951 // To compute Ik for loop k, 0 <= k <= n, generate:
5952 // Prod = N(k+1) * N(k+2) * ... * Nn;
5953 // Ik = Acc / Prod;
5954 // Acc -= Ik * Prod;
5955 //
5956 ExprResult Acc = IV;
5957 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005958 LoopIterationSpace &IS = IterSpaces[Cnt];
5959 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005960 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005961
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005962 // Compute prod
5963 ExprResult Prod =
5964 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5965 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5966 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5967 IterSpaces[K].NumIterations);
5968
5969 // Iter = Acc / Prod
5970 // If there is at least one more inner loop to avoid
5971 // multiplication by 1.
5972 if (Cnt + 1 < NestedLoopCount)
5973 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5974 Acc.get(), Prod.get());
5975 else
5976 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005977 if (!Iter.isUsable()) {
5978 HasErrors = true;
5979 break;
5980 }
5981
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005982 // Update Acc:
5983 // Acc -= Iter * Prod
5984 // Check if there is at least one more inner loop to avoid
5985 // multiplication by 1.
5986 if (Cnt + 1 < NestedLoopCount)
5987 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5988 Iter.get(), Prod.get());
5989 else
5990 Prod = Iter;
5991 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5992 Acc.get(), Prod.get());
5993
Alexey Bataev39f915b82015-05-08 10:41:21 +00005994 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005995 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005996 DeclRefExpr *CounterVar = buildDeclRefExpr(
5997 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5998 /*RefersToCapture=*/true);
5999 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006000 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006001 if (!Init.isUsable()) {
6002 HasErrors = true;
6003 break;
6004 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006005 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006006 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6007 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006008 if (!Update.isUsable()) {
6009 HasErrors = true;
6010 break;
6011 }
6012
6013 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006014 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00006015 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006016 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006017 if (!Final.isUsable()) {
6018 HasErrors = true;
6019 break;
6020 }
6021
Alexander Musmana5f070a2014-10-01 06:03:56 +00006022 if (!Update.isUsable() || !Final.isUsable()) {
6023 HasErrors = true;
6024 break;
6025 }
6026 // Save results
6027 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006028 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006029 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006030 Built.Updates[Cnt] = Update.get();
6031 Built.Finals[Cnt] = Final.get();
6032 }
6033 }
6034
6035 if (HasErrors)
6036 return 0;
6037
6038 // Save results
6039 Built.IterationVarRef = IV.get();
6040 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006041 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006042 Built.CalcLastIteration = SemaRef
6043 .ActOnFinishFullExpr(CalcLastIteration.get(),
6044 /*DiscardedValue*/ false)
6045 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006046 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006047 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006048 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006049 Built.Init = Init.get();
6050 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006051 Built.LB = LB.get();
6052 Built.UB = UB.get();
6053 Built.IL = IL.get();
6054 Built.ST = ST.get();
6055 Built.EUB = EUB.get();
6056 Built.NLB = NextLB.get();
6057 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006058 Built.PrevLB = PrevLB.get();
6059 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006060 Built.DistInc = DistInc.get();
6061 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006062 Built.DistCombinedFields.LB = CombLB.get();
6063 Built.DistCombinedFields.UB = CombUB.get();
6064 Built.DistCombinedFields.EUB = CombEUB.get();
6065 Built.DistCombinedFields.Init = CombInit.get();
6066 Built.DistCombinedFields.Cond = CombCond.get();
6067 Built.DistCombinedFields.NLB = CombNextLB.get();
6068 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006069 Built.DistCombinedFields.DistCond = CombDistCond.get();
6070 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006071
Alexey Bataevabfc0692014-06-25 06:52:00 +00006072 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006073}
6074
Alexey Bataev10e775f2015-07-30 11:36:16 +00006075static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006076 auto CollapseClauses =
6077 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6078 if (CollapseClauses.begin() != CollapseClauses.end())
6079 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006080 return nullptr;
6081}
6082
Alexey Bataev10e775f2015-07-30 11:36:16 +00006083static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006084 auto OrderedClauses =
6085 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6086 if (OrderedClauses.begin() != OrderedClauses.end())
6087 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006088 return nullptr;
6089}
6090
Kelvin Lic5609492016-07-15 04:39:07 +00006091static bool checkSimdlenSafelenSpecified(Sema &S,
6092 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006093 const OMPSafelenClause *Safelen = nullptr;
6094 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006095
Alexey Bataeve3727102018-04-18 15:57:46 +00006096 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006097 if (Clause->getClauseKind() == OMPC_safelen)
6098 Safelen = cast<OMPSafelenClause>(Clause);
6099 else if (Clause->getClauseKind() == OMPC_simdlen)
6100 Simdlen = cast<OMPSimdlenClause>(Clause);
6101 if (Safelen && Simdlen)
6102 break;
6103 }
6104
6105 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006106 const Expr *SimdlenLength = Simdlen->getSimdlen();
6107 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006108 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6109 SimdlenLength->isInstantiationDependent() ||
6110 SimdlenLength->containsUnexpandedParameterPack())
6111 return false;
6112 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6113 SafelenLength->isInstantiationDependent() ||
6114 SafelenLength->containsUnexpandedParameterPack())
6115 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006116 Expr::EvalResult SimdlenResult, SafelenResult;
6117 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6118 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6119 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6120 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006121 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6122 // If both simdlen and safelen clauses are specified, the value of the
6123 // simdlen parameter must be less than or equal to the value of the safelen
6124 // parameter.
6125 if (SimdlenRes > SafelenRes) {
6126 S.Diag(SimdlenLength->getExprLoc(),
6127 diag::err_omp_wrong_simdlen_safelen_values)
6128 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6129 return true;
6130 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006131 }
6132 return false;
6133}
6134
Alexey Bataeve3727102018-04-18 15:57:46 +00006135StmtResult
6136Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6137 SourceLocation StartLoc, SourceLocation EndLoc,
6138 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006139 if (!AStmt)
6140 return StmtError();
6141
6142 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006143 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006144 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6145 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006146 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006147 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6148 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006149 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006150 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006151
Alexander Musmana5f070a2014-10-01 06:03:56 +00006152 assert((CurContext->isDependentContext() || B.builtAll()) &&
6153 "omp simd loop exprs were not built");
6154
Alexander Musman3276a272015-03-21 10:12:56 +00006155 if (!CurContext->isDependentContext()) {
6156 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006157 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006158 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006159 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006160 B.NumIterations, *this, CurScope,
6161 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006162 return StmtError();
6163 }
6164 }
6165
Kelvin Lic5609492016-07-15 04:39:07 +00006166 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006167 return StmtError();
6168
Reid Kleckner87a31802018-03-12 21:43:02 +00006169 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006170 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6171 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006172}
6173
Alexey Bataeve3727102018-04-18 15:57:46 +00006174StmtResult
6175Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6176 SourceLocation StartLoc, SourceLocation EndLoc,
6177 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006178 if (!AStmt)
6179 return StmtError();
6180
6181 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006182 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006183 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6184 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006185 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006186 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6187 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006188 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006189 return StmtError();
6190
Alexander Musmana5f070a2014-10-01 06:03:56 +00006191 assert((CurContext->isDependentContext() || B.builtAll()) &&
6192 "omp for loop exprs were not built");
6193
Alexey Bataev54acd402015-08-04 11:18:19 +00006194 if (!CurContext->isDependentContext()) {
6195 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006196 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006197 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006198 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006199 B.NumIterations, *this, CurScope,
6200 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006201 return StmtError();
6202 }
6203 }
6204
Reid Kleckner87a31802018-03-12 21:43:02 +00006205 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006206 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006207 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006208}
6209
Alexander Musmanf82886e2014-09-18 05:12:34 +00006210StmtResult Sema::ActOnOpenMPForSimdDirective(
6211 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006212 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006213 if (!AStmt)
6214 return StmtError();
6215
6216 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006217 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006218 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6219 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006220 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006221 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006222 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6223 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006224 if (NestedLoopCount == 0)
6225 return StmtError();
6226
Alexander Musmanc6388682014-12-15 07:07:06 +00006227 assert((CurContext->isDependentContext() || B.builtAll()) &&
6228 "omp for simd loop exprs were not built");
6229
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006230 if (!CurContext->isDependentContext()) {
6231 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006232 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006233 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006234 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006235 B.NumIterations, *this, CurScope,
6236 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006237 return StmtError();
6238 }
6239 }
6240
Kelvin Lic5609492016-07-15 04:39:07 +00006241 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006242 return StmtError();
6243
Reid Kleckner87a31802018-03-12 21:43:02 +00006244 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006245 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6246 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006247}
6248
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006249StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6250 Stmt *AStmt,
6251 SourceLocation StartLoc,
6252 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006253 if (!AStmt)
6254 return StmtError();
6255
6256 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006257 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006258 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006259 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006260 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006261 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006262 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006263 return StmtError();
6264 // All associated statements must be '#pragma omp section' except for
6265 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006266 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006267 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6268 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006269 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006270 diag::err_omp_sections_substmt_not_section);
6271 return StmtError();
6272 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006273 cast<OMPSectionDirective>(SectionStmt)
6274 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006275 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006276 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006277 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006278 return StmtError();
6279 }
6280
Reid Kleckner87a31802018-03-12 21:43:02 +00006281 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006282
Alexey Bataev25e5b442015-09-15 12:52:43 +00006283 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6284 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006285}
6286
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006287StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6288 SourceLocation StartLoc,
6289 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006290 if (!AStmt)
6291 return StmtError();
6292
6293 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006294
Reid Kleckner87a31802018-03-12 21:43:02 +00006295 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006296 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006297
Alexey Bataev25e5b442015-09-15 12:52:43 +00006298 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6299 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006300}
6301
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006302StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6303 Stmt *AStmt,
6304 SourceLocation StartLoc,
6305 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006306 if (!AStmt)
6307 return StmtError();
6308
6309 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006310
Reid Kleckner87a31802018-03-12 21:43:02 +00006311 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006312
Alexey Bataev3255bf32015-01-19 05:20:46 +00006313 // OpenMP [2.7.3, single Construct, Restrictions]
6314 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006315 const OMPClause *Nowait = nullptr;
6316 const OMPClause *Copyprivate = nullptr;
6317 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006318 if (Clause->getClauseKind() == OMPC_nowait)
6319 Nowait = Clause;
6320 else if (Clause->getClauseKind() == OMPC_copyprivate)
6321 Copyprivate = Clause;
6322 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006323 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006324 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006325 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006326 return StmtError();
6327 }
6328 }
6329
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006330 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6331}
6332
Alexander Musman80c22892014-07-17 08:54:58 +00006333StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6334 SourceLocation StartLoc,
6335 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006336 if (!AStmt)
6337 return StmtError();
6338
6339 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006340
Reid Kleckner87a31802018-03-12 21:43:02 +00006341 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006342
6343 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6344}
6345
Alexey Bataev28c75412015-12-15 08:19:24 +00006346StmtResult Sema::ActOnOpenMPCriticalDirective(
6347 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6348 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006349 if (!AStmt)
6350 return StmtError();
6351
6352 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006353
Alexey Bataev28c75412015-12-15 08:19:24 +00006354 bool ErrorFound = false;
6355 llvm::APSInt Hint;
6356 SourceLocation HintLoc;
6357 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006358 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006359 if (C->getClauseKind() == OMPC_hint) {
6360 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006361 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006362 ErrorFound = true;
6363 }
6364 Expr *E = cast<OMPHintClause>(C)->getHint();
6365 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006366 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006367 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006368 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006369 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006370 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006371 }
6372 }
6373 }
6374 if (ErrorFound)
6375 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006376 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006377 if (Pair.first && DirName.getName() && !DependentHint) {
6378 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6379 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006380 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006381 Diag(HintLoc, diag::note_omp_critical_hint_here)
6382 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006383 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006384 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006385 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006386 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006387 << 1
6388 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6389 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006390 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006391 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006392 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006393 }
6394 }
6395
Reid Kleckner87a31802018-03-12 21:43:02 +00006396 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006397
Alexey Bataev28c75412015-12-15 08:19:24 +00006398 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6399 Clauses, AStmt);
6400 if (!Pair.first && DirName.getName() && !DependentHint)
6401 DSAStack->addCriticalWithHint(Dir, Hint);
6402 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006403}
6404
Alexey Bataev4acb8592014-07-07 13:01:15 +00006405StmtResult Sema::ActOnOpenMPParallelForDirective(
6406 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006407 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006408 if (!AStmt)
6409 return StmtError();
6410
Alexey Bataeve3727102018-04-18 15:57:46 +00006411 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006412 // 1.2.2 OpenMP Language Terminology
6413 // Structured block - An executable statement with a single entry at the
6414 // top and a single exit at the bottom.
6415 // The point of exit cannot be a branch out of the structured block.
6416 // longjmp() and throw() must not violate the entry/exit criteria.
6417 CS->getCapturedDecl()->setNothrow();
6418
Alexander Musmanc6388682014-12-15 07:07:06 +00006419 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006420 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6421 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006422 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006423 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006424 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6425 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006426 if (NestedLoopCount == 0)
6427 return StmtError();
6428
Alexander Musmana5f070a2014-10-01 06:03:56 +00006429 assert((CurContext->isDependentContext() || B.builtAll()) &&
6430 "omp parallel for loop exprs were not built");
6431
Alexey Bataev54acd402015-08-04 11:18:19 +00006432 if (!CurContext->isDependentContext()) {
6433 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006434 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006435 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006436 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006437 B.NumIterations, *this, CurScope,
6438 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006439 return StmtError();
6440 }
6441 }
6442
Reid Kleckner87a31802018-03-12 21:43:02 +00006443 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006444 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006445 NestedLoopCount, Clauses, AStmt, B,
6446 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006447}
6448
Alexander Musmane4e893b2014-09-23 09:33:00 +00006449StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6450 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006451 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006452 if (!AStmt)
6453 return StmtError();
6454
Alexey Bataeve3727102018-04-18 15:57:46 +00006455 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006456 // 1.2.2 OpenMP Language Terminology
6457 // Structured block - An executable statement with a single entry at the
6458 // top and a single exit at the bottom.
6459 // The point of exit cannot be a branch out of the structured block.
6460 // longjmp() and throw() must not violate the entry/exit criteria.
6461 CS->getCapturedDecl()->setNothrow();
6462
Alexander Musmanc6388682014-12-15 07:07:06 +00006463 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006464 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6465 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006466 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006467 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006468 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6469 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006470 if (NestedLoopCount == 0)
6471 return StmtError();
6472
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006473 if (!CurContext->isDependentContext()) {
6474 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006475 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006476 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006477 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006478 B.NumIterations, *this, CurScope,
6479 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006480 return StmtError();
6481 }
6482 }
6483
Kelvin Lic5609492016-07-15 04:39:07 +00006484 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006485 return StmtError();
6486
Reid Kleckner87a31802018-03-12 21:43:02 +00006487 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006488 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006489 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006490}
6491
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006492StmtResult
6493Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6494 Stmt *AStmt, SourceLocation StartLoc,
6495 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006496 if (!AStmt)
6497 return StmtError();
6498
6499 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006500 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006501 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006502 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006503 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006504 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006505 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006506 return StmtError();
6507 // All associated statements must be '#pragma omp section' except for
6508 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006509 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006510 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6511 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006512 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006513 diag::err_omp_parallel_sections_substmt_not_section);
6514 return StmtError();
6515 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006516 cast<OMPSectionDirective>(SectionStmt)
6517 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006518 }
6519 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006520 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006521 diag::err_omp_parallel_sections_not_compound_stmt);
6522 return StmtError();
6523 }
6524
Reid Kleckner87a31802018-03-12 21:43:02 +00006525 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006526
Alexey Bataev25e5b442015-09-15 12:52:43 +00006527 return OMPParallelSectionsDirective::Create(
6528 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006529}
6530
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006531StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6532 Stmt *AStmt, SourceLocation StartLoc,
6533 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006534 if (!AStmt)
6535 return StmtError();
6536
David Majnemer9d168222016-08-05 17:44:54 +00006537 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006538 // 1.2.2 OpenMP Language Terminology
6539 // Structured block - An executable statement with a single entry at the
6540 // top and a single exit at the bottom.
6541 // The point of exit cannot be a branch out of the structured block.
6542 // longjmp() and throw() must not violate the entry/exit criteria.
6543 CS->getCapturedDecl()->setNothrow();
6544
Reid Kleckner87a31802018-03-12 21:43:02 +00006545 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006546
Alexey Bataev25e5b442015-09-15 12:52:43 +00006547 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6548 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006549}
6550
Alexey Bataev68446b72014-07-18 07:47:19 +00006551StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6552 SourceLocation EndLoc) {
6553 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6554}
6555
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006556StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6557 SourceLocation EndLoc) {
6558 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6559}
6560
Alexey Bataev2df347a2014-07-18 10:17:07 +00006561StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6562 SourceLocation EndLoc) {
6563 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6564}
6565
Alexey Bataev169d96a2017-07-18 20:17:46 +00006566StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6567 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006568 SourceLocation StartLoc,
6569 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006570 if (!AStmt)
6571 return StmtError();
6572
6573 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006574
Reid Kleckner87a31802018-03-12 21:43:02 +00006575 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006576
Alexey Bataev169d96a2017-07-18 20:17:46 +00006577 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006578 AStmt,
6579 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006580}
6581
Alexey Bataev6125da92014-07-21 11:26:11 +00006582StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6583 SourceLocation StartLoc,
6584 SourceLocation EndLoc) {
6585 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6586 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6587}
6588
Alexey Bataev346265e2015-09-25 10:37:12 +00006589StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6590 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006591 SourceLocation StartLoc,
6592 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006593 const OMPClause *DependFound = nullptr;
6594 const OMPClause *DependSourceClause = nullptr;
6595 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006596 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006597 const OMPThreadsClause *TC = nullptr;
6598 const OMPSIMDClause *SC = nullptr;
6599 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006600 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6601 DependFound = C;
6602 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6603 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006604 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006605 << getOpenMPDirectiveName(OMPD_ordered)
6606 << getOpenMPClauseName(OMPC_depend) << 2;
6607 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006608 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006609 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006610 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006611 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006612 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006613 << 0;
6614 ErrorFound = true;
6615 }
6616 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6617 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006618 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006619 << 1;
6620 ErrorFound = true;
6621 }
6622 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006623 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006624 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006625 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006626 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006627 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006628 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006629 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006630 if (!ErrorFound && !SC &&
6631 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006632 // OpenMP [2.8.1,simd Construct, Restrictions]
6633 // An ordered construct with the simd clause is the only OpenMP construct
6634 // that can appear in the simd region.
6635 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006636 ErrorFound = true;
6637 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006638 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006639 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6640 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006641 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006642 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006643 diag::err_omp_ordered_directive_without_param);
6644 ErrorFound = true;
6645 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006646 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006647 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006648 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6649 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006650 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006651 ErrorFound = true;
6652 }
6653 }
6654 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006655 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006656
6657 if (AStmt) {
6658 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6659
Reid Kleckner87a31802018-03-12 21:43:02 +00006660 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006661 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006662
6663 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006664}
6665
Alexey Bataev1d160b12015-03-13 12:27:31 +00006666namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006667/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006668/// construct.
6669class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006670 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006671 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006672 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006673 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006674 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006675 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006676 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006677 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006678 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006679 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006680 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006681 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006682 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006683 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006684 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006685 /// expression.
6686 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006687 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006688 /// part.
6689 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006690 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006691 NoError
6692 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006693 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006694 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006695 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006696 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006697 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006698 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006699 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006700 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006701 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006702 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6703 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6704 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006705 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006706 /// important for non-associative operations.
6707 bool IsXLHSInRHSPart;
6708 BinaryOperatorKind Op;
6709 SourceLocation OpLoc;
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;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006713
6714public:
6715 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006716 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006717 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006719 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006720 /// expression. If DiagId and NoteId == 0, then only check is performed
6721 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006722 /// \param DiagId Diagnostic which should be emitted if error is found.
6723 /// \param NoteId Diagnostic note for the main error message.
6724 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006725 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006726 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006727 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006728 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006729 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006730 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006731 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6732 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6733 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006734 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006735 /// false otherwise.
6736 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6737
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006738 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006739 /// if it is a prefix unary operation.
6740 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6741
Alexey Bataev1d160b12015-03-13 12:27:31 +00006742private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006743 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6744 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006745};
6746} // namespace
6747
6748bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6749 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6750 ExprAnalysisErrorCode ErrorFound = NoError;
6751 SourceLocation ErrorLoc, NoteLoc;
6752 SourceRange ErrorRange, NoteRange;
6753 // Allowed constructs are:
6754 // x = x binop expr;
6755 // x = expr binop x;
6756 if (AtomicBinOp->getOpcode() == BO_Assign) {
6757 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006758 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006759 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6760 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6761 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6762 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006763 Op = AtomicInnerBinOp->getOpcode();
6764 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006765 Expr *LHS = AtomicInnerBinOp->getLHS();
6766 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006767 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6768 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6769 /*Canonical=*/true);
6770 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6771 /*Canonical=*/true);
6772 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6773 /*Canonical=*/true);
6774 if (XId == LHSId) {
6775 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006776 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006777 } else if (XId == RHSId) {
6778 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006779 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006780 } else {
6781 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6782 ErrorRange = AtomicInnerBinOp->getSourceRange();
6783 NoteLoc = X->getExprLoc();
6784 NoteRange = X->getSourceRange();
6785 ErrorFound = NotAnUpdateExpression;
6786 }
6787 } else {
6788 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6789 ErrorRange = AtomicInnerBinOp->getSourceRange();
6790 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6791 NoteRange = SourceRange(NoteLoc, NoteLoc);
6792 ErrorFound = NotABinaryOperator;
6793 }
6794 } else {
6795 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6796 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6797 ErrorFound = NotABinaryExpression;
6798 }
6799 } else {
6800 ErrorLoc = AtomicBinOp->getExprLoc();
6801 ErrorRange = AtomicBinOp->getSourceRange();
6802 NoteLoc = AtomicBinOp->getOperatorLoc();
6803 NoteRange = SourceRange(NoteLoc, NoteLoc);
6804 ErrorFound = NotAnAssignmentOp;
6805 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006806 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006807 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6808 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6809 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006810 }
6811 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006812 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006813 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006814}
6815
6816bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6817 unsigned NoteId) {
6818 ExprAnalysisErrorCode ErrorFound = NoError;
6819 SourceLocation ErrorLoc, NoteLoc;
6820 SourceRange ErrorRange, NoteRange;
6821 // Allowed constructs are:
6822 // x++;
6823 // x--;
6824 // ++x;
6825 // --x;
6826 // x binop= expr;
6827 // x = x binop expr;
6828 // x = expr binop x;
6829 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6830 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6831 if (AtomicBody->getType()->isScalarType() ||
6832 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006833 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006834 AtomicBody->IgnoreParenImpCasts())) {
6835 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006836 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006837 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006838 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006839 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006840 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006841 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006842 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6843 AtomicBody->IgnoreParenImpCasts())) {
6844 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006845 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006846 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006847 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006848 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006849 // Check for Unary Operation
6850 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006851 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006852 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6853 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006854 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006855 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6856 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006857 } else {
6858 ErrorFound = NotAnUnaryIncDecExpression;
6859 ErrorLoc = AtomicUnaryOp->getExprLoc();
6860 ErrorRange = AtomicUnaryOp->getSourceRange();
6861 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6862 NoteRange = SourceRange(NoteLoc, NoteLoc);
6863 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006864 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006865 ErrorFound = NotABinaryOrUnaryExpression;
6866 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6867 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6868 }
6869 } else {
6870 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006871 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006872 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6873 }
6874 } else {
6875 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006876 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006877 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6878 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006879 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006880 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6881 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6882 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006883 }
6884 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006885 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006886 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006887 // Build an update expression of form 'OpaqueValueExpr(x) binop
6888 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6889 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6890 auto *OVEX = new (SemaRef.getASTContext())
6891 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6892 auto *OVEExpr = new (SemaRef.getASTContext())
6893 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006894 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006895 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6896 IsXLHSInRHSPart ? OVEExpr : OVEX);
6897 if (Update.isInvalid())
6898 return true;
6899 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6900 Sema::AA_Casting);
6901 if (Update.isInvalid())
6902 return true;
6903 UpdateExpr = Update.get();
6904 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006905 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006906}
6907
Alexey Bataev0162e452014-07-22 10:10:35 +00006908StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6909 Stmt *AStmt,
6910 SourceLocation StartLoc,
6911 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006912 if (!AStmt)
6913 return StmtError();
6914
David Majnemer9d168222016-08-05 17:44:54 +00006915 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006916 // 1.2.2 OpenMP Language Terminology
6917 // Structured block - An executable statement with a single entry at the
6918 // top and a single exit at the bottom.
6919 // The point of exit cannot be a branch out of the structured block.
6920 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006921 OpenMPClauseKind AtomicKind = OMPC_unknown;
6922 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006923 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006924 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006925 C->getClauseKind() == OMPC_update ||
6926 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006927 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006928 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006929 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006930 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6931 << getOpenMPClauseName(AtomicKind);
6932 } else {
6933 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006934 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006935 }
6936 }
6937 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006938
Alexey Bataeve3727102018-04-18 15:57:46 +00006939 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006940 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6941 Body = EWC->getSubExpr();
6942
Alexey Bataev62cec442014-11-18 10:14:22 +00006943 Expr *X = nullptr;
6944 Expr *V = nullptr;
6945 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006946 Expr *UE = nullptr;
6947 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006948 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006949 // OpenMP [2.12.6, atomic Construct]
6950 // In the next expressions:
6951 // * x and v (as applicable) are both l-value expressions with scalar type.
6952 // * During the execution of an atomic region, multiple syntactic
6953 // occurrences of x must designate the same storage location.
6954 // * Neither of v and expr (as applicable) may access the storage location
6955 // designated by x.
6956 // * Neither of x and expr (as applicable) may access the storage location
6957 // designated by v.
6958 // * expr is an expression with scalar type.
6959 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6960 // * binop, binop=, ++, and -- are not overloaded operators.
6961 // * The expression x binop expr must be numerically equivalent to x binop
6962 // (expr). This requirement is satisfied if the operators in expr have
6963 // precedence greater than binop, or by using parentheses around expr or
6964 // subexpressions of expr.
6965 // * The expression expr binop x must be numerically equivalent to (expr)
6966 // binop x. This requirement is satisfied if the operators in expr have
6967 // precedence equal to or greater than binop, or by using parentheses around
6968 // expr or subexpressions of expr.
6969 // * For forms that allow multiple occurrences of x, the number of times
6970 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006971 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006972 enum {
6973 NotAnExpression,
6974 NotAnAssignmentOp,
6975 NotAScalarType,
6976 NotAnLValue,
6977 NoError
6978 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006979 SourceLocation ErrorLoc, NoteLoc;
6980 SourceRange ErrorRange, NoteRange;
6981 // If clause is read:
6982 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006983 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6984 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006985 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6986 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6987 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6988 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6989 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6990 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6991 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006992 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006993 ErrorFound = NotAnLValue;
6994 ErrorLoc = AtomicBinOp->getExprLoc();
6995 ErrorRange = AtomicBinOp->getSourceRange();
6996 NoteLoc = NotLValueExpr->getExprLoc();
6997 NoteRange = NotLValueExpr->getSourceRange();
6998 }
6999 } else if (!X->isInstantiationDependent() ||
7000 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007001 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00007002 (X->isInstantiationDependent() || X->getType()->isScalarType())
7003 ? V
7004 : X;
7005 ErrorFound = NotAScalarType;
7006 ErrorLoc = AtomicBinOp->getExprLoc();
7007 ErrorRange = AtomicBinOp->getSourceRange();
7008 NoteLoc = NotScalarExpr->getExprLoc();
7009 NoteRange = NotScalarExpr->getSourceRange();
7010 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007011 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00007012 ErrorFound = NotAnAssignmentOp;
7013 ErrorLoc = AtomicBody->getExprLoc();
7014 ErrorRange = AtomicBody->getSourceRange();
7015 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7016 : AtomicBody->getExprLoc();
7017 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7018 : AtomicBody->getSourceRange();
7019 }
7020 } else {
7021 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007022 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007023 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007024 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007025 if (ErrorFound != NoError) {
7026 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7027 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007028 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7029 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007030 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007031 }
7032 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007033 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007034 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007035 enum {
7036 NotAnExpression,
7037 NotAnAssignmentOp,
7038 NotAScalarType,
7039 NotAnLValue,
7040 NoError
7041 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007042 SourceLocation ErrorLoc, NoteLoc;
7043 SourceRange ErrorRange, NoteRange;
7044 // If clause is write:
7045 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007046 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7047 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007048 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7049 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007050 X = AtomicBinOp->getLHS();
7051 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007052 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7053 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7054 if (!X->isLValue()) {
7055 ErrorFound = NotAnLValue;
7056 ErrorLoc = AtomicBinOp->getExprLoc();
7057 ErrorRange = AtomicBinOp->getSourceRange();
7058 NoteLoc = X->getExprLoc();
7059 NoteRange = X->getSourceRange();
7060 }
7061 } else if (!X->isInstantiationDependent() ||
7062 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007063 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007064 (X->isInstantiationDependent() || X->getType()->isScalarType())
7065 ? E
7066 : X;
7067 ErrorFound = NotAScalarType;
7068 ErrorLoc = AtomicBinOp->getExprLoc();
7069 ErrorRange = AtomicBinOp->getSourceRange();
7070 NoteLoc = NotScalarExpr->getExprLoc();
7071 NoteRange = NotScalarExpr->getSourceRange();
7072 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007073 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007074 ErrorFound = NotAnAssignmentOp;
7075 ErrorLoc = AtomicBody->getExprLoc();
7076 ErrorRange = AtomicBody->getSourceRange();
7077 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7078 : AtomicBody->getExprLoc();
7079 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7080 : AtomicBody->getSourceRange();
7081 }
7082 } else {
7083 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007084 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007085 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007086 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007087 if (ErrorFound != NoError) {
7088 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7089 << ErrorRange;
7090 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7091 << NoteRange;
7092 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007093 }
7094 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007095 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007096 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007097 // If clause is update:
7098 // x++;
7099 // x--;
7100 // ++x;
7101 // --x;
7102 // x binop= expr;
7103 // x = x binop expr;
7104 // x = expr binop x;
7105 OpenMPAtomicUpdateChecker Checker(*this);
7106 if (Checker.checkStatement(
7107 Body, (AtomicKind == OMPC_update)
7108 ? diag::err_omp_atomic_update_not_expression_statement
7109 : diag::err_omp_atomic_not_expression_statement,
7110 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007111 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007112 if (!CurContext->isDependentContext()) {
7113 E = Checker.getExpr();
7114 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007115 UE = Checker.getUpdateExpr();
7116 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007117 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007118 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007119 enum {
7120 NotAnAssignmentOp,
7121 NotACompoundStatement,
7122 NotTwoSubstatements,
7123 NotASpecificExpression,
7124 NoError
7125 } ErrorFound = NoError;
7126 SourceLocation ErrorLoc, NoteLoc;
7127 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007128 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007129 // If clause is a capture:
7130 // v = x++;
7131 // v = x--;
7132 // v = ++x;
7133 // v = --x;
7134 // v = x binop= expr;
7135 // v = x = x binop expr;
7136 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007137 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007138 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7139 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7140 V = AtomicBinOp->getLHS();
7141 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7142 OpenMPAtomicUpdateChecker Checker(*this);
7143 if (Checker.checkStatement(
7144 Body, diag::err_omp_atomic_capture_not_expression_statement,
7145 diag::note_omp_atomic_update))
7146 return StmtError();
7147 E = Checker.getExpr();
7148 X = Checker.getX();
7149 UE = Checker.getUpdateExpr();
7150 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7151 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007152 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007153 ErrorLoc = AtomicBody->getExprLoc();
7154 ErrorRange = AtomicBody->getSourceRange();
7155 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7156 : AtomicBody->getExprLoc();
7157 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7158 : AtomicBody->getSourceRange();
7159 ErrorFound = NotAnAssignmentOp;
7160 }
7161 if (ErrorFound != NoError) {
7162 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7163 << ErrorRange;
7164 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7165 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007166 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007167 if (CurContext->isDependentContext())
7168 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007169 } else {
7170 // If clause is a capture:
7171 // { v = x; x = expr; }
7172 // { v = x; x++; }
7173 // { v = x; x--; }
7174 // { v = x; ++x; }
7175 // { v = x; --x; }
7176 // { v = x; x binop= expr; }
7177 // { v = x; x = x binop expr; }
7178 // { v = x; x = expr binop x; }
7179 // { x++; v = x; }
7180 // { x--; v = x; }
7181 // { ++x; v = x; }
7182 // { --x; v = x; }
7183 // { x binop= expr; v = x; }
7184 // { x = x binop expr; v = x; }
7185 // { x = expr binop x; v = x; }
7186 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7187 // Check that this is { expr1; expr2; }
7188 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007189 Stmt *First = CS->body_front();
7190 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007191 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7192 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7193 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7194 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7195 // Need to find what subexpression is 'v' and what is 'x'.
7196 OpenMPAtomicUpdateChecker Checker(*this);
7197 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7198 BinaryOperator *BinOp = nullptr;
7199 if (IsUpdateExprFound) {
7200 BinOp = dyn_cast<BinaryOperator>(First);
7201 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7202 }
7203 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7204 // { v = x; x++; }
7205 // { v = x; x--; }
7206 // { v = x; ++x; }
7207 // { v = x; --x; }
7208 // { v = x; x binop= expr; }
7209 // { v = x; x = x binop expr; }
7210 // { v = x; x = expr binop x; }
7211 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007212 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007213 llvm::FoldingSetNodeID XId, PossibleXId;
7214 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7215 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7216 IsUpdateExprFound = XId == PossibleXId;
7217 if (IsUpdateExprFound) {
7218 V = BinOp->getLHS();
7219 X = Checker.getX();
7220 E = Checker.getExpr();
7221 UE = Checker.getUpdateExpr();
7222 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007223 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007224 }
7225 }
7226 if (!IsUpdateExprFound) {
7227 IsUpdateExprFound = !Checker.checkStatement(First);
7228 BinOp = nullptr;
7229 if (IsUpdateExprFound) {
7230 BinOp = dyn_cast<BinaryOperator>(Second);
7231 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7232 }
7233 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7234 // { x++; v = x; }
7235 // { x--; v = x; }
7236 // { ++x; v = x; }
7237 // { --x; v = x; }
7238 // { x binop= expr; v = x; }
7239 // { x = x binop expr; v = x; }
7240 // { x = expr binop x; v = x; }
7241 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007242 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007243 llvm::FoldingSetNodeID XId, PossibleXId;
7244 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7245 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7246 IsUpdateExprFound = XId == PossibleXId;
7247 if (IsUpdateExprFound) {
7248 V = BinOp->getLHS();
7249 X = Checker.getX();
7250 E = Checker.getExpr();
7251 UE = Checker.getUpdateExpr();
7252 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007253 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007254 }
7255 }
7256 }
7257 if (!IsUpdateExprFound) {
7258 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007259 auto *FirstExpr = dyn_cast<Expr>(First);
7260 auto *SecondExpr = dyn_cast<Expr>(Second);
7261 if (!FirstExpr || !SecondExpr ||
7262 !(FirstExpr->isInstantiationDependent() ||
7263 SecondExpr->isInstantiationDependent())) {
7264 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7265 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007266 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007267 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007268 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007269 NoteRange = ErrorRange = FirstBinOp
7270 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007271 : SourceRange(ErrorLoc, ErrorLoc);
7272 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007273 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7274 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7275 ErrorFound = NotAnAssignmentOp;
7276 NoteLoc = ErrorLoc = SecondBinOp
7277 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007278 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007279 NoteRange = ErrorRange =
7280 SecondBinOp ? SecondBinOp->getSourceRange()
7281 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007282 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007283 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007284 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007285 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007286 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7287 llvm::FoldingSetNodeID X1Id, X2Id;
7288 PossibleXRHSInFirst->Profile(X1Id, Context,
7289 /*Canonical=*/true);
7290 PossibleXLHSInSecond->Profile(X2Id, Context,
7291 /*Canonical=*/true);
7292 IsUpdateExprFound = X1Id == X2Id;
7293 if (IsUpdateExprFound) {
7294 V = FirstBinOp->getLHS();
7295 X = SecondBinOp->getLHS();
7296 E = SecondBinOp->getRHS();
7297 UE = nullptr;
7298 IsXLHSInRHSPart = false;
7299 IsPostfixUpdate = true;
7300 } else {
7301 ErrorFound = NotASpecificExpression;
7302 ErrorLoc = FirstBinOp->getExprLoc();
7303 ErrorRange = FirstBinOp->getSourceRange();
7304 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7305 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7306 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007307 }
7308 }
7309 }
7310 }
7311 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007312 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007313 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007314 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007315 ErrorFound = NotTwoSubstatements;
7316 }
7317 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007318 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007319 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007320 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007321 ErrorFound = NotACompoundStatement;
7322 }
7323 if (ErrorFound != NoError) {
7324 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7325 << ErrorRange;
7326 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7327 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007328 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007329 if (CurContext->isDependentContext())
7330 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007331 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007332 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007333
Reid Kleckner87a31802018-03-12 21:43:02 +00007334 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007335
Alexey Bataev62cec442014-11-18 10:14:22 +00007336 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007337 X, V, E, UE, IsXLHSInRHSPart,
7338 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007339}
7340
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007341StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7342 Stmt *AStmt,
7343 SourceLocation StartLoc,
7344 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007345 if (!AStmt)
7346 return StmtError();
7347
Alexey Bataeve3727102018-04-18 15:57:46 +00007348 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007349 // 1.2.2 OpenMP Language Terminology
7350 // Structured block - An executable statement with a single entry at the
7351 // top and a single exit at the bottom.
7352 // The point of exit cannot be a branch out of the structured block.
7353 // longjmp() and throw() must not violate the entry/exit criteria.
7354 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007355 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7356 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7357 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7358 // 1.2.2 OpenMP Language Terminology
7359 // Structured block - An executable statement with a single entry at the
7360 // top and a single exit at the bottom.
7361 // The point of exit cannot be a branch out of the structured block.
7362 // longjmp() and throw() must not violate the entry/exit criteria.
7363 CS->getCapturedDecl()->setNothrow();
7364 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007365
Alexey Bataev13314bf2014-10-09 04:18:56 +00007366 // OpenMP [2.16, Nesting of Regions]
7367 // If specified, a teams construct must be contained within a target
7368 // construct. That target construct must contain no statements or directives
7369 // outside of the teams construct.
7370 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007371 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007372 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007373 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007374 auto I = CS->body_begin();
7375 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007376 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007377 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7378 OMPTeamsFound) {
7379
Alexey Bataev13314bf2014-10-09 04:18:56 +00007380 OMPTeamsFound = false;
7381 break;
7382 }
7383 ++I;
7384 }
7385 assert(I != CS->body_end() && "Not found statement");
7386 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007387 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007388 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007389 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007390 }
7391 if (!OMPTeamsFound) {
7392 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7393 Diag(DSAStack->getInnerTeamsRegionLoc(),
7394 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007395 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007396 << isa<OMPExecutableDirective>(S);
7397 return StmtError();
7398 }
7399 }
7400
Reid Kleckner87a31802018-03-12 21:43:02 +00007401 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007402
7403 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7404}
7405
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007406StmtResult
7407Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7408 Stmt *AStmt, SourceLocation StartLoc,
7409 SourceLocation EndLoc) {
7410 if (!AStmt)
7411 return StmtError();
7412
Alexey Bataeve3727102018-04-18 15:57:46 +00007413 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007414 // 1.2.2 OpenMP Language Terminology
7415 // Structured block - An executable statement with a single entry at the
7416 // top and a single exit at the bottom.
7417 // The point of exit cannot be a branch out of the structured block.
7418 // longjmp() and throw() must not violate the entry/exit criteria.
7419 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007420 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7421 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7422 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7423 // 1.2.2 OpenMP Language Terminology
7424 // Structured block - An executable statement with a single entry at the
7425 // top and a single exit at the bottom.
7426 // The point of exit cannot be a branch out of the structured block.
7427 // longjmp() and throw() must not violate the entry/exit criteria.
7428 CS->getCapturedDecl()->setNothrow();
7429 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007430
Reid Kleckner87a31802018-03-12 21:43:02 +00007431 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007432
7433 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7434 AStmt);
7435}
7436
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007437StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007439 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007440 if (!AStmt)
7441 return StmtError();
7442
Alexey Bataeve3727102018-04-18 15:57:46 +00007443 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007444 // 1.2.2 OpenMP Language Terminology
7445 // Structured block - An executable statement with a single entry at the
7446 // top and a single exit at the bottom.
7447 // The point of exit cannot be a branch out of the structured block.
7448 // longjmp() and throw() must not violate the entry/exit criteria.
7449 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007450 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7451 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7452 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7453 // 1.2.2 OpenMP Language Terminology
7454 // Structured block - An executable statement with a single entry at the
7455 // top and a single exit at the bottom.
7456 // The point of exit cannot be a branch out of the structured block.
7457 // longjmp() and throw() must not violate the entry/exit criteria.
7458 CS->getCapturedDecl()->setNothrow();
7459 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007460
7461 OMPLoopDirective::HelperExprs B;
7462 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7463 // define the nested loops number.
7464 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007465 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007466 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007467 VarsWithImplicitDSA, B);
7468 if (NestedLoopCount == 0)
7469 return StmtError();
7470
7471 assert((CurContext->isDependentContext() || B.builtAll()) &&
7472 "omp target parallel for loop exprs were not built");
7473
7474 if (!CurContext->isDependentContext()) {
7475 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007476 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007477 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007478 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007479 B.NumIterations, *this, CurScope,
7480 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007481 return StmtError();
7482 }
7483 }
7484
Reid Kleckner87a31802018-03-12 21:43:02 +00007485 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007486 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7487 NestedLoopCount, Clauses, AStmt,
7488 B, DSAStack->isCancelRegion());
7489}
7490
Alexey Bataev95b64a92017-05-30 16:00:04 +00007491/// Check for existence of a map clause in the list of clauses.
7492static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7493 const OpenMPClauseKind K) {
7494 return llvm::any_of(
7495 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7496}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007497
Alexey Bataev95b64a92017-05-30 16:00:04 +00007498template <typename... Params>
7499static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7500 const Params... ClauseTypes) {
7501 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007502}
7503
Michael Wong65f367f2015-07-21 13:44:28 +00007504StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7505 Stmt *AStmt,
7506 SourceLocation StartLoc,
7507 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007508 if (!AStmt)
7509 return StmtError();
7510
7511 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7512
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007513 // OpenMP [2.10.1, Restrictions, p. 97]
7514 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007515 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7516 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7517 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007518 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007519 return StmtError();
7520 }
7521
Reid Kleckner87a31802018-03-12 21:43:02 +00007522 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007523
7524 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7525 AStmt);
7526}
7527
Samuel Antaodf67fc42016-01-19 19:15:56 +00007528StmtResult
7529Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7530 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007531 SourceLocation EndLoc, Stmt *AStmt) {
7532 if (!AStmt)
7533 return StmtError();
7534
Alexey Bataeve3727102018-04-18 15:57:46 +00007535 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007536 // 1.2.2 OpenMP Language Terminology
7537 // Structured block - An executable statement with a single entry at the
7538 // top and a single exit at the bottom.
7539 // The point of exit cannot be a branch out of the structured block.
7540 // longjmp() and throw() must not violate the entry/exit criteria.
7541 CS->getCapturedDecl()->setNothrow();
7542 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7543 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7544 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7545 // 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 }
7552
Samuel Antaodf67fc42016-01-19 19:15:56 +00007553 // OpenMP [2.10.2, Restrictions, p. 99]
7554 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007555 if (!hasClauses(Clauses, OMPC_map)) {
7556 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7557 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007558 return StmtError();
7559 }
7560
Alexey Bataev7828b252017-11-21 17:08:48 +00007561 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7562 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007563}
7564
Samuel Antao72590762016-01-19 20:04:50 +00007565StmtResult
7566Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7567 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007568 SourceLocation EndLoc, Stmt *AStmt) {
7569 if (!AStmt)
7570 return StmtError();
7571
Alexey Bataeve3727102018-04-18 15:57:46 +00007572 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007573 // 1.2.2 OpenMP Language Terminology
7574 // Structured block - An executable statement with a single entry at the
7575 // top and a single exit at the bottom.
7576 // The point of exit cannot be a branch out of the structured block.
7577 // longjmp() and throw() must not violate the entry/exit criteria.
7578 CS->getCapturedDecl()->setNothrow();
7579 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7580 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7581 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7582 // 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 }
7589
Samuel Antao72590762016-01-19 20:04:50 +00007590 // OpenMP [2.10.3, Restrictions, p. 102]
7591 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007592 if (!hasClauses(Clauses, OMPC_map)) {
7593 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7594 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007595 return StmtError();
7596 }
7597
Alexey Bataev7828b252017-11-21 17:08:48 +00007598 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7599 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007600}
7601
Samuel Antao686c70c2016-05-26 17:30:50 +00007602StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7603 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007604 SourceLocation EndLoc,
7605 Stmt *AStmt) {
7606 if (!AStmt)
7607 return StmtError();
7608
Alexey Bataeve3727102018-04-18 15:57:46 +00007609 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007610 // 1.2.2 OpenMP Language Terminology
7611 // Structured block - An executable statement with a single entry at the
7612 // top and a single exit at the bottom.
7613 // The point of exit cannot be a branch out of the structured block.
7614 // longjmp() and throw() must not violate the entry/exit criteria.
7615 CS->getCapturedDecl()->setNothrow();
7616 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7617 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7618 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7619 // 1.2.2 OpenMP Language Terminology
7620 // Structured block - An executable statement with a single entry at the
7621 // top and a single exit at the bottom.
7622 // The point of exit cannot be a branch out of the structured block.
7623 // longjmp() and throw() must not violate the entry/exit criteria.
7624 CS->getCapturedDecl()->setNothrow();
7625 }
7626
Alexey Bataev95b64a92017-05-30 16:00:04 +00007627 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007628 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7629 return StmtError();
7630 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007631 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7632 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007633}
7634
Alexey Bataev13314bf2014-10-09 04:18:56 +00007635StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7636 Stmt *AStmt, SourceLocation StartLoc,
7637 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007638 if (!AStmt)
7639 return StmtError();
7640
Alexey Bataeve3727102018-04-18 15:57:46 +00007641 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007642 // 1.2.2 OpenMP Language Terminology
7643 // Structured block - An executable statement with a single entry at the
7644 // top and a single exit at the bottom.
7645 // The point of exit cannot be a branch out of the structured block.
7646 // longjmp() and throw() must not violate the entry/exit criteria.
7647 CS->getCapturedDecl()->setNothrow();
7648
Reid Kleckner87a31802018-03-12 21:43:02 +00007649 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007650
Alexey Bataevceabd412017-11-30 18:01:54 +00007651 DSAStack->setParentTeamsRegionLoc(StartLoc);
7652
Alexey Bataev13314bf2014-10-09 04:18:56 +00007653 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7654}
7655
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007656StmtResult
7657Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7658 SourceLocation EndLoc,
7659 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007660 if (DSAStack->isParentNowaitRegion()) {
7661 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7662 return StmtError();
7663 }
7664 if (DSAStack->isParentOrderedRegion()) {
7665 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7666 return StmtError();
7667 }
7668 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7669 CancelRegion);
7670}
7671
Alexey Bataev87933c72015-09-18 08:07:34 +00007672StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7673 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007674 SourceLocation EndLoc,
7675 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007676 if (DSAStack->isParentNowaitRegion()) {
7677 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7678 return StmtError();
7679 }
7680 if (DSAStack->isParentOrderedRegion()) {
7681 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7682 return StmtError();
7683 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007684 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007685 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7686 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007687}
7688
Alexey Bataev382967a2015-12-08 12:06:20 +00007689static bool checkGrainsizeNumTasksClauses(Sema &S,
7690 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007691 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007692 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007693 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007694 if (C->getClauseKind() == OMPC_grainsize ||
7695 C->getClauseKind() == OMPC_num_tasks) {
7696 if (!PrevClause)
7697 PrevClause = C;
7698 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007699 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007700 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7701 << getOpenMPClauseName(C->getClauseKind())
7702 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007703 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007704 diag::note_omp_previous_grainsize_num_tasks)
7705 << getOpenMPClauseName(PrevClause->getClauseKind());
7706 ErrorFound = true;
7707 }
7708 }
7709 }
7710 return ErrorFound;
7711}
7712
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007713static bool checkReductionClauseWithNogroup(Sema &S,
7714 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007715 const OMPClause *ReductionClause = nullptr;
7716 const OMPClause *NogroupClause = nullptr;
7717 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007718 if (C->getClauseKind() == OMPC_reduction) {
7719 ReductionClause = C;
7720 if (NogroupClause)
7721 break;
7722 continue;
7723 }
7724 if (C->getClauseKind() == OMPC_nogroup) {
7725 NogroupClause = C;
7726 if (ReductionClause)
7727 break;
7728 continue;
7729 }
7730 }
7731 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007732 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7733 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007734 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007735 return true;
7736 }
7737 return false;
7738}
7739
Alexey Bataev49f6e782015-12-01 04:18:41 +00007740StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7741 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007742 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007743 if (!AStmt)
7744 return StmtError();
7745
7746 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7747 OMPLoopDirective::HelperExprs B;
7748 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7749 // define the nested loops number.
7750 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007751 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007752 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007753 VarsWithImplicitDSA, B);
7754 if (NestedLoopCount == 0)
7755 return StmtError();
7756
7757 assert((CurContext->isDependentContext() || B.builtAll()) &&
7758 "omp for loop exprs were not built");
7759
Alexey Bataev382967a2015-12-08 12:06:20 +00007760 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7761 // The grainsize clause and num_tasks clause are mutually exclusive and may
7762 // not appear on the same taskloop directive.
7763 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7764 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007765 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7766 // If a reduction clause is present on the taskloop directive, the nogroup
7767 // clause must not be specified.
7768 if (checkReductionClauseWithNogroup(*this, Clauses))
7769 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007770
Reid Kleckner87a31802018-03-12 21:43:02 +00007771 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007772 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7773 NestedLoopCount, Clauses, AStmt, B);
7774}
7775
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007776StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7777 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007778 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007779 if (!AStmt)
7780 return StmtError();
7781
7782 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7783 OMPLoopDirective::HelperExprs B;
7784 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7785 // define the nested loops number.
7786 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007787 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007788 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7789 VarsWithImplicitDSA, B);
7790 if (NestedLoopCount == 0)
7791 return StmtError();
7792
7793 assert((CurContext->isDependentContext() || B.builtAll()) &&
7794 "omp for loop exprs were not built");
7795
Alexey Bataev5a3af132016-03-29 08:58:54 +00007796 if (!CurContext->isDependentContext()) {
7797 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007798 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007799 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007800 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007801 B.NumIterations, *this, CurScope,
7802 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007803 return StmtError();
7804 }
7805 }
7806
Alexey Bataev382967a2015-12-08 12:06:20 +00007807 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7808 // The grainsize clause and num_tasks clause are mutually exclusive and may
7809 // not appear on the same taskloop directive.
7810 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7811 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007812 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7813 // If a reduction clause is present on the taskloop directive, the nogroup
7814 // clause must not be specified.
7815 if (checkReductionClauseWithNogroup(*this, Clauses))
7816 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007817 if (checkSimdlenSafelenSpecified(*this, Clauses))
7818 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007819
Reid Kleckner87a31802018-03-12 21:43:02 +00007820 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007821 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7822 NestedLoopCount, Clauses, AStmt, B);
7823}
7824
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007825StmtResult Sema::ActOnOpenMPDistributeDirective(
7826 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007827 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007828 if (!AStmt)
7829 return StmtError();
7830
7831 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7832 OMPLoopDirective::HelperExprs B;
7833 // In presence of clause 'collapse' with number of loops, it will
7834 // define the nested loops number.
7835 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007836 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007837 nullptr /*ordered not a clause on distribute*/, AStmt,
7838 *this, *DSAStack, VarsWithImplicitDSA, B);
7839 if (NestedLoopCount == 0)
7840 return StmtError();
7841
7842 assert((CurContext->isDependentContext() || B.builtAll()) &&
7843 "omp for loop exprs were not built");
7844
Reid Kleckner87a31802018-03-12 21:43:02 +00007845 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007846 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7847 NestedLoopCount, Clauses, AStmt, B);
7848}
7849
Carlo Bertolli9925f152016-06-27 14:55:37 +00007850StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7851 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007852 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007853 if (!AStmt)
7854 return StmtError();
7855
Alexey Bataeve3727102018-04-18 15:57:46 +00007856 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007857 // 1.2.2 OpenMP Language Terminology
7858 // Structured block - An executable statement with a single entry at the
7859 // top and a single exit at the bottom.
7860 // The point of exit cannot be a branch out of the structured block.
7861 // longjmp() and throw() must not violate the entry/exit criteria.
7862 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007863 for (int ThisCaptureLevel =
7864 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7865 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7866 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7867 // 1.2.2 OpenMP Language Terminology
7868 // Structured block - An executable statement with a single entry at the
7869 // top and a single exit at the bottom.
7870 // The point of exit cannot be a branch out of the structured block.
7871 // longjmp() and throw() must not violate the entry/exit criteria.
7872 CS->getCapturedDecl()->setNothrow();
7873 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007874
7875 OMPLoopDirective::HelperExprs B;
7876 // In presence of clause 'collapse' with number of loops, it will
7877 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007878 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007879 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007880 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007881 VarsWithImplicitDSA, B);
7882 if (NestedLoopCount == 0)
7883 return StmtError();
7884
7885 assert((CurContext->isDependentContext() || B.builtAll()) &&
7886 "omp for loop exprs were not built");
7887
Reid Kleckner87a31802018-03-12 21:43:02 +00007888 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007889 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007890 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7891 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007892}
7893
Kelvin Li4a39add2016-07-05 05:00:15 +00007894StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7895 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007896 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007897 if (!AStmt)
7898 return StmtError();
7899
Alexey Bataeve3727102018-04-18 15:57:46 +00007900 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007901 // 1.2.2 OpenMP Language Terminology
7902 // Structured block - An executable statement with a single entry at the
7903 // top and a single exit at the bottom.
7904 // The point of exit cannot be a branch out of the structured block.
7905 // longjmp() and throw() must not violate the entry/exit criteria.
7906 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007907 for (int ThisCaptureLevel =
7908 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7909 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7910 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7911 // 1.2.2 OpenMP Language Terminology
7912 // Structured block - An executable statement with a single entry at the
7913 // top and a single exit at the bottom.
7914 // The point of exit cannot be a branch out of the structured block.
7915 // longjmp() and throw() must not violate the entry/exit criteria.
7916 CS->getCapturedDecl()->setNothrow();
7917 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007918
7919 OMPLoopDirective::HelperExprs B;
7920 // In presence of clause 'collapse' with number of loops, it will
7921 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007922 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007923 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007924 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007925 VarsWithImplicitDSA, B);
7926 if (NestedLoopCount == 0)
7927 return StmtError();
7928
7929 assert((CurContext->isDependentContext() || B.builtAll()) &&
7930 "omp for loop exprs were not built");
7931
Alexey Bataev438388c2017-11-22 18:34:02 +00007932 if (!CurContext->isDependentContext()) {
7933 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007934 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007935 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7936 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7937 B.NumIterations, *this, CurScope,
7938 DSAStack))
7939 return StmtError();
7940 }
7941 }
7942
Kelvin Lic5609492016-07-15 04:39:07 +00007943 if (checkSimdlenSafelenSpecified(*this, Clauses))
7944 return StmtError();
7945
Reid Kleckner87a31802018-03-12 21:43:02 +00007946 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007947 return OMPDistributeParallelForSimdDirective::Create(
7948 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7949}
7950
Kelvin Li787f3fc2016-07-06 04:45:38 +00007951StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7952 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007953 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007954 if (!AStmt)
7955 return StmtError();
7956
Alexey Bataeve3727102018-04-18 15:57:46 +00007957 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007958 // 1.2.2 OpenMP Language Terminology
7959 // Structured block - An executable statement with a single entry at the
7960 // top and a single exit at the bottom.
7961 // The point of exit cannot be a branch out of the structured block.
7962 // longjmp() and throw() must not violate the entry/exit criteria.
7963 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007964 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7965 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7966 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7967 // 1.2.2 OpenMP Language Terminology
7968 // Structured block - An executable statement with a single entry at the
7969 // top and a single exit at the bottom.
7970 // The point of exit cannot be a branch out of the structured block.
7971 // longjmp() and throw() must not violate the entry/exit criteria.
7972 CS->getCapturedDecl()->setNothrow();
7973 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007974
7975 OMPLoopDirective::HelperExprs B;
7976 // In presence of clause 'collapse' with number of loops, it will
7977 // define the nested loops number.
7978 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007979 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007980 nullptr /*ordered not a clause on distribute*/, CS, *this,
7981 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007982 if (NestedLoopCount == 0)
7983 return StmtError();
7984
7985 assert((CurContext->isDependentContext() || B.builtAll()) &&
7986 "omp for loop exprs were not built");
7987
Alexey Bataev438388c2017-11-22 18:34:02 +00007988 if (!CurContext->isDependentContext()) {
7989 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007990 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007991 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7993 B.NumIterations, *this, CurScope,
7994 DSAStack))
7995 return StmtError();
7996 }
7997 }
7998
Kelvin Lic5609492016-07-15 04:39:07 +00007999 if (checkSimdlenSafelenSpecified(*this, Clauses))
8000 return StmtError();
8001
Reid Kleckner87a31802018-03-12 21:43:02 +00008002 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00008003 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8004 NestedLoopCount, Clauses, AStmt, B);
8005}
8006
Kelvin Lia579b912016-07-14 02:54:56 +00008007StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8008 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008009 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00008010 if (!AStmt)
8011 return StmtError();
8012
Alexey Bataeve3727102018-04-18 15:57:46 +00008013 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00008014 // 1.2.2 OpenMP Language Terminology
8015 // Structured block - An executable statement with a single entry at the
8016 // top and a single exit at the bottom.
8017 // The point of exit cannot be a branch out of the structured block.
8018 // longjmp() and throw() must not violate the entry/exit criteria.
8019 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008020 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8021 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8022 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8023 // 1.2.2 OpenMP Language Terminology
8024 // Structured block - An executable statement with a single entry at the
8025 // top and a single exit at the bottom.
8026 // The point of exit cannot be a branch out of the structured block.
8027 // longjmp() and throw() must not violate the entry/exit criteria.
8028 CS->getCapturedDecl()->setNothrow();
8029 }
Kelvin Lia579b912016-07-14 02:54:56 +00008030
8031 OMPLoopDirective::HelperExprs B;
8032 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8033 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008034 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008035 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008036 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008037 VarsWithImplicitDSA, B);
8038 if (NestedLoopCount == 0)
8039 return StmtError();
8040
8041 assert((CurContext->isDependentContext() || B.builtAll()) &&
8042 "omp target parallel for simd loop exprs were not built");
8043
8044 if (!CurContext->isDependentContext()) {
8045 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008046 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008047 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008048 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8049 B.NumIterations, *this, CurScope,
8050 DSAStack))
8051 return StmtError();
8052 }
8053 }
Kelvin Lic5609492016-07-15 04:39:07 +00008054 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008055 return StmtError();
8056
Reid Kleckner87a31802018-03-12 21:43:02 +00008057 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008058 return OMPTargetParallelForSimdDirective::Create(
8059 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8060}
8061
Kelvin Li986330c2016-07-20 22:57:10 +00008062StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8063 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008064 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008065 if (!AStmt)
8066 return StmtError();
8067
Alexey Bataeve3727102018-04-18 15:57:46 +00008068 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008069 // 1.2.2 OpenMP Language Terminology
8070 // Structured block - An executable statement with a single entry at the
8071 // top and a single exit at the bottom.
8072 // The point of exit cannot be a branch out of the structured block.
8073 // longjmp() and throw() must not violate the entry/exit criteria.
8074 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008075 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8076 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8077 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8078 // 1.2.2 OpenMP Language Terminology
8079 // Structured block - An executable statement with a single entry at the
8080 // top and a single exit at the bottom.
8081 // The point of exit cannot be a branch out of the structured block.
8082 // longjmp() and throw() must not violate the entry/exit criteria.
8083 CS->getCapturedDecl()->setNothrow();
8084 }
8085
Kelvin Li986330c2016-07-20 22:57:10 +00008086 OMPLoopDirective::HelperExprs B;
8087 // In presence of clause 'collapse' with number of loops, it will define the
8088 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008089 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008090 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008091 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008092 VarsWithImplicitDSA, B);
8093 if (NestedLoopCount == 0)
8094 return StmtError();
8095
8096 assert((CurContext->isDependentContext() || B.builtAll()) &&
8097 "omp target simd loop exprs were not built");
8098
8099 if (!CurContext->isDependentContext()) {
8100 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008101 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008102 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008103 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8104 B.NumIterations, *this, CurScope,
8105 DSAStack))
8106 return StmtError();
8107 }
8108 }
8109
8110 if (checkSimdlenSafelenSpecified(*this, Clauses))
8111 return StmtError();
8112
Reid Kleckner87a31802018-03-12 21:43:02 +00008113 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008114 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8115 NestedLoopCount, Clauses, AStmt, B);
8116}
8117
Kelvin Li02532872016-08-05 14:37:37 +00008118StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8119 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008120 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008121 if (!AStmt)
8122 return StmtError();
8123
Alexey Bataeve3727102018-04-18 15:57:46 +00008124 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008125 // 1.2.2 OpenMP Language Terminology
8126 // Structured block - An executable statement with a single entry at the
8127 // top and a single exit at the bottom.
8128 // The point of exit cannot be a branch out of the structured block.
8129 // longjmp() and throw() must not violate the entry/exit criteria.
8130 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008131 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8132 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8133 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8134 // 1.2.2 OpenMP Language Terminology
8135 // Structured block - An executable statement with a single entry at the
8136 // top and a single exit at the bottom.
8137 // The point of exit cannot be a branch out of the structured block.
8138 // longjmp() and throw() must not violate the entry/exit criteria.
8139 CS->getCapturedDecl()->setNothrow();
8140 }
Kelvin Li02532872016-08-05 14:37:37 +00008141
8142 OMPLoopDirective::HelperExprs B;
8143 // In presence of clause 'collapse' with number of loops, it will
8144 // define the nested loops number.
8145 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008146 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008147 nullptr /*ordered not a clause on distribute*/, CS, *this,
8148 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008149 if (NestedLoopCount == 0)
8150 return StmtError();
8151
8152 assert((CurContext->isDependentContext() || B.builtAll()) &&
8153 "omp teams distribute loop exprs were not built");
8154
Reid Kleckner87a31802018-03-12 21:43:02 +00008155 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008156
8157 DSAStack->setParentTeamsRegionLoc(StartLoc);
8158
David Majnemer9d168222016-08-05 17:44:54 +00008159 return OMPTeamsDistributeDirective::Create(
8160 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008161}
8162
Kelvin Li4e325f72016-10-25 12:50:55 +00008163StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8164 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008165 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008166 if (!AStmt)
8167 return StmtError();
8168
Alexey Bataeve3727102018-04-18 15:57:46 +00008169 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008170 // 1.2.2 OpenMP Language Terminology
8171 // Structured block - An executable statement with a single entry at the
8172 // top and a single exit at the bottom.
8173 // The point of exit cannot be a branch out of the structured block.
8174 // longjmp() and throw() must not violate the entry/exit criteria.
8175 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008176 for (int ThisCaptureLevel =
8177 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8178 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8179 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8180 // 1.2.2 OpenMP Language Terminology
8181 // Structured block - An executable statement with a single entry at the
8182 // top and a single exit at the bottom.
8183 // The point of exit cannot be a branch out of the structured block.
8184 // longjmp() and throw() must not violate the entry/exit criteria.
8185 CS->getCapturedDecl()->setNothrow();
8186 }
8187
Kelvin Li4e325f72016-10-25 12:50:55 +00008188
8189 OMPLoopDirective::HelperExprs B;
8190 // In presence of clause 'collapse' with number of loops, it will
8191 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008192 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008193 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008194 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008195 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008196
8197 if (NestedLoopCount == 0)
8198 return StmtError();
8199
8200 assert((CurContext->isDependentContext() || B.builtAll()) &&
8201 "omp teams distribute simd loop exprs were not built");
8202
8203 if (!CurContext->isDependentContext()) {
8204 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008205 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008206 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8207 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8208 B.NumIterations, *this, CurScope,
8209 DSAStack))
8210 return StmtError();
8211 }
8212 }
8213
8214 if (checkSimdlenSafelenSpecified(*this, Clauses))
8215 return StmtError();
8216
Reid Kleckner87a31802018-03-12 21:43:02 +00008217 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008218
8219 DSAStack->setParentTeamsRegionLoc(StartLoc);
8220
Kelvin Li4e325f72016-10-25 12:50:55 +00008221 return OMPTeamsDistributeSimdDirective::Create(
8222 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8223}
8224
Kelvin Li579e41c2016-11-30 23:51:03 +00008225StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8226 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008227 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008228 if (!AStmt)
8229 return StmtError();
8230
Alexey Bataeve3727102018-04-18 15:57:46 +00008231 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008232 // 1.2.2 OpenMP Language Terminology
8233 // Structured block - An executable statement with a single entry at the
8234 // top and a single exit at the bottom.
8235 // The point of exit cannot be a branch out of the structured block.
8236 // longjmp() and throw() must not violate the entry/exit criteria.
8237 CS->getCapturedDecl()->setNothrow();
8238
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008239 for (int ThisCaptureLevel =
8240 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8241 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8242 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8243 // 1.2.2 OpenMP Language Terminology
8244 // Structured block - An executable statement with a single entry at the
8245 // top and a single exit at the bottom.
8246 // The point of exit cannot be a branch out of the structured block.
8247 // longjmp() and throw() must not violate the entry/exit criteria.
8248 CS->getCapturedDecl()->setNothrow();
8249 }
8250
Kelvin Li579e41c2016-11-30 23:51:03 +00008251 OMPLoopDirective::HelperExprs B;
8252 // In presence of clause 'collapse' with number of loops, it will
8253 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008254 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008255 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008256 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008257 VarsWithImplicitDSA, B);
8258
8259 if (NestedLoopCount == 0)
8260 return StmtError();
8261
8262 assert((CurContext->isDependentContext() || B.builtAll()) &&
8263 "omp for loop exprs were not built");
8264
8265 if (!CurContext->isDependentContext()) {
8266 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008267 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008268 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8269 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8270 B.NumIterations, *this, CurScope,
8271 DSAStack))
8272 return StmtError();
8273 }
8274 }
8275
8276 if (checkSimdlenSafelenSpecified(*this, Clauses))
8277 return StmtError();
8278
Reid Kleckner87a31802018-03-12 21:43:02 +00008279 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008280
8281 DSAStack->setParentTeamsRegionLoc(StartLoc);
8282
Kelvin Li579e41c2016-11-30 23:51:03 +00008283 return OMPTeamsDistributeParallelForSimdDirective::Create(
8284 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8285}
8286
Kelvin Li7ade93f2016-12-09 03:24:30 +00008287StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8288 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008289 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008290 if (!AStmt)
8291 return StmtError();
8292
Alexey Bataeve3727102018-04-18 15:57:46 +00008293 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008294 // 1.2.2 OpenMP Language Terminology
8295 // Structured block - An executable statement with a single entry at the
8296 // top and a single exit at the bottom.
8297 // The point of exit cannot be a branch out of the structured block.
8298 // longjmp() and throw() must not violate the entry/exit criteria.
8299 CS->getCapturedDecl()->setNothrow();
8300
Carlo Bertolli62fae152017-11-20 20:46:39 +00008301 for (int ThisCaptureLevel =
8302 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8303 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8304 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8305 // 1.2.2 OpenMP Language Terminology
8306 // Structured block - An executable statement with a single entry at the
8307 // top and a single exit at the bottom.
8308 // The point of exit cannot be a branch out of the structured block.
8309 // longjmp() and throw() must not violate the entry/exit criteria.
8310 CS->getCapturedDecl()->setNothrow();
8311 }
8312
Kelvin Li7ade93f2016-12-09 03:24:30 +00008313 OMPLoopDirective::HelperExprs B;
8314 // In presence of clause 'collapse' with number of loops, it will
8315 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008316 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008317 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008318 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008319 VarsWithImplicitDSA, B);
8320
8321 if (NestedLoopCount == 0)
8322 return StmtError();
8323
8324 assert((CurContext->isDependentContext() || B.builtAll()) &&
8325 "omp for loop exprs were not built");
8326
Reid Kleckner87a31802018-03-12 21:43:02 +00008327 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008328
8329 DSAStack->setParentTeamsRegionLoc(StartLoc);
8330
Kelvin Li7ade93f2016-12-09 03:24:30 +00008331 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008332 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8333 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008334}
8335
Kelvin Libf594a52016-12-17 05:48:59 +00008336StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8337 Stmt *AStmt,
8338 SourceLocation StartLoc,
8339 SourceLocation EndLoc) {
8340 if (!AStmt)
8341 return StmtError();
8342
Alexey Bataeve3727102018-04-18 15:57:46 +00008343 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008344 // 1.2.2 OpenMP Language Terminology
8345 // Structured block - An executable statement with a single entry at the
8346 // top and a single exit at the bottom.
8347 // The point of exit cannot be a branch out of the structured block.
8348 // longjmp() and throw() must not violate the entry/exit criteria.
8349 CS->getCapturedDecl()->setNothrow();
8350
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008351 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8352 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8353 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8354 // 1.2.2 OpenMP Language Terminology
8355 // Structured block - An executable statement with a single entry at the
8356 // top and a single exit at the bottom.
8357 // The point of exit cannot be a branch out of the structured block.
8358 // longjmp() and throw() must not violate the entry/exit criteria.
8359 CS->getCapturedDecl()->setNothrow();
8360 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008361 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008362
8363 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8364 AStmt);
8365}
8366
Kelvin Li83c451e2016-12-25 04:52:54 +00008367StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8368 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008369 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008370 if (!AStmt)
8371 return StmtError();
8372
Alexey Bataeve3727102018-04-18 15:57:46 +00008373 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008374 // 1.2.2 OpenMP Language Terminology
8375 // Structured block - An executable statement with a single entry at the
8376 // top and a single exit at the bottom.
8377 // The point of exit cannot be a branch out of the structured block.
8378 // longjmp() and throw() must not violate the entry/exit criteria.
8379 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008380 for (int ThisCaptureLevel =
8381 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8382 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8383 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8384 // 1.2.2 OpenMP Language Terminology
8385 // Structured block - An executable statement with a single entry at the
8386 // top and a single exit at the bottom.
8387 // The point of exit cannot be a branch out of the structured block.
8388 // longjmp() and throw() must not violate the entry/exit criteria.
8389 CS->getCapturedDecl()->setNothrow();
8390 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008391
8392 OMPLoopDirective::HelperExprs B;
8393 // In presence of clause 'collapse' with number of loops, it will
8394 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008395 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008396 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8397 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008398 VarsWithImplicitDSA, B);
8399 if (NestedLoopCount == 0)
8400 return StmtError();
8401
8402 assert((CurContext->isDependentContext() || B.builtAll()) &&
8403 "omp target teams distribute loop exprs were not built");
8404
Reid Kleckner87a31802018-03-12 21:43:02 +00008405 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008406 return OMPTargetTeamsDistributeDirective::Create(
8407 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8408}
8409
Kelvin Li80e8f562016-12-29 22:16:30 +00008410StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8411 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008412 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008413 if (!AStmt)
8414 return StmtError();
8415
Alexey Bataeve3727102018-04-18 15:57:46 +00008416 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008417 // 1.2.2 OpenMP Language Terminology
8418 // Structured block - An executable statement with a single entry at the
8419 // top and a single exit at the bottom.
8420 // The point of exit cannot be a branch out of the structured block.
8421 // longjmp() and throw() must not violate the entry/exit criteria.
8422 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008423 for (int ThisCaptureLevel =
8424 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8425 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8426 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8427 // 1.2.2 OpenMP Language Terminology
8428 // Structured block - An executable statement with a single entry at the
8429 // top and a single exit at the bottom.
8430 // The point of exit cannot be a branch out of the structured block.
8431 // longjmp() and throw() must not violate the entry/exit criteria.
8432 CS->getCapturedDecl()->setNothrow();
8433 }
8434
Kelvin Li80e8f562016-12-29 22:16:30 +00008435 OMPLoopDirective::HelperExprs B;
8436 // In presence of clause 'collapse' with number of loops, it will
8437 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008438 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008439 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8440 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008441 VarsWithImplicitDSA, B);
8442 if (NestedLoopCount == 0)
8443 return StmtError();
8444
8445 assert((CurContext->isDependentContext() || B.builtAll()) &&
8446 "omp target teams distribute parallel for loop exprs were not built");
8447
Alexey Bataev647dd842018-01-15 20:59:40 +00008448 if (!CurContext->isDependentContext()) {
8449 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008450 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008451 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8452 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8453 B.NumIterations, *this, CurScope,
8454 DSAStack))
8455 return StmtError();
8456 }
8457 }
8458
Reid Kleckner87a31802018-03-12 21:43:02 +00008459 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008460 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008461 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8462 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008463}
8464
Kelvin Li1851df52017-01-03 05:23:48 +00008465StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8466 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008467 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008468 if (!AStmt)
8469 return StmtError();
8470
Alexey Bataeve3727102018-04-18 15:57:46 +00008471 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008472 // 1.2.2 OpenMP Language Terminology
8473 // Structured block - An executable statement with a single entry at the
8474 // top and a single exit at the bottom.
8475 // The point of exit cannot be a branch out of the structured block.
8476 // longjmp() and throw() must not violate the entry/exit criteria.
8477 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008478 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8479 OMPD_target_teams_distribute_parallel_for_simd);
8480 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8481 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8482 // 1.2.2 OpenMP Language Terminology
8483 // Structured block - An executable statement with a single entry at the
8484 // top and a single exit at the bottom.
8485 // The point of exit cannot be a branch out of the structured block.
8486 // longjmp() and throw() must not violate the entry/exit criteria.
8487 CS->getCapturedDecl()->setNothrow();
8488 }
Kelvin Li1851df52017-01-03 05:23:48 +00008489
8490 OMPLoopDirective::HelperExprs B;
8491 // In presence of clause 'collapse' with number of loops, it will
8492 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008493 unsigned NestedLoopCount =
8494 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008495 getCollapseNumberExpr(Clauses),
8496 nullptr /*ordered not a clause on distribute*/, CS, *this,
8497 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008498 if (NestedLoopCount == 0)
8499 return StmtError();
8500
8501 assert((CurContext->isDependentContext() || B.builtAll()) &&
8502 "omp target teams distribute parallel for simd loop exprs were not "
8503 "built");
8504
8505 if (!CurContext->isDependentContext()) {
8506 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008507 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008508 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8509 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8510 B.NumIterations, *this, CurScope,
8511 DSAStack))
8512 return StmtError();
8513 }
8514 }
8515
Alexey Bataev438388c2017-11-22 18:34:02 +00008516 if (checkSimdlenSafelenSpecified(*this, Clauses))
8517 return StmtError();
8518
Reid Kleckner87a31802018-03-12 21:43:02 +00008519 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008520 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8521 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8522}
8523
Kelvin Lida681182017-01-10 18:08:18 +00008524StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8525 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008526 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008527 if (!AStmt)
8528 return StmtError();
8529
8530 auto *CS = cast<CapturedStmt>(AStmt);
8531 // 1.2.2 OpenMP Language Terminology
8532 // Structured block - An executable statement with a single entry at the
8533 // top and a single exit at the bottom.
8534 // The point of exit cannot be a branch out of the structured block.
8535 // longjmp() and throw() must not violate the entry/exit criteria.
8536 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008537 for (int ThisCaptureLevel =
8538 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8539 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8540 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8541 // 1.2.2 OpenMP Language Terminology
8542 // Structured block - An executable statement with a single entry at the
8543 // top and a single exit at the bottom.
8544 // The point of exit cannot be a branch out of the structured block.
8545 // longjmp() and throw() must not violate the entry/exit criteria.
8546 CS->getCapturedDecl()->setNothrow();
8547 }
Kelvin Lida681182017-01-10 18:08:18 +00008548
8549 OMPLoopDirective::HelperExprs B;
8550 // In presence of clause 'collapse' with number of loops, it will
8551 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008552 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008553 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008554 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008555 VarsWithImplicitDSA, B);
8556 if (NestedLoopCount == 0)
8557 return StmtError();
8558
8559 assert((CurContext->isDependentContext() || B.builtAll()) &&
8560 "omp target teams distribute simd loop exprs were not built");
8561
Alexey Bataev438388c2017-11-22 18:34:02 +00008562 if (!CurContext->isDependentContext()) {
8563 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008564 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008565 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8566 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8567 B.NumIterations, *this, CurScope,
8568 DSAStack))
8569 return StmtError();
8570 }
8571 }
8572
8573 if (checkSimdlenSafelenSpecified(*this, Clauses))
8574 return StmtError();
8575
Reid Kleckner87a31802018-03-12 21:43:02 +00008576 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008577 return OMPTargetTeamsDistributeSimdDirective::Create(
8578 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8579}
8580
Alexey Bataeved09d242014-05-28 05:53:51 +00008581OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008582 SourceLocation StartLoc,
8583 SourceLocation LParenLoc,
8584 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008585 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008586 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008587 case OMPC_final:
8588 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8589 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008590 case OMPC_num_threads:
8591 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8592 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008593 case OMPC_safelen:
8594 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8595 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008596 case OMPC_simdlen:
8597 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8598 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008599 case OMPC_allocator:
8600 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8601 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008602 case OMPC_collapse:
8603 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8604 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008605 case OMPC_ordered:
8606 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8607 break;
Michael Wonge710d542015-08-07 16:16:36 +00008608 case OMPC_device:
8609 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8610 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008611 case OMPC_num_teams:
8612 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8613 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008614 case OMPC_thread_limit:
8615 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8616 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008617 case OMPC_priority:
8618 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8619 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008620 case OMPC_grainsize:
8621 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8622 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008623 case OMPC_num_tasks:
8624 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8625 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008626 case OMPC_hint:
8627 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8628 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008629 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008630 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008631 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008632 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008633 case OMPC_private:
8634 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008635 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008636 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008637 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008638 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008639 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008640 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008641 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008642 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008643 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008644 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008645 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008646 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008647 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008648 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008649 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008650 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008651 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008652 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008653 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008654 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008655 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008656 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008657 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008658 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008659 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008660 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008661 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008662 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008663 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008664 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008665 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008666 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008667 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008668 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008669 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008670 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008671 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008672 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008673 llvm_unreachable("Clause is not allowed.");
8674 }
8675 return Res;
8676}
8677
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008678// An OpenMP directive such as 'target parallel' has two captured regions:
8679// for the 'target' and 'parallel' respectively. This function returns
8680// the region in which to capture expressions associated with a clause.
8681// A return value of OMPD_unknown signifies that the expression should not
8682// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008683static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8684 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8685 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008686 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008687 switch (CKind) {
8688 case OMPC_if:
8689 switch (DKind) {
8690 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008691 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008692 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008693 // If this clause applies to the nested 'parallel' region, capture within
8694 // the 'target' region, otherwise do not capture.
8695 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8696 CaptureRegion = OMPD_target;
8697 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008698 case OMPD_target_teams_distribute_parallel_for:
8699 case OMPD_target_teams_distribute_parallel_for_simd:
8700 // If this clause applies to the nested 'parallel' region, capture within
8701 // the 'teams' region, otherwise do not capture.
8702 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8703 CaptureRegion = OMPD_teams;
8704 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008705 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008706 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008707 CaptureRegion = OMPD_teams;
8708 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008709 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008710 case OMPD_target_enter_data:
8711 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008712 CaptureRegion = OMPD_task;
8713 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008714 case OMPD_cancel:
8715 case OMPD_parallel:
8716 case OMPD_parallel_sections:
8717 case OMPD_parallel_for:
8718 case OMPD_parallel_for_simd:
8719 case OMPD_target:
8720 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008721 case OMPD_target_teams:
8722 case OMPD_target_teams_distribute:
8723 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008724 case OMPD_distribute_parallel_for:
8725 case OMPD_distribute_parallel_for_simd:
8726 case OMPD_task:
8727 case OMPD_taskloop:
8728 case OMPD_taskloop_simd:
8729 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008730 // Do not capture if-clause expressions.
8731 break;
8732 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008733 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008734 case OMPD_taskyield:
8735 case OMPD_barrier:
8736 case OMPD_taskwait:
8737 case OMPD_cancellation_point:
8738 case OMPD_flush:
8739 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008740 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008741 case OMPD_declare_simd:
8742 case OMPD_declare_target:
8743 case OMPD_end_declare_target:
8744 case OMPD_teams:
8745 case OMPD_simd:
8746 case OMPD_for:
8747 case OMPD_for_simd:
8748 case OMPD_sections:
8749 case OMPD_section:
8750 case OMPD_single:
8751 case OMPD_master:
8752 case OMPD_critical:
8753 case OMPD_taskgroup:
8754 case OMPD_distribute:
8755 case OMPD_ordered:
8756 case OMPD_atomic:
8757 case OMPD_distribute_simd:
8758 case OMPD_teams_distribute:
8759 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008760 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008761 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8762 case OMPD_unknown:
8763 llvm_unreachable("Unknown OpenMP directive");
8764 }
8765 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008766 case OMPC_num_threads:
8767 switch (DKind) {
8768 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008769 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008770 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008771 CaptureRegion = OMPD_target;
8772 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008773 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008774 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008775 case OMPD_target_teams_distribute_parallel_for:
8776 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008777 CaptureRegion = OMPD_teams;
8778 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008779 case OMPD_parallel:
8780 case OMPD_parallel_sections:
8781 case OMPD_parallel_for:
8782 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008783 case OMPD_distribute_parallel_for:
8784 case OMPD_distribute_parallel_for_simd:
8785 // Do not capture num_threads-clause expressions.
8786 break;
8787 case OMPD_target_data:
8788 case OMPD_target_enter_data:
8789 case OMPD_target_exit_data:
8790 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008791 case OMPD_target:
8792 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008793 case OMPD_target_teams:
8794 case OMPD_target_teams_distribute:
8795 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008796 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008797 case OMPD_task:
8798 case OMPD_taskloop:
8799 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008800 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008801 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008802 case OMPD_taskyield:
8803 case OMPD_barrier:
8804 case OMPD_taskwait:
8805 case OMPD_cancellation_point:
8806 case OMPD_flush:
8807 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008808 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008809 case OMPD_declare_simd:
8810 case OMPD_declare_target:
8811 case OMPD_end_declare_target:
8812 case OMPD_teams:
8813 case OMPD_simd:
8814 case OMPD_for:
8815 case OMPD_for_simd:
8816 case OMPD_sections:
8817 case OMPD_section:
8818 case OMPD_single:
8819 case OMPD_master:
8820 case OMPD_critical:
8821 case OMPD_taskgroup:
8822 case OMPD_distribute:
8823 case OMPD_ordered:
8824 case OMPD_atomic:
8825 case OMPD_distribute_simd:
8826 case OMPD_teams_distribute:
8827 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008828 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008829 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8830 case OMPD_unknown:
8831 llvm_unreachable("Unknown OpenMP directive");
8832 }
8833 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008834 case OMPC_num_teams:
8835 switch (DKind) {
8836 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008837 case OMPD_target_teams_distribute:
8838 case OMPD_target_teams_distribute_simd:
8839 case OMPD_target_teams_distribute_parallel_for:
8840 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008841 CaptureRegion = OMPD_target;
8842 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008843 case OMPD_teams_distribute_parallel_for:
8844 case OMPD_teams_distribute_parallel_for_simd:
8845 case OMPD_teams:
8846 case OMPD_teams_distribute:
8847 case OMPD_teams_distribute_simd:
8848 // Do not capture num_teams-clause expressions.
8849 break;
8850 case OMPD_distribute_parallel_for:
8851 case OMPD_distribute_parallel_for_simd:
8852 case OMPD_task:
8853 case OMPD_taskloop:
8854 case OMPD_taskloop_simd:
8855 case OMPD_target_data:
8856 case OMPD_target_enter_data:
8857 case OMPD_target_exit_data:
8858 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008859 case OMPD_cancel:
8860 case OMPD_parallel:
8861 case OMPD_parallel_sections:
8862 case OMPD_parallel_for:
8863 case OMPD_parallel_for_simd:
8864 case OMPD_target:
8865 case OMPD_target_simd:
8866 case OMPD_target_parallel:
8867 case OMPD_target_parallel_for:
8868 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008869 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008870 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008871 case OMPD_taskyield:
8872 case OMPD_barrier:
8873 case OMPD_taskwait:
8874 case OMPD_cancellation_point:
8875 case OMPD_flush:
8876 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008877 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008878 case OMPD_declare_simd:
8879 case OMPD_declare_target:
8880 case OMPD_end_declare_target:
8881 case OMPD_simd:
8882 case OMPD_for:
8883 case OMPD_for_simd:
8884 case OMPD_sections:
8885 case OMPD_section:
8886 case OMPD_single:
8887 case OMPD_master:
8888 case OMPD_critical:
8889 case OMPD_taskgroup:
8890 case OMPD_distribute:
8891 case OMPD_ordered:
8892 case OMPD_atomic:
8893 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008894 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008895 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8896 case OMPD_unknown:
8897 llvm_unreachable("Unknown OpenMP directive");
8898 }
8899 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008900 case OMPC_thread_limit:
8901 switch (DKind) {
8902 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008903 case OMPD_target_teams_distribute:
8904 case OMPD_target_teams_distribute_simd:
8905 case OMPD_target_teams_distribute_parallel_for:
8906 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008907 CaptureRegion = OMPD_target;
8908 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008909 case OMPD_teams_distribute_parallel_for:
8910 case OMPD_teams_distribute_parallel_for_simd:
8911 case OMPD_teams:
8912 case OMPD_teams_distribute:
8913 case OMPD_teams_distribute_simd:
8914 // Do not capture thread_limit-clause expressions.
8915 break;
8916 case OMPD_distribute_parallel_for:
8917 case OMPD_distribute_parallel_for_simd:
8918 case OMPD_task:
8919 case OMPD_taskloop:
8920 case OMPD_taskloop_simd:
8921 case OMPD_target_data:
8922 case OMPD_target_enter_data:
8923 case OMPD_target_exit_data:
8924 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008925 case OMPD_cancel:
8926 case OMPD_parallel:
8927 case OMPD_parallel_sections:
8928 case OMPD_parallel_for:
8929 case OMPD_parallel_for_simd:
8930 case OMPD_target:
8931 case OMPD_target_simd:
8932 case OMPD_target_parallel:
8933 case OMPD_target_parallel_for:
8934 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008935 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008936 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008937 case OMPD_taskyield:
8938 case OMPD_barrier:
8939 case OMPD_taskwait:
8940 case OMPD_cancellation_point:
8941 case OMPD_flush:
8942 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008943 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008944 case OMPD_declare_simd:
8945 case OMPD_declare_target:
8946 case OMPD_end_declare_target:
8947 case OMPD_simd:
8948 case OMPD_for:
8949 case OMPD_for_simd:
8950 case OMPD_sections:
8951 case OMPD_section:
8952 case OMPD_single:
8953 case OMPD_master:
8954 case OMPD_critical:
8955 case OMPD_taskgroup:
8956 case OMPD_distribute:
8957 case OMPD_ordered:
8958 case OMPD_atomic:
8959 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008960 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008961 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8962 case OMPD_unknown:
8963 llvm_unreachable("Unknown OpenMP directive");
8964 }
8965 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008966 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008967 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008968 case OMPD_parallel_for:
8969 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008970 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008971 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008972 case OMPD_teams_distribute_parallel_for:
8973 case OMPD_teams_distribute_parallel_for_simd:
8974 case OMPD_target_parallel_for:
8975 case OMPD_target_parallel_for_simd:
8976 case OMPD_target_teams_distribute_parallel_for:
8977 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008978 CaptureRegion = OMPD_parallel;
8979 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008980 case OMPD_for:
8981 case OMPD_for_simd:
8982 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008983 break;
8984 case OMPD_task:
8985 case OMPD_taskloop:
8986 case OMPD_taskloop_simd:
8987 case OMPD_target_data:
8988 case OMPD_target_enter_data:
8989 case OMPD_target_exit_data:
8990 case OMPD_target_update:
8991 case OMPD_teams:
8992 case OMPD_teams_distribute:
8993 case OMPD_teams_distribute_simd:
8994 case OMPD_target_teams_distribute:
8995 case OMPD_target_teams_distribute_simd:
8996 case OMPD_target:
8997 case OMPD_target_simd:
8998 case OMPD_target_parallel:
8999 case OMPD_cancel:
9000 case OMPD_parallel:
9001 case OMPD_parallel_sections:
9002 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009003 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009004 case OMPD_taskyield:
9005 case OMPD_barrier:
9006 case OMPD_taskwait:
9007 case OMPD_cancellation_point:
9008 case OMPD_flush:
9009 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009010 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009011 case OMPD_declare_simd:
9012 case OMPD_declare_target:
9013 case OMPD_end_declare_target:
9014 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009015 case OMPD_sections:
9016 case OMPD_section:
9017 case OMPD_single:
9018 case OMPD_master:
9019 case OMPD_critical:
9020 case OMPD_taskgroup:
9021 case OMPD_distribute:
9022 case OMPD_ordered:
9023 case OMPD_atomic:
9024 case OMPD_distribute_simd:
9025 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009026 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009027 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9028 case OMPD_unknown:
9029 llvm_unreachable("Unknown OpenMP directive");
9030 }
9031 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009032 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009033 switch (DKind) {
9034 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009035 case OMPD_teams_distribute_parallel_for_simd:
9036 case OMPD_teams_distribute:
9037 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009038 case OMPD_target_teams_distribute_parallel_for:
9039 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009040 case OMPD_target_teams_distribute:
9041 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009042 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009043 break;
9044 case OMPD_distribute_parallel_for:
9045 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009046 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009047 case OMPD_distribute_simd:
9048 // Do not capture thread_limit-clause expressions.
9049 break;
9050 case OMPD_parallel_for:
9051 case OMPD_parallel_for_simd:
9052 case OMPD_target_parallel_for_simd:
9053 case OMPD_target_parallel_for:
9054 case OMPD_task:
9055 case OMPD_taskloop:
9056 case OMPD_taskloop_simd:
9057 case OMPD_target_data:
9058 case OMPD_target_enter_data:
9059 case OMPD_target_exit_data:
9060 case OMPD_target_update:
9061 case OMPD_teams:
9062 case OMPD_target:
9063 case OMPD_target_simd:
9064 case OMPD_target_parallel:
9065 case OMPD_cancel:
9066 case OMPD_parallel:
9067 case OMPD_parallel_sections:
9068 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009069 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009070 case OMPD_taskyield:
9071 case OMPD_barrier:
9072 case OMPD_taskwait:
9073 case OMPD_cancellation_point:
9074 case OMPD_flush:
9075 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009076 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009077 case OMPD_declare_simd:
9078 case OMPD_declare_target:
9079 case OMPD_end_declare_target:
9080 case OMPD_simd:
9081 case OMPD_for:
9082 case OMPD_for_simd:
9083 case OMPD_sections:
9084 case OMPD_section:
9085 case OMPD_single:
9086 case OMPD_master:
9087 case OMPD_critical:
9088 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009089 case OMPD_ordered:
9090 case OMPD_atomic:
9091 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009092 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009093 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9094 case OMPD_unknown:
9095 llvm_unreachable("Unknown OpenMP directive");
9096 }
9097 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009098 case OMPC_device:
9099 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009100 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009101 case OMPD_target_enter_data:
9102 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009103 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009104 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009105 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009106 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009107 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009108 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009109 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009110 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009111 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009112 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009113 CaptureRegion = OMPD_task;
9114 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009115 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009116 // Do not capture device-clause expressions.
9117 break;
9118 case OMPD_teams_distribute_parallel_for:
9119 case OMPD_teams_distribute_parallel_for_simd:
9120 case OMPD_teams:
9121 case OMPD_teams_distribute:
9122 case OMPD_teams_distribute_simd:
9123 case OMPD_distribute_parallel_for:
9124 case OMPD_distribute_parallel_for_simd:
9125 case OMPD_task:
9126 case OMPD_taskloop:
9127 case OMPD_taskloop_simd:
9128 case OMPD_cancel:
9129 case OMPD_parallel:
9130 case OMPD_parallel_sections:
9131 case OMPD_parallel_for:
9132 case OMPD_parallel_for_simd:
9133 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009134 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009135 case OMPD_taskyield:
9136 case OMPD_barrier:
9137 case OMPD_taskwait:
9138 case OMPD_cancellation_point:
9139 case OMPD_flush:
9140 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009141 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009142 case OMPD_declare_simd:
9143 case OMPD_declare_target:
9144 case OMPD_end_declare_target:
9145 case OMPD_simd:
9146 case OMPD_for:
9147 case OMPD_for_simd:
9148 case OMPD_sections:
9149 case OMPD_section:
9150 case OMPD_single:
9151 case OMPD_master:
9152 case OMPD_critical:
9153 case OMPD_taskgroup:
9154 case OMPD_distribute:
9155 case OMPD_ordered:
9156 case OMPD_atomic:
9157 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009158 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009159 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9160 case OMPD_unknown:
9161 llvm_unreachable("Unknown OpenMP directive");
9162 }
9163 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009164 case OMPC_firstprivate:
9165 case OMPC_lastprivate:
9166 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009167 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009168 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009169 case OMPC_linear:
9170 case OMPC_default:
9171 case OMPC_proc_bind:
9172 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009173 case OMPC_safelen:
9174 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009175 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009176 case OMPC_collapse:
9177 case OMPC_private:
9178 case OMPC_shared:
9179 case OMPC_aligned:
9180 case OMPC_copyin:
9181 case OMPC_copyprivate:
9182 case OMPC_ordered:
9183 case OMPC_nowait:
9184 case OMPC_untied:
9185 case OMPC_mergeable:
9186 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009187 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009188 case OMPC_flush:
9189 case OMPC_read:
9190 case OMPC_write:
9191 case OMPC_update:
9192 case OMPC_capture:
9193 case OMPC_seq_cst:
9194 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009195 case OMPC_threads:
9196 case OMPC_simd:
9197 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009198 case OMPC_priority:
9199 case OMPC_grainsize:
9200 case OMPC_nogroup:
9201 case OMPC_num_tasks:
9202 case OMPC_hint:
9203 case OMPC_defaultmap:
9204 case OMPC_unknown:
9205 case OMPC_uniform:
9206 case OMPC_to:
9207 case OMPC_from:
9208 case OMPC_use_device_ptr:
9209 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009210 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009211 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009212 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009213 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009214 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009215 llvm_unreachable("Unexpected OpenMP clause.");
9216 }
9217 return CaptureRegion;
9218}
9219
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009220OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9221 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009222 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009223 SourceLocation NameModifierLoc,
9224 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009225 SourceLocation EndLoc) {
9226 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009227 Stmt *HelperValStmt = nullptr;
9228 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009229 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9230 !Condition->isInstantiationDependent() &&
9231 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009232 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009233 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009234 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009235
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009236 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009237
9238 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9239 CaptureRegion =
9240 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009241 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009242 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009243 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009244 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9245 HelperValStmt = buildPreInits(Context, Captures);
9246 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009247 }
9248
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009249 return new (Context)
9250 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9251 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009252}
9253
Alexey Bataev3778b602014-07-17 07:32:53 +00009254OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9255 SourceLocation StartLoc,
9256 SourceLocation LParenLoc,
9257 SourceLocation EndLoc) {
9258 Expr *ValExpr = Condition;
9259 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9260 !Condition->isInstantiationDependent() &&
9261 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009262 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009263 if (Val.isInvalid())
9264 return nullptr;
9265
Richard Smith03a4aa32016-06-23 19:02:52 +00009266 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009267 }
9268
9269 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9270}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009271ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9272 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009273 if (!Op)
9274 return ExprError();
9275
9276 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9277 public:
9278 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009279 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009280 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9281 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009282 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9283 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009284 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9285 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009286 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9287 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009288 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9289 QualType T,
9290 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009291 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9292 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009293 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9294 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009295 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009296 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009297 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009298 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9299 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009300 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9301 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009302 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9303 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009304 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009305 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009306 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009307 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9308 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009309 llvm_unreachable("conversion functions are permitted");
9310 }
9311 } ConvertDiagnoser;
9312 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9313}
9314
Alexey Bataeve3727102018-04-18 15:57:46 +00009315static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009316 OpenMPClauseKind CKind,
9317 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009318 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9319 !ValExpr->isInstantiationDependent()) {
9320 SourceLocation Loc = ValExpr->getExprLoc();
9321 ExprResult Value =
9322 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9323 if (Value.isInvalid())
9324 return false;
9325
9326 ValExpr = Value.get();
9327 // The expression must evaluate to a non-negative integer value.
9328 llvm::APSInt Result;
9329 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009330 Result.isSigned() &&
9331 !((!StrictlyPositive && Result.isNonNegative()) ||
9332 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009333 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009334 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9335 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009336 return false;
9337 }
9338 }
9339 return true;
9340}
9341
Alexey Bataev568a8332014-03-06 06:15:19 +00009342OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9343 SourceLocation StartLoc,
9344 SourceLocation LParenLoc,
9345 SourceLocation EndLoc) {
9346 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009347 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009348
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009349 // OpenMP [2.5, Restrictions]
9350 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009351 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009352 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009353 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009354
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009355 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009356 OpenMPDirectiveKind CaptureRegion =
9357 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9358 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009359 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009360 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009361 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9362 HelperValStmt = buildPreInits(Context, Captures);
9363 }
9364
9365 return new (Context) OMPNumThreadsClause(
9366 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009367}
9368
Alexey Bataev62c87d22014-03-21 04:51:18 +00009369ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009370 OpenMPClauseKind CKind,
9371 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009372 if (!E)
9373 return ExprError();
9374 if (E->isValueDependent() || E->isTypeDependent() ||
9375 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009376 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009377 llvm::APSInt Result;
9378 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9379 if (ICE.isInvalid())
9380 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009381 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9382 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009383 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009384 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9385 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009386 return ExprError();
9387 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009388 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9389 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9390 << E->getSourceRange();
9391 return ExprError();
9392 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009393 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9394 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009395 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009396 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009397 return ICE;
9398}
9399
9400OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9401 SourceLocation LParenLoc,
9402 SourceLocation EndLoc) {
9403 // OpenMP [2.8.1, simd construct, Description]
9404 // The parameter of the safelen clause must be a constant
9405 // positive integer expression.
9406 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9407 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009408 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009409 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009410 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009411}
9412
Alexey Bataev66b15b52015-08-21 11:14:16 +00009413OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9414 SourceLocation LParenLoc,
9415 SourceLocation EndLoc) {
9416 // OpenMP [2.8.1, simd construct, Description]
9417 // The parameter of the simdlen clause must be a constant
9418 // positive integer expression.
9419 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9420 if (Simdlen.isInvalid())
9421 return nullptr;
9422 return new (Context)
9423 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9424}
9425
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009426/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009427static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9428 DSAStackTy *Stack) {
9429 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009430 if (!OMPAllocatorHandleT.isNull())
9431 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009432 // Build the predefined allocator expressions.
9433 bool ErrorFound = false;
9434 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9435 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9436 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9437 StringRef Allocator =
9438 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9439 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9440 auto *VD = dyn_cast_or_null<ValueDecl>(
9441 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9442 if (!VD) {
9443 ErrorFound = true;
9444 break;
9445 }
9446 QualType AllocatorType =
9447 VD->getType().getNonLValueExprType(S.getASTContext());
9448 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9449 if (!Res.isUsable()) {
9450 ErrorFound = true;
9451 break;
9452 }
9453 if (OMPAllocatorHandleT.isNull())
9454 OMPAllocatorHandleT = AllocatorType;
9455 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9456 ErrorFound = true;
9457 break;
9458 }
9459 Stack->setAllocator(AllocatorKind, Res.get());
9460 }
9461 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009462 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9463 return false;
9464 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00009465 OMPAllocatorHandleT.addConst();
9466 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009467 return true;
9468}
9469
9470OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9471 SourceLocation LParenLoc,
9472 SourceLocation EndLoc) {
9473 // OpenMP [2.11.3, allocate Directive, Description]
9474 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009475 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009476 return nullptr;
9477
9478 ExprResult Allocator = DefaultLvalueConversion(A);
9479 if (Allocator.isInvalid())
9480 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009481 Allocator = PerformImplicitConversion(Allocator.get(),
9482 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009483 Sema::AA_Initializing,
9484 /*AllowExplicit=*/true);
9485 if (Allocator.isInvalid())
9486 return nullptr;
9487 return new (Context)
9488 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9489}
9490
Alexander Musman64d33f12014-06-04 07:53:32 +00009491OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9492 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009493 SourceLocation LParenLoc,
9494 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009495 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009496 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009497 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009498 // The parameter of the collapse clause must be a constant
9499 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009500 ExprResult NumForLoopsResult =
9501 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9502 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009503 return nullptr;
9504 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009505 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009506}
9507
Alexey Bataev10e775f2015-07-30 11:36:16 +00009508OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9509 SourceLocation EndLoc,
9510 SourceLocation LParenLoc,
9511 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009512 // OpenMP [2.7.1, loop construct, Description]
9513 // OpenMP [2.8.1, simd construct, Description]
9514 // OpenMP [2.9.6, distribute construct, Description]
9515 // The parameter of the ordered clause must be a constant
9516 // positive integer expression if any.
9517 if (NumForLoops && LParenLoc.isValid()) {
9518 ExprResult NumForLoopsResult =
9519 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9520 if (NumForLoopsResult.isInvalid())
9521 return nullptr;
9522 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009523 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009524 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009525 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009526 auto *Clause = OMPOrderedClause::Create(
9527 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9528 StartLoc, LParenLoc, EndLoc);
9529 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9530 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009531}
9532
Alexey Bataeved09d242014-05-28 05:53:51 +00009533OMPClause *Sema::ActOnOpenMPSimpleClause(
9534 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9535 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009536 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009537 switch (Kind) {
9538 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009539 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009540 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9541 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009542 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009543 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009544 Res = ActOnOpenMPProcBindClause(
9545 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9546 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009547 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009548 case OMPC_atomic_default_mem_order:
9549 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9550 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9551 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9552 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009553 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009554 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009555 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009556 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009557 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009558 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009559 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009560 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009561 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009562 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009563 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009564 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009565 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009566 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009567 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009568 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009569 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009570 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009571 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009572 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009573 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009574 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009575 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009576 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009577 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009578 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009579 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009580 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009581 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009582 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009583 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009584 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009585 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009586 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009587 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009588 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009589 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009590 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009591 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009592 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009593 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009594 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009595 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009596 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009597 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009598 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009599 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009600 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009601 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009602 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009603 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009604 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009605 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009606 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009607 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009608 llvm_unreachable("Clause is not allowed.");
9609 }
9610 return Res;
9611}
9612
Alexey Bataev6402bca2015-12-28 07:25:51 +00009613static std::string
9614getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9615 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009616 SmallString<256> Buffer;
9617 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009618 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9619 unsigned Skipped = Exclude.size();
9620 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009621 for (unsigned I = First; I < Last; ++I) {
9622 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009623 --Skipped;
9624 continue;
9625 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009626 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9627 if (I == Bound - Skipped)
9628 Out << " or ";
9629 else if (I != Bound + 1 - Skipped)
9630 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009631 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009632 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009633}
9634
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009635OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9636 SourceLocation KindKwLoc,
9637 SourceLocation StartLoc,
9638 SourceLocation LParenLoc,
9639 SourceLocation EndLoc) {
9640 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009641 static_assert(OMPC_DEFAULT_unknown > 0,
9642 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009643 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009644 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9645 /*Last=*/OMPC_DEFAULT_unknown)
9646 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009647 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009648 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009649 switch (Kind) {
9650 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009651 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009652 break;
9653 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009654 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009655 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009656 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009657 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009658 break;
9659 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009660 return new (Context)
9661 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009662}
9663
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009664OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9665 SourceLocation KindKwLoc,
9666 SourceLocation StartLoc,
9667 SourceLocation LParenLoc,
9668 SourceLocation EndLoc) {
9669 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009670 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009671 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9672 /*Last=*/OMPC_PROC_BIND_unknown)
9673 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009674 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009675 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009676 return new (Context)
9677 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009678}
9679
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009680OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9681 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9682 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9683 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9684 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9685 << getListOfPossibleValues(
9686 OMPC_atomic_default_mem_order, /*First=*/0,
9687 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9688 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9689 return nullptr;
9690 }
9691 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9692 LParenLoc, EndLoc);
9693}
9694
Alexey Bataev56dafe82014-06-20 07:16:17 +00009695OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009696 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009697 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009698 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009699 SourceLocation EndLoc) {
9700 OMPClause *Res = nullptr;
9701 switch (Kind) {
9702 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009703 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9704 assert(Argument.size() == NumberOfElements &&
9705 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009706 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009707 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9708 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9709 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9710 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9711 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009712 break;
9713 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009714 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9715 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9716 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9717 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009718 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009719 case OMPC_dist_schedule:
9720 Res = ActOnOpenMPDistScheduleClause(
9721 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9722 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9723 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009724 case OMPC_defaultmap:
9725 enum { Modifier, DefaultmapKind };
9726 Res = ActOnOpenMPDefaultmapClause(
9727 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9728 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009729 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9730 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009731 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009732 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009733 case OMPC_num_threads:
9734 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009735 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009736 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009737 case OMPC_collapse:
9738 case OMPC_default:
9739 case OMPC_proc_bind:
9740 case OMPC_private:
9741 case OMPC_firstprivate:
9742 case OMPC_lastprivate:
9743 case OMPC_shared:
9744 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009745 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009746 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009747 case OMPC_linear:
9748 case OMPC_aligned:
9749 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009750 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009751 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009752 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009753 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009754 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009755 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009756 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009757 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009758 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009759 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009760 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009761 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009762 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009763 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009764 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009765 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009766 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009767 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009768 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009769 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009770 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009771 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009772 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009773 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009774 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009775 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009776 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009777 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009778 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009779 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009780 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009781 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009782 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009783 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009784 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009785 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009786 llvm_unreachable("Clause is not allowed.");
9787 }
9788 return Res;
9789}
9790
Alexey Bataev6402bca2015-12-28 07:25:51 +00009791static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9792 OpenMPScheduleClauseModifier M2,
9793 SourceLocation M1Loc, SourceLocation M2Loc) {
9794 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9795 SmallVector<unsigned, 2> Excluded;
9796 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9797 Excluded.push_back(M2);
9798 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9799 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9800 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9801 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9802 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9803 << getListOfPossibleValues(OMPC_schedule,
9804 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9805 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9806 Excluded)
9807 << getOpenMPClauseName(OMPC_schedule);
9808 return true;
9809 }
9810 return false;
9811}
9812
Alexey Bataev56dafe82014-06-20 07:16:17 +00009813OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009814 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009815 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009816 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9817 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9818 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9819 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9820 return nullptr;
9821 // OpenMP, 2.7.1, Loop Construct, Restrictions
9822 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9823 // but not both.
9824 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9825 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9826 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9827 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9828 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9829 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9830 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9831 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9832 return nullptr;
9833 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009834 if (Kind == OMPC_SCHEDULE_unknown) {
9835 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009836 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9837 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9838 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9839 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9840 Exclude);
9841 } else {
9842 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9843 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009844 }
9845 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9846 << Values << getOpenMPClauseName(OMPC_schedule);
9847 return nullptr;
9848 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009849 // OpenMP, 2.7.1, Loop Construct, Restrictions
9850 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9851 // schedule(guided).
9852 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9853 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9854 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9855 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9856 diag::err_omp_schedule_nonmonotonic_static);
9857 return nullptr;
9858 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009859 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009860 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009861 if (ChunkSize) {
9862 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9863 !ChunkSize->isInstantiationDependent() &&
9864 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009865 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009866 ExprResult Val =
9867 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9868 if (Val.isInvalid())
9869 return nullptr;
9870
9871 ValExpr = Val.get();
9872
9873 // OpenMP [2.7.1, Restrictions]
9874 // chunk_size must be a loop invariant integer expression with a positive
9875 // value.
9876 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009877 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9878 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9879 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009880 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009881 return nullptr;
9882 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009883 } else if (getOpenMPCaptureRegionForClause(
9884 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9885 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009886 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009887 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009888 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009889 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9890 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009891 }
9892 }
9893 }
9894
Alexey Bataev6402bca2015-12-28 07:25:51 +00009895 return new (Context)
9896 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009897 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009898}
9899
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009900OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9901 SourceLocation StartLoc,
9902 SourceLocation EndLoc) {
9903 OMPClause *Res = nullptr;
9904 switch (Kind) {
9905 case OMPC_ordered:
9906 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9907 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009908 case OMPC_nowait:
9909 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9910 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009911 case OMPC_untied:
9912 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9913 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009914 case OMPC_mergeable:
9915 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9916 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009917 case OMPC_read:
9918 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9919 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009920 case OMPC_write:
9921 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9922 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009923 case OMPC_update:
9924 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9925 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009926 case OMPC_capture:
9927 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9928 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009929 case OMPC_seq_cst:
9930 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9931 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009932 case OMPC_threads:
9933 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9934 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009935 case OMPC_simd:
9936 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9937 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009938 case OMPC_nogroup:
9939 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9940 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009941 case OMPC_unified_address:
9942 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9943 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009944 case OMPC_unified_shared_memory:
9945 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9946 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009947 case OMPC_reverse_offload:
9948 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9949 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009950 case OMPC_dynamic_allocators:
9951 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9952 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009953 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009954 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009955 case OMPC_num_threads:
9956 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009957 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009958 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009959 case OMPC_collapse:
9960 case OMPC_schedule:
9961 case OMPC_private:
9962 case OMPC_firstprivate:
9963 case OMPC_lastprivate:
9964 case OMPC_shared:
9965 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009966 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009967 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009968 case OMPC_linear:
9969 case OMPC_aligned:
9970 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009971 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009972 case OMPC_default:
9973 case OMPC_proc_bind:
9974 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009975 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009976 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009977 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009978 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009979 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009980 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009981 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009982 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009983 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009984 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009985 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009986 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009987 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009988 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009989 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009990 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009991 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009992 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009993 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009994 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009995 llvm_unreachable("Clause is not allowed.");
9996 }
9997 return Res;
9998}
9999
Alexey Bataev236070f2014-06-20 11:19:47 +000010000OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10001 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000010002 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000010003 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10004}
10005
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010006OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10007 SourceLocation EndLoc) {
10008 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10009}
10010
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010011OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10012 SourceLocation EndLoc) {
10013 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10014}
10015
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010016OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10017 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010018 return new (Context) OMPReadClause(StartLoc, EndLoc);
10019}
10020
Alexey Bataevdea47612014-07-23 07:46:59 +000010021OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10022 SourceLocation EndLoc) {
10023 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10024}
10025
Alexey Bataev67a4f222014-07-23 10:25:33 +000010026OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10027 SourceLocation EndLoc) {
10028 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10029}
10030
Alexey Bataev459dec02014-07-24 06:46:57 +000010031OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10032 SourceLocation EndLoc) {
10033 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10034}
10035
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010036OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10037 SourceLocation EndLoc) {
10038 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10039}
10040
Alexey Bataev346265e2015-09-25 10:37:12 +000010041OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10042 SourceLocation EndLoc) {
10043 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10044}
10045
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010046OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10047 SourceLocation EndLoc) {
10048 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10049}
10050
Alexey Bataevb825de12015-12-07 10:51:44 +000010051OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10052 SourceLocation EndLoc) {
10053 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10054}
10055
Kelvin Li1408f912018-09-26 04:28:39 +000010056OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10057 SourceLocation EndLoc) {
10058 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10059}
10060
Patrick Lyster4a370b92018-10-01 13:47:43 +000010061OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10062 SourceLocation EndLoc) {
10063 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10064}
10065
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010066OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10067 SourceLocation EndLoc) {
10068 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10069}
10070
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010071OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10072 SourceLocation EndLoc) {
10073 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10074}
10075
Alexey Bataevc5e02582014-06-16 07:08:35 +000010076OMPClause *Sema::ActOnOpenMPVarListClause(
10077 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010078 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10079 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10080 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010081 OpenMPLinearClauseKind LinKind,
10082 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010083 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10084 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10085 SourceLocation StartLoc = Locs.StartLoc;
10086 SourceLocation LParenLoc = Locs.LParenLoc;
10087 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010088 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010089 switch (Kind) {
10090 case OMPC_private:
10091 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10092 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010093 case OMPC_firstprivate:
10094 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10095 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010096 case OMPC_lastprivate:
10097 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10098 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010099 case OMPC_shared:
10100 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10101 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010102 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010103 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010104 EndLoc, ReductionOrMapperIdScopeSpec,
10105 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010106 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010107 case OMPC_task_reduction:
10108 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010109 EndLoc, ReductionOrMapperIdScopeSpec,
10110 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010111 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010112 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010113 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10114 EndLoc, ReductionOrMapperIdScopeSpec,
10115 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010116 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010117 case OMPC_linear:
10118 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010119 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010120 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010121 case OMPC_aligned:
10122 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10123 ColonLoc, EndLoc);
10124 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010125 case OMPC_copyin:
10126 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10127 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010128 case OMPC_copyprivate:
10129 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10130 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010131 case OMPC_flush:
10132 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10133 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010134 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010135 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010136 StartLoc, LParenLoc, EndLoc);
10137 break;
10138 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010139 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10140 ReductionOrMapperIdScopeSpec,
10141 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10142 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010143 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010144 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010145 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10146 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010147 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010148 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010149 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10150 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010151 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010152 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010153 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010154 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010155 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010156 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010157 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010158 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010159 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010160 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010161 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010162 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010163 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010164 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010165 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010166 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010167 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010168 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010169 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010170 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010171 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010172 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010173 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010174 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010175 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010176 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010177 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010178 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010179 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010180 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010181 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010182 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010183 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010184 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010185 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010186 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010187 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010188 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010189 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010190 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010191 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010192 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010193 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010194 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010195 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010196 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010197 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010198 llvm_unreachable("Clause is not allowed.");
10199 }
10200 return Res;
10201}
10202
Alexey Bataev90c228f2016-02-08 09:29:13 +000010203ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010204 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010205 ExprResult Res = BuildDeclRefExpr(
10206 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10207 if (!Res.isUsable())
10208 return ExprError();
10209 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10210 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10211 if (!Res.isUsable())
10212 return ExprError();
10213 }
10214 if (VK != VK_LValue && Res.get()->isGLValue()) {
10215 Res = DefaultLvalueConversion(Res.get());
10216 if (!Res.isUsable())
10217 return ExprError();
10218 }
10219 return Res;
10220}
10221
Alexey Bataev60da77e2016-02-29 05:54:20 +000010222static std::pair<ValueDecl *, bool>
10223getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10224 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010225 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10226 RefExpr->containsUnexpandedParameterPack())
10227 return std::make_pair(nullptr, true);
10228
Alexey Bataevd985eda2016-02-10 11:29:16 +000010229 // OpenMP [3.1, C/C++]
10230 // A list item is a variable name.
10231 // OpenMP [2.9.3.3, Restrictions, p.1]
10232 // A variable that is part of another variable (as an array or
10233 // structure element) cannot appear in a private clause.
10234 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010235 enum {
10236 NoArrayExpr = -1,
10237 ArraySubscript = 0,
10238 OMPArraySection = 1
10239 } IsArrayExpr = NoArrayExpr;
10240 if (AllowArraySection) {
10241 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010242 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010243 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10244 Base = TempASE->getBase()->IgnoreParenImpCasts();
10245 RefExpr = Base;
10246 IsArrayExpr = ArraySubscript;
10247 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010248 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010249 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10250 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10251 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10252 Base = TempASE->getBase()->IgnoreParenImpCasts();
10253 RefExpr = Base;
10254 IsArrayExpr = OMPArraySection;
10255 }
10256 }
10257 ELoc = RefExpr->getExprLoc();
10258 ERange = RefExpr->getSourceRange();
10259 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010260 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10261 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10262 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10263 (S.getCurrentThisType().isNull() || !ME ||
10264 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10265 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010266 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010267 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10268 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010269 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010270 S.Diag(ELoc,
10271 AllowArraySection
10272 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10273 : diag::err_omp_expected_var_name_member_expr)
10274 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10275 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010276 return std::make_pair(nullptr, false);
10277 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010278 return std::make_pair(
10279 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010280}
10281
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010282OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10283 SourceLocation StartLoc,
10284 SourceLocation LParenLoc,
10285 SourceLocation EndLoc) {
10286 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010287 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010288 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010289 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010290 SourceLocation ELoc;
10291 SourceRange ERange;
10292 Expr *SimpleRefExpr = RefExpr;
10293 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010294 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010295 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010296 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010297 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010298 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010299 ValueDecl *D = Res.first;
10300 if (!D)
10301 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010302
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010303 QualType Type = D->getType();
10304 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010305
10306 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10307 // A variable that appears in a private clause must not have an incomplete
10308 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010309 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010310 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010311 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010312
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010313 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10314 // A variable that is privatized must not have a const-qualified type
10315 // unless it is of class type with a mutable member. This restriction does
10316 // not apply to the firstprivate clause.
10317 //
10318 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10319 // A variable that appears in a private clause must not have a
10320 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010321 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010322 continue;
10323
Alexey Bataev758e55e2013-09-06 18:03:48 +000010324 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10325 // in a Construct]
10326 // Variables with the predetermined data-sharing attributes may not be
10327 // listed in data-sharing attributes clauses, except for the cases
10328 // listed below. For these exceptions only, listing a predetermined
10329 // variable in a data-sharing attribute clause is allowed and overrides
10330 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010331 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010332 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010333 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10334 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010335 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010336 continue;
10337 }
10338
Alexey Bataeve3727102018-04-18 15:57:46 +000010339 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010340 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010341 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010342 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010343 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10344 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010345 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010346 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010347 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010348 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010349 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010350 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010351 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010352 continue;
10353 }
10354
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010355 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10356 // A list item cannot appear in both a map clause and a data-sharing
10357 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010358 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010359 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010360 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010361 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010362 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10363 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10364 ConflictKind = WhereFoundClauseKind;
10365 return true;
10366 })) {
10367 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010368 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010369 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010370 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010371 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010372 continue;
10373 }
10374 }
10375
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010376 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10377 // A variable of class type (or array thereof) that appears in a private
10378 // clause requires an accessible, unambiguous default constructor for the
10379 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010380 // Generate helper private variable and initialize it with the default
10381 // value. The address of the original variable is replaced by the address of
10382 // the new private variable in CodeGen. This new variable is not added to
10383 // IdResolver, so the code in the OpenMP region uses original variable for
10384 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010385 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010386 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010387 buildVarDecl(*this, ELoc, Type, D->getName(),
10388 D->hasAttrs() ? &D->getAttrs() : nullptr,
10389 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010390 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010391 if (VDPrivate->isInvalidDecl())
10392 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010393 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010394 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010395
Alexey Bataev90c228f2016-02-08 09:29:13 +000010396 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010397 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010398 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010399 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010400 Vars.push_back((VD || CurContext->isDependentContext())
10401 ? RefExpr->IgnoreParens()
10402 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010403 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010404 }
10405
Alexey Bataeved09d242014-05-28 05:53:51 +000010406 if (Vars.empty())
10407 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010408
Alexey Bataev03b340a2014-10-21 03:16:40 +000010409 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10410 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010411}
10412
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010413namespace {
10414class DiagsUninitializedSeveretyRAII {
10415private:
10416 DiagnosticsEngine &Diags;
10417 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010418 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010419
10420public:
10421 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10422 bool IsIgnored)
10423 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10424 if (!IsIgnored) {
10425 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10426 /*Map*/ diag::Severity::Ignored, Loc);
10427 }
10428 }
10429 ~DiagsUninitializedSeveretyRAII() {
10430 if (!IsIgnored)
10431 Diags.popMappings(SavedLoc);
10432 }
10433};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010434}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010435
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010436OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10437 SourceLocation StartLoc,
10438 SourceLocation LParenLoc,
10439 SourceLocation EndLoc) {
10440 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010441 SmallVector<Expr *, 8> PrivateCopies;
10442 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010443 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010444 bool IsImplicitClause =
10445 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010446 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010447
Alexey Bataeve3727102018-04-18 15:57:46 +000010448 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010449 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010450 SourceLocation ELoc;
10451 SourceRange ERange;
10452 Expr *SimpleRefExpr = RefExpr;
10453 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010454 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010455 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010456 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010457 PrivateCopies.push_back(nullptr);
10458 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010459 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010460 ValueDecl *D = Res.first;
10461 if (!D)
10462 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010463
Alexey Bataev60da77e2016-02-29 05:54:20 +000010464 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010465 QualType Type = D->getType();
10466 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010467
10468 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10469 // A variable that appears in a private clause must not have an incomplete
10470 // type or a reference type.
10471 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010472 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010473 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010474 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010475
10476 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10477 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010478 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010479 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010480 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010481
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010482 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010483 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010484 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010485 DSAStackTy::DSAVarData DVar =
10486 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010487 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010488 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010489 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010490 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10491 // A list item that specifies a given variable may not appear in more
10492 // than one clause on the same directive, except that a variable may be
10493 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010494 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10495 // A list item may appear in a firstprivate or lastprivate clause but not
10496 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010497 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010498 (isOpenMPDistributeDirective(CurrDir) ||
10499 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010500 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010501 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010502 << getOpenMPClauseName(DVar.CKind)
10503 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010504 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010505 continue;
10506 }
10507
10508 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10509 // in a Construct]
10510 // Variables with the predetermined data-sharing attributes may not be
10511 // listed in data-sharing attributes clauses, except for the cases
10512 // listed below. For these exceptions only, listing a predetermined
10513 // variable in a data-sharing attribute clause is allowed and overrides
10514 // the variable's predetermined data-sharing attributes.
10515 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10516 // in a Construct, C/C++, p.2]
10517 // Variables with const-qualified type having no mutable member may be
10518 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010519 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010520 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10521 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010522 << getOpenMPClauseName(DVar.CKind)
10523 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010524 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010525 continue;
10526 }
10527
10528 // OpenMP [2.9.3.4, Restrictions, p.2]
10529 // A list item that is private within a parallel region must not appear
10530 // in a firstprivate clause on a worksharing construct if any of the
10531 // worksharing regions arising from the worksharing construct ever bind
10532 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010533 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10534 // A list item that is private within a teams region must not appear in a
10535 // firstprivate clause on a distribute construct if any of the distribute
10536 // regions arising from the distribute construct ever bind to any of the
10537 // teams regions arising from the teams construct.
10538 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10539 // A list item that appears in a reduction clause of a teams construct
10540 // must not appear in a firstprivate clause on a distribute construct if
10541 // any of the distribute regions arising from the distribute construct
10542 // ever bind to any of the teams regions arising from the teams construct.
10543 if ((isOpenMPWorksharingDirective(CurrDir) ||
10544 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010545 !isOpenMPParallelDirective(CurrDir) &&
10546 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010547 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010548 if (DVar.CKind != OMPC_shared &&
10549 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010550 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010551 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010552 Diag(ELoc, diag::err_omp_required_access)
10553 << getOpenMPClauseName(OMPC_firstprivate)
10554 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010555 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010556 continue;
10557 }
10558 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010559 // OpenMP [2.9.3.4, Restrictions, p.3]
10560 // A list item that appears in a reduction clause of a parallel construct
10561 // must not appear in a firstprivate clause on a worksharing or task
10562 // construct if any of the worksharing or task regions arising from the
10563 // worksharing or task construct ever bind to any of the parallel regions
10564 // arising from the parallel construct.
10565 // OpenMP [2.9.3.4, Restrictions, p.4]
10566 // A list item that appears in a reduction clause in worksharing
10567 // construct must not appear in a firstprivate clause in a task construct
10568 // encountered during execution of any of the worksharing regions arising
10569 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010570 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010571 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010572 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10573 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010574 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010575 isOpenMPWorksharingDirective(K) ||
10576 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010577 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010578 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010579 if (DVar.CKind == OMPC_reduction &&
10580 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010581 isOpenMPWorksharingDirective(DVar.DKind) ||
10582 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010583 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10584 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010585 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010586 continue;
10587 }
10588 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010589
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010590 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10591 // A list item cannot appear in both a map clause and a data-sharing
10592 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010593 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010594 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010595 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010596 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010597 [&ConflictKind](
10598 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10599 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010600 ConflictKind = WhereFoundClauseKind;
10601 return true;
10602 })) {
10603 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010604 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010605 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010606 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010607 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010608 continue;
10609 }
10610 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010611 }
10612
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010613 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010614 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010615 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010616 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10617 << getOpenMPClauseName(OMPC_firstprivate) << Type
10618 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10619 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010620 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010621 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010622 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010623 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010624 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010625 continue;
10626 }
10627
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010628 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010629 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010630 buildVarDecl(*this, ELoc, Type, D->getName(),
10631 D->hasAttrs() ? &D->getAttrs() : nullptr,
10632 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010633 // Generate helper private variable and initialize it with the value of the
10634 // original variable. The address of the original variable is replaced by
10635 // the address of the new private variable in the CodeGen. This new variable
10636 // is not added to IdResolver, so the code in the OpenMP region uses
10637 // original variable for proper diagnostics and variable capturing.
10638 Expr *VDInitRefExpr = nullptr;
10639 // For arrays generate initializer for single element and replace it by the
10640 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010641 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010642 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010643 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010644 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010645 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010646 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010647 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10648 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010649 InitializedEntity Entity =
10650 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010651 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10652
10653 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10654 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10655 if (Result.isInvalid())
10656 VDPrivate->setInvalidDecl();
10657 else
10658 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010659 // Remove temp variable declaration.
10660 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010661 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010662 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10663 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010664 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10665 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010666 AddInitializerToDecl(VDPrivate,
10667 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010668 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010669 }
10670 if (VDPrivate->isInvalidDecl()) {
10671 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010672 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010673 diag::note_omp_task_predetermined_firstprivate_here);
10674 }
10675 continue;
10676 }
10677 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010678 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010679 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10680 RefExpr->getExprLoc());
10681 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010682 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010683 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010684 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010685 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010686 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010687 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010688 ExprCaptures.push_back(Ref->getDecl());
10689 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010690 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010691 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010692 Vars.push_back((VD || CurContext->isDependentContext())
10693 ? RefExpr->IgnoreParens()
10694 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010695 PrivateCopies.push_back(VDPrivateRefExpr);
10696 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010697 }
10698
Alexey Bataeved09d242014-05-28 05:53:51 +000010699 if (Vars.empty())
10700 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010701
10702 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010703 Vars, PrivateCopies, Inits,
10704 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010705}
10706
Alexander Musman1bb328c2014-06-04 13:06:39 +000010707OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10708 SourceLocation StartLoc,
10709 SourceLocation LParenLoc,
10710 SourceLocation EndLoc) {
10711 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010712 SmallVector<Expr *, 8> SrcExprs;
10713 SmallVector<Expr *, 8> DstExprs;
10714 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010715 SmallVector<Decl *, 4> ExprCaptures;
10716 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010717 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010718 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010719 SourceLocation ELoc;
10720 SourceRange ERange;
10721 Expr *SimpleRefExpr = RefExpr;
10722 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010723 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010724 // It will be analyzed later.
10725 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010726 SrcExprs.push_back(nullptr);
10727 DstExprs.push_back(nullptr);
10728 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010729 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010730 ValueDecl *D = Res.first;
10731 if (!D)
10732 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010733
Alexey Bataev74caaf22016-02-20 04:09:36 +000010734 QualType Type = D->getType();
10735 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010736
10737 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10738 // A variable that appears in a lastprivate clause must not have an
10739 // incomplete type or a reference type.
10740 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010741 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010742 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010743 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010744
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010745 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10746 // A variable that is privatized must not have a const-qualified type
10747 // unless it is of class type with a mutable member. This restriction does
10748 // not apply to the firstprivate clause.
10749 //
10750 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10751 // A variable that appears in a lastprivate clause must not have a
10752 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010753 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010754 continue;
10755
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010756 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010757 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10758 // in a Construct]
10759 // Variables with the predetermined data-sharing attributes may not be
10760 // listed in data-sharing attributes clauses, except for the cases
10761 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010762 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10763 // A list item may appear in a firstprivate or lastprivate clause but not
10764 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010765 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010766 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010767 (isOpenMPDistributeDirective(CurrDir) ||
10768 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010769 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10770 Diag(ELoc, diag::err_omp_wrong_dsa)
10771 << getOpenMPClauseName(DVar.CKind)
10772 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010773 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010774 continue;
10775 }
10776
Alexey Bataevf29276e2014-06-18 04:14:57 +000010777 // OpenMP [2.14.3.5, Restrictions, p.2]
10778 // A list item that is private within a parallel region, or that appears in
10779 // the reduction clause of a parallel construct, must not appear in a
10780 // lastprivate clause on a worksharing construct if any of the corresponding
10781 // worksharing regions ever binds to any of the corresponding parallel
10782 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010783 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010784 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010785 !isOpenMPParallelDirective(CurrDir) &&
10786 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010787 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010788 if (DVar.CKind != OMPC_shared) {
10789 Diag(ELoc, diag::err_omp_required_access)
10790 << getOpenMPClauseName(OMPC_lastprivate)
10791 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010792 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010793 continue;
10794 }
10795 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010796
Alexander Musman1bb328c2014-06-04 13:06:39 +000010797 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010798 // A variable of class type (or array thereof) that appears in a
10799 // lastprivate clause requires an accessible, unambiguous default
10800 // constructor for the class type, unless the list item is also specified
10801 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010802 // A variable of class type (or array thereof) that appears in a
10803 // lastprivate clause requires an accessible, unambiguous copy assignment
10804 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010805 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010806 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10807 Type.getUnqualifiedType(), ".lastprivate.src",
10808 D->hasAttrs() ? &D->getAttrs() : nullptr);
10809 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010810 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010811 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010812 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010813 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010814 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010815 // For arrays generate assignment operation for single element and replace
10816 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010817 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10818 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010819 if (AssignmentOp.isInvalid())
10820 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010821 AssignmentOp =
10822 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010823 if (AssignmentOp.isInvalid())
10824 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010825
Alexey Bataev74caaf22016-02-20 04:09:36 +000010826 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010827 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010828 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010829 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010830 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010831 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010832 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010833 ExprCaptures.push_back(Ref->getDecl());
10834 }
10835 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010836 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010837 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010838 ExprResult RefRes = DefaultLvalueConversion(Ref);
10839 if (!RefRes.isUsable())
10840 continue;
10841 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010842 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10843 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010844 if (!PostUpdateRes.isUsable())
10845 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010846 ExprPostUpdates.push_back(
10847 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010848 }
10849 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010850 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010851 Vars.push_back((VD || CurContext->isDependentContext())
10852 ? RefExpr->IgnoreParens()
10853 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010854 SrcExprs.push_back(PseudoSrcExpr);
10855 DstExprs.push_back(PseudoDstExpr);
10856 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010857 }
10858
10859 if (Vars.empty())
10860 return nullptr;
10861
10862 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010863 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010864 buildPreInits(Context, ExprCaptures),
10865 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010866}
10867
Alexey Bataev758e55e2013-09-06 18:03:48 +000010868OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10869 SourceLocation StartLoc,
10870 SourceLocation LParenLoc,
10871 SourceLocation EndLoc) {
10872 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010873 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010874 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010875 SourceLocation ELoc;
10876 SourceRange ERange;
10877 Expr *SimpleRefExpr = RefExpr;
10878 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010879 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010880 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010881 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010882 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010883 ValueDecl *D = Res.first;
10884 if (!D)
10885 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010886
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010887 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010888 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10889 // in a Construct]
10890 // Variables with the predetermined data-sharing attributes may not be
10891 // listed in data-sharing attributes clauses, except for the cases
10892 // listed below. For these exceptions only, listing a predetermined
10893 // variable in a data-sharing attribute clause is allowed and overrides
10894 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010895 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010896 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10897 DVar.RefExpr) {
10898 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10899 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010900 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010901 continue;
10902 }
10903
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010904 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010905 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010906 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010907 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010908 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10909 ? RefExpr->IgnoreParens()
10910 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010911 }
10912
Alexey Bataeved09d242014-05-28 05:53:51 +000010913 if (Vars.empty())
10914 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010915
10916 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10917}
10918
Alexey Bataevc5e02582014-06-16 07:08:35 +000010919namespace {
10920class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10921 DSAStackTy *Stack;
10922
10923public:
10924 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010925 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10926 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010927 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10928 return false;
10929 if (DVar.CKind != OMPC_unknown)
10930 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010931 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010932 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010933 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010934 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010935 }
10936 return false;
10937 }
10938 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010939 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010940 if (Child && Visit(Child))
10941 return true;
10942 }
10943 return false;
10944 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010945 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010946};
Alexey Bataev23b69422014-06-18 07:08:49 +000010947} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010948
Alexey Bataev60da77e2016-02-29 05:54:20 +000010949namespace {
10950// Transform MemberExpression for specified FieldDecl of current class to
10951// DeclRefExpr to specified OMPCapturedExprDecl.
10952class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10953 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010954 ValueDecl *Field = nullptr;
10955 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010956
10957public:
10958 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10959 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10960
10961 ExprResult TransformMemberExpr(MemberExpr *E) {
10962 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10963 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010964 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010965 return CapturedExpr;
10966 }
10967 return BaseTransform::TransformMemberExpr(E);
10968 }
10969 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10970};
10971} // namespace
10972
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010973template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010974static T filterLookupForUDReductionAndMapper(
10975 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010976 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010977 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010978 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010979 return Res;
10980 }
10981 }
10982 return T();
10983}
10984
Alexey Bataev43b90b72018-09-12 16:31:59 +000010985static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10986 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10987
10988 for (auto RD : D->redecls()) {
10989 // Don't bother with extra checks if we already know this one isn't visible.
10990 if (RD == D)
10991 continue;
10992
10993 auto ND = cast<NamedDecl>(RD);
10994 if (LookupResult::isVisible(SemaRef, ND))
10995 return ND;
10996 }
10997
10998 return nullptr;
10999}
11000
11001static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000011002argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000011003 SourceLocation Loc, QualType Ty,
11004 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11005 // Find all of the associated namespaces and classes based on the
11006 // arguments we have.
11007 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11008 Sema::AssociatedClassSet AssociatedClasses;
11009 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11010 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11011 AssociatedClasses);
11012
11013 // C++ [basic.lookup.argdep]p3:
11014 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11015 // and let Y be the lookup set produced by argument dependent
11016 // lookup (defined as follows). If X contains [...] then Y is
11017 // empty. Otherwise Y is the set of declarations found in the
11018 // namespaces associated with the argument types as described
11019 // below. The set of declarations found by the lookup of the name
11020 // is the union of X and Y.
11021 //
11022 // Here, we compute Y and add its members to the overloaded
11023 // candidate set.
11024 for (auto *NS : AssociatedNamespaces) {
11025 // When considering an associated namespace, the lookup is the
11026 // same as the lookup performed when the associated namespace is
11027 // used as a qualifier (3.4.3.2) except that:
11028 //
11029 // -- Any using-directives in the associated namespace are
11030 // ignored.
11031 //
11032 // -- Any namespace-scope friend functions declared in
11033 // associated classes are visible within their respective
11034 // namespaces even if they are not visible during an ordinary
11035 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011036 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011037 for (auto *D : R) {
11038 auto *Underlying = D;
11039 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11040 Underlying = USD->getTargetDecl();
11041
Michael Kruse4304e9d2019-02-19 16:38:20 +000011042 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11043 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011044 continue;
11045
11046 if (!SemaRef.isVisible(D)) {
11047 D = findAcceptableDecl(SemaRef, D);
11048 if (!D)
11049 continue;
11050 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11051 Underlying = USD->getTargetDecl();
11052 }
11053 Lookups.emplace_back();
11054 Lookups.back().addDecl(Underlying);
11055 }
11056 }
11057}
11058
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011059static ExprResult
11060buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11061 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11062 const DeclarationNameInfo &ReductionId, QualType Ty,
11063 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11064 if (ReductionIdScopeSpec.isInvalid())
11065 return ExprError();
11066 SmallVector<UnresolvedSet<8>, 4> Lookups;
11067 if (S) {
11068 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11069 Lookup.suppressDiagnostics();
11070 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011071 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011072 do {
11073 S = S->getParent();
11074 } while (S && !S->isDeclScope(D));
11075 if (S)
11076 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011077 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011078 Lookups.back().append(Lookup.begin(), Lookup.end());
11079 Lookup.clear();
11080 }
11081 } else if (auto *ULE =
11082 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11083 Lookups.push_back(UnresolvedSet<8>());
11084 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011085 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011086 if (D == PrevD)
11087 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011088 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011089 Lookups.back().addDecl(DRD);
11090 PrevD = D;
11091 }
11092 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011093 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11094 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011095 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011096 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011097 return !D->isInvalidDecl() &&
11098 (D->getType()->isDependentType() ||
11099 D->getType()->isInstantiationDependentType() ||
11100 D->getType()->containsUnexpandedParameterPack());
11101 })) {
11102 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011103 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011104 if (Set.empty())
11105 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011106 ResSet.append(Set.begin(), Set.end());
11107 // The last item marks the end of all declarations at the specified scope.
11108 ResSet.addDecl(Set[Set.size() - 1]);
11109 }
11110 return UnresolvedLookupExpr::Create(
11111 SemaRef.Context, /*NamingClass=*/nullptr,
11112 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11113 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11114 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011115 // Lookup inside the classes.
11116 // C++ [over.match.oper]p3:
11117 // For a unary operator @ with an operand of a type whose
11118 // cv-unqualified version is T1, and for a binary operator @ with
11119 // a left operand of a type whose cv-unqualified version is T1 and
11120 // a right operand of a type whose cv-unqualified version is T2,
11121 // three sets of candidate functions, designated member
11122 // candidates, non-member candidates and built-in candidates, are
11123 // constructed as follows:
11124 // -- If T1 is a complete class type or a class currently being
11125 // defined, the set of member candidates is the result of the
11126 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11127 // the set of member candidates is empty.
11128 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11129 Lookup.suppressDiagnostics();
11130 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11131 // Complete the type if it can be completed.
11132 // If the type is neither complete nor being defined, bail out now.
11133 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11134 TyRec->getDecl()->getDefinition()) {
11135 Lookup.clear();
11136 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11137 if (Lookup.empty()) {
11138 Lookups.emplace_back();
11139 Lookups.back().append(Lookup.begin(), Lookup.end());
11140 }
11141 }
11142 }
11143 // Perform ADL.
Alexey Bataev74a04e82019-03-13 19:31:34 +000011144 if (SemaRef.getLangOpts().CPlusPlus) {
11145 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11146 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11147 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11148 if (!D->isInvalidDecl() &&
11149 SemaRef.Context.hasSameType(D->getType(), Ty))
11150 return D;
11151 return nullptr;
11152 }))
11153 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11154 VK_LValue, Loc);
11155 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11156 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11157 if (!D->isInvalidDecl() &&
11158 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11159 !Ty.isMoreQualifiedThan(D->getType()))
11160 return D;
11161 return nullptr;
11162 })) {
11163 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11164 /*DetectVirtual=*/false);
11165 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11166 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11167 VD->getType().getUnqualifiedType()))) {
11168 if (SemaRef.CheckBaseClassAccess(
11169 Loc, VD->getType(), Ty, Paths.front(),
11170 /*DiagID=*/0) != Sema::AR_inaccessible) {
11171 SemaRef.BuildBasePathArray(Paths, BasePath);
11172 return SemaRef.BuildDeclRefExpr(
11173 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11174 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011175 }
11176 }
11177 }
11178 }
11179 if (ReductionIdScopeSpec.isSet()) {
11180 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11181 return ExprError();
11182 }
11183 return ExprEmpty();
11184}
11185
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011186namespace {
11187/// Data for the reduction-based clauses.
11188struct ReductionData {
11189 /// List of original reduction items.
11190 SmallVector<Expr *, 8> Vars;
11191 /// List of private copies of the reduction items.
11192 SmallVector<Expr *, 8> Privates;
11193 /// LHS expressions for the reduction_op expressions.
11194 SmallVector<Expr *, 8> LHSs;
11195 /// RHS expressions for the reduction_op expressions.
11196 SmallVector<Expr *, 8> RHSs;
11197 /// Reduction operation expression.
11198 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011199 /// Taskgroup descriptors for the corresponding reduction items in
11200 /// in_reduction clauses.
11201 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011202 /// List of captures for clause.
11203 SmallVector<Decl *, 4> ExprCaptures;
11204 /// List of postupdate expressions.
11205 SmallVector<Expr *, 4> ExprPostUpdates;
11206 ReductionData() = delete;
11207 /// Reserves required memory for the reduction data.
11208 ReductionData(unsigned Size) {
11209 Vars.reserve(Size);
11210 Privates.reserve(Size);
11211 LHSs.reserve(Size);
11212 RHSs.reserve(Size);
11213 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011214 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011215 ExprCaptures.reserve(Size);
11216 ExprPostUpdates.reserve(Size);
11217 }
11218 /// Stores reduction item and reduction operation only (required for dependent
11219 /// reduction item).
11220 void push(Expr *Item, Expr *ReductionOp) {
11221 Vars.emplace_back(Item);
11222 Privates.emplace_back(nullptr);
11223 LHSs.emplace_back(nullptr);
11224 RHSs.emplace_back(nullptr);
11225 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011226 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011227 }
11228 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011229 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11230 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011231 Vars.emplace_back(Item);
11232 Privates.emplace_back(Private);
11233 LHSs.emplace_back(LHS);
11234 RHSs.emplace_back(RHS);
11235 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011236 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011237 }
11238};
11239} // namespace
11240
Alexey Bataeve3727102018-04-18 15:57:46 +000011241static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011242 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11243 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11244 const Expr *Length = OASE->getLength();
11245 if (Length == nullptr) {
11246 // For array sections of the form [1:] or [:], we would need to analyze
11247 // the lower bound...
11248 if (OASE->getColonLoc().isValid())
11249 return false;
11250
11251 // This is an array subscript which has implicit length 1!
11252 SingleElement = true;
11253 ArraySizes.push_back(llvm::APSInt::get(1));
11254 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011255 Expr::EvalResult Result;
11256 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011257 return false;
11258
Fangrui Song407659a2018-11-30 23:41:18 +000011259 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011260 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11261 ArraySizes.push_back(ConstantLengthValue);
11262 }
11263
11264 // Get the base of this array section and walk up from there.
11265 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11266
11267 // We require length = 1 for all array sections except the right-most to
11268 // guarantee that the memory region is contiguous and has no holes in it.
11269 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11270 Length = TempOASE->getLength();
11271 if (Length == nullptr) {
11272 // For array sections of the form [1:] or [:], we would need to analyze
11273 // the lower bound...
11274 if (OASE->getColonLoc().isValid())
11275 return false;
11276
11277 // This is an array subscript which has implicit length 1!
11278 ArraySizes.push_back(llvm::APSInt::get(1));
11279 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011280 Expr::EvalResult Result;
11281 if (!Length->EvaluateAsInt(Result, Context))
11282 return false;
11283
11284 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11285 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011286 return false;
11287
11288 ArraySizes.push_back(ConstantLengthValue);
11289 }
11290 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11291 }
11292
11293 // If we have a single element, we don't need to add the implicit lengths.
11294 if (!SingleElement) {
11295 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11296 // Has implicit length 1!
11297 ArraySizes.push_back(llvm::APSInt::get(1));
11298 Base = TempASE->getBase()->IgnoreParenImpCasts();
11299 }
11300 }
11301
11302 // This array section can be privatized as a single value or as a constant
11303 // sized array.
11304 return true;
11305}
11306
Alexey Bataeve3727102018-04-18 15:57:46 +000011307static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011308 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11309 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11310 SourceLocation ColonLoc, SourceLocation EndLoc,
11311 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011312 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011313 DeclarationName DN = ReductionId.getName();
11314 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011315 BinaryOperatorKind BOK = BO_Comma;
11316
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011317 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011318 // OpenMP [2.14.3.6, reduction clause]
11319 // C
11320 // reduction-identifier is either an identifier or one of the following
11321 // operators: +, -, *, &, |, ^, && and ||
11322 // C++
11323 // reduction-identifier is either an id-expression or one of the following
11324 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011325 switch (OOK) {
11326 case OO_Plus:
11327 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011328 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011329 break;
11330 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011331 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011332 break;
11333 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011334 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011335 break;
11336 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011337 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011338 break;
11339 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011340 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011341 break;
11342 case OO_AmpAmp:
11343 BOK = BO_LAnd;
11344 break;
11345 case OO_PipePipe:
11346 BOK = BO_LOr;
11347 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011348 case OO_New:
11349 case OO_Delete:
11350 case OO_Array_New:
11351 case OO_Array_Delete:
11352 case OO_Slash:
11353 case OO_Percent:
11354 case OO_Tilde:
11355 case OO_Exclaim:
11356 case OO_Equal:
11357 case OO_Less:
11358 case OO_Greater:
11359 case OO_LessEqual:
11360 case OO_GreaterEqual:
11361 case OO_PlusEqual:
11362 case OO_MinusEqual:
11363 case OO_StarEqual:
11364 case OO_SlashEqual:
11365 case OO_PercentEqual:
11366 case OO_CaretEqual:
11367 case OO_AmpEqual:
11368 case OO_PipeEqual:
11369 case OO_LessLess:
11370 case OO_GreaterGreater:
11371 case OO_LessLessEqual:
11372 case OO_GreaterGreaterEqual:
11373 case OO_EqualEqual:
11374 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011375 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011376 case OO_PlusPlus:
11377 case OO_MinusMinus:
11378 case OO_Comma:
11379 case OO_ArrowStar:
11380 case OO_Arrow:
11381 case OO_Call:
11382 case OO_Subscript:
11383 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011384 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011385 case NUM_OVERLOADED_OPERATORS:
11386 llvm_unreachable("Unexpected reduction identifier");
11387 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011388 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011389 if (II->isStr("max"))
11390 BOK = BO_GT;
11391 else if (II->isStr("min"))
11392 BOK = BO_LT;
11393 }
11394 break;
11395 }
11396 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011397 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011398 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011399 else
11400 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011401 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011402
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011403 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11404 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011405 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011406 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011407 // OpenMP [2.1, C/C++]
11408 // A list item is a variable or array section, subject to the restrictions
11409 // specified in Section 2.4 on page 42 and in each of the sections
11410 // describing clauses and directives for which a list appears.
11411 // OpenMP [2.14.3.3, Restrictions, p.1]
11412 // A variable that is part of another variable (as an array or
11413 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011414 if (!FirstIter && IR != ER)
11415 ++IR;
11416 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011417 SourceLocation ELoc;
11418 SourceRange ERange;
11419 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011420 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011421 /*AllowArraySection=*/true);
11422 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011423 // Try to find 'declare reduction' corresponding construct before using
11424 // builtin/overloaded operators.
11425 QualType Type = Context.DependentTy;
11426 CXXCastPath BasePath;
11427 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011428 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011429 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011430 Expr *ReductionOp = nullptr;
11431 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011432 (DeclareReductionRef.isUnset() ||
11433 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011434 ReductionOp = DeclareReductionRef.get();
11435 // It will be analyzed later.
11436 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011437 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011438 ValueDecl *D = Res.first;
11439 if (!D)
11440 continue;
11441
Alexey Bataev88202be2017-07-27 13:20:36 +000011442 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011443 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011444 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11445 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011446 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011447 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011448 } else if (OASE) {
11449 QualType BaseType =
11450 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11451 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011452 Type = ATy->getElementType();
11453 else
11454 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011455 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011456 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011457 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011458 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011459 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011460
Alexey Bataevc5e02582014-06-16 07:08:35 +000011461 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11462 // A variable that appears in a private clause must not have an incomplete
11463 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011464 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011465 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011466 continue;
11467 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011468 // A list item that appears in a reduction clause must not be
11469 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011470 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11471 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011472 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011473
11474 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011475 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11476 // If a list-item is a reference type then it must bind to the same object
11477 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011478 if (!ASE && !OASE) {
11479 if (VD) {
11480 VarDecl *VDDef = VD->getDefinition();
11481 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11482 DSARefChecker Check(Stack);
11483 if (Check.Visit(VDDef->getInit())) {
11484 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11485 << getOpenMPClauseName(ClauseKind) << ERange;
11486 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11487 continue;
11488 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011489 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011490 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011491
Alexey Bataevbc529672018-09-28 19:33:14 +000011492 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11493 // in a Construct]
11494 // Variables with the predetermined data-sharing attributes may not be
11495 // listed in data-sharing attributes clauses, except for the cases
11496 // listed below. For these exceptions only, listing a predetermined
11497 // variable in a data-sharing attribute clause is allowed and overrides
11498 // the variable's predetermined data-sharing attributes.
11499 // OpenMP [2.14.3.6, Restrictions, p.3]
11500 // Any number of reduction clauses can be specified on the directive,
11501 // but a list item can appear only once in the reduction clauses for that
11502 // directive.
11503 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11504 if (DVar.CKind == OMPC_reduction) {
11505 S.Diag(ELoc, diag::err_omp_once_referenced)
11506 << getOpenMPClauseName(ClauseKind);
11507 if (DVar.RefExpr)
11508 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11509 continue;
11510 }
11511 if (DVar.CKind != OMPC_unknown) {
11512 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11513 << getOpenMPClauseName(DVar.CKind)
11514 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011515 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011516 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011517 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011518
11519 // OpenMP [2.14.3.6, Restrictions, p.1]
11520 // A list item that appears in a reduction clause of a worksharing
11521 // construct must be shared in the parallel regions to which any of the
11522 // worksharing regions arising from the worksharing construct bind.
11523 if (isOpenMPWorksharingDirective(CurrDir) &&
11524 !isOpenMPParallelDirective(CurrDir) &&
11525 !isOpenMPTeamsDirective(CurrDir)) {
11526 DVar = Stack->getImplicitDSA(D, true);
11527 if (DVar.CKind != OMPC_shared) {
11528 S.Diag(ELoc, diag::err_omp_required_access)
11529 << getOpenMPClauseName(OMPC_reduction)
11530 << getOpenMPClauseName(OMPC_shared);
11531 reportOriginalDsa(S, Stack, D, DVar);
11532 continue;
11533 }
11534 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011535 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011536
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011537 // Try to find 'declare reduction' corresponding construct before using
11538 // builtin/overloaded operators.
11539 CXXCastPath BasePath;
11540 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011541 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011542 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11543 if (DeclareReductionRef.isInvalid())
11544 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011545 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011546 (DeclareReductionRef.isUnset() ||
11547 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011548 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011549 continue;
11550 }
11551 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11552 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011553 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011554 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011555 << Type << ReductionIdRange;
11556 continue;
11557 }
11558
11559 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11560 // The type of a list item that appears in a reduction clause must be valid
11561 // for the reduction-identifier. For a max or min reduction in C, the type
11562 // of the list item must be an allowed arithmetic data type: char, int,
11563 // float, double, or _Bool, possibly modified with long, short, signed, or
11564 // unsigned. For a max or min reduction in C++, the type of the list item
11565 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11566 // double, or bool, possibly modified with long, short, signed, or unsigned.
11567 if (DeclareReductionRef.isUnset()) {
11568 if ((BOK == BO_GT || BOK == BO_LT) &&
11569 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011570 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11571 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011572 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011573 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011574 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11575 VarDecl::DeclarationOnly;
11576 S.Diag(D->getLocation(),
11577 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011578 << D;
11579 }
11580 continue;
11581 }
11582 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011583 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011584 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11585 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011586 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011587 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11588 VarDecl::DeclarationOnly;
11589 S.Diag(D->getLocation(),
11590 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011591 << D;
11592 }
11593 continue;
11594 }
11595 }
11596
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011597 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011598 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11599 D->hasAttrs() ? &D->getAttrs() : nullptr);
11600 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11601 D->hasAttrs() ? &D->getAttrs() : nullptr);
11602 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011603
11604 // Try if we can determine constant lengths for all array sections and avoid
11605 // the VLA.
11606 bool ConstantLengthOASE = false;
11607 if (OASE) {
11608 bool SingleElement;
11609 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011610 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011611 Context, OASE, SingleElement, ArraySizes);
11612
11613 // If we don't have a single element, we must emit a constant array type.
11614 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011615 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011616 PrivateTy = Context.getConstantArrayType(
11617 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011618 }
11619 }
11620
11621 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011622 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011623 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011624 if (!Context.getTargetInfo().isVLASupported() &&
11625 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11626 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11627 S.Diag(ELoc, diag::note_vla_unsupported);
11628 continue;
11629 }
David Majnemer9d168222016-08-05 17:44:54 +000011630 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011631 // Create pseudo array type for private copy. The size for this array will
11632 // be generated during codegen.
11633 // For array subscripts or single variables Private Ty is the same as Type
11634 // (type of the variable or single array element).
11635 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011636 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011637 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011638 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011639 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011640 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011641 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011642 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011643 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011644 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011645 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11646 D->hasAttrs() ? &D->getAttrs() : nullptr,
11647 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011648 // Add initializer for private variable.
11649 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011650 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11651 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011652 if (DeclareReductionRef.isUsable()) {
11653 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11654 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11655 if (DRD->getInitializer()) {
11656 Init = DRDRef;
11657 RHSVD->setInit(DRDRef);
11658 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011659 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011660 } else {
11661 switch (BOK) {
11662 case BO_Add:
11663 case BO_Xor:
11664 case BO_Or:
11665 case BO_LOr:
11666 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11667 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011668 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011669 break;
11670 case BO_Mul:
11671 case BO_LAnd:
11672 if (Type->isScalarType() || Type->isAnyComplexType()) {
11673 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011674 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011675 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011676 break;
11677 case BO_And: {
11678 // '&' reduction op - initializer is '~0'.
11679 QualType OrigType = Type;
11680 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11681 Type = ComplexTy->getElementType();
11682 if (Type->isRealFloatingType()) {
11683 llvm::APFloat InitValue =
11684 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11685 /*isIEEE=*/true);
11686 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11687 Type, ELoc);
11688 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011689 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011690 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11691 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11692 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11693 }
11694 if (Init && OrigType->isAnyComplexType()) {
11695 // Init = 0xFFFF + 0xFFFFi;
11696 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011697 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011698 }
11699 Type = OrigType;
11700 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011701 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011702 case BO_LT:
11703 case BO_GT: {
11704 // 'min' reduction op - initializer is 'Largest representable number in
11705 // the reduction list item type'.
11706 // 'max' reduction op - initializer is 'Least representable number in
11707 // the reduction list item type'.
11708 if (Type->isIntegerType() || Type->isPointerType()) {
11709 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011710 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011711 QualType IntTy =
11712 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11713 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011714 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11715 : llvm::APInt::getMinValue(Size)
11716 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11717 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011718 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11719 if (Type->isPointerType()) {
11720 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011721 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011722 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011723 if (CastExpr.isInvalid())
11724 continue;
11725 Init = CastExpr.get();
11726 }
11727 } else if (Type->isRealFloatingType()) {
11728 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11729 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11730 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11731 Type, ELoc);
11732 }
11733 break;
11734 }
11735 case BO_PtrMemD:
11736 case BO_PtrMemI:
11737 case BO_MulAssign:
11738 case BO_Div:
11739 case BO_Rem:
11740 case BO_Sub:
11741 case BO_Shl:
11742 case BO_Shr:
11743 case BO_LE:
11744 case BO_GE:
11745 case BO_EQ:
11746 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011747 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011748 case BO_AndAssign:
11749 case BO_XorAssign:
11750 case BO_OrAssign:
11751 case BO_Assign:
11752 case BO_AddAssign:
11753 case BO_SubAssign:
11754 case BO_DivAssign:
11755 case BO_RemAssign:
11756 case BO_ShlAssign:
11757 case BO_ShrAssign:
11758 case BO_Comma:
11759 llvm_unreachable("Unexpected reduction operation");
11760 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011761 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011762 if (Init && DeclareReductionRef.isUnset())
11763 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11764 else if (!Init)
11765 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011766 if (RHSVD->isInvalidDecl())
11767 continue;
11768 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011769 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11770 << Type << ReductionIdRange;
11771 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11772 VarDecl::DeclarationOnly;
11773 S.Diag(D->getLocation(),
11774 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011775 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011776 continue;
11777 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011778 // Store initializer for single element in private copy. Will be used during
11779 // codegen.
11780 PrivateVD->setInit(RHSVD->getInit());
11781 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011782 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011783 ExprResult ReductionOp;
11784 if (DeclareReductionRef.isUsable()) {
11785 QualType RedTy = DeclareReductionRef.get()->getType();
11786 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011787 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11788 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011789 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011790 LHS = S.DefaultLvalueConversion(LHS.get());
11791 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011792 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11793 CK_UncheckedDerivedToBase, LHS.get(),
11794 &BasePath, LHS.get()->getValueKind());
11795 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11796 CK_UncheckedDerivedToBase, RHS.get(),
11797 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011798 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011799 FunctionProtoType::ExtProtoInfo EPI;
11800 QualType Params[] = {PtrRedTy, PtrRedTy};
11801 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11802 auto *OVE = new (Context) OpaqueValueExpr(
11803 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011804 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011805 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011806 ReductionOp =
11807 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011808 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011809 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011810 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011811 if (ReductionOp.isUsable()) {
11812 if (BOK != BO_LT && BOK != BO_GT) {
11813 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011814 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011815 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011816 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011817 auto *ConditionalOp = new (Context)
11818 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11819 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011820 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011821 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011822 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011823 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011824 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011825 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11826 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011827 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011828 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011829 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011830 }
11831
Alexey Bataevfa312f32017-07-21 18:48:21 +000011832 // OpenMP [2.15.4.6, Restrictions, p.2]
11833 // A list item that appears in an in_reduction clause of a task construct
11834 // must appear in a task_reduction clause of a construct associated with a
11835 // taskgroup region that includes the participating task in its taskgroup
11836 // set. The construct associated with the innermost region that meets this
11837 // condition must specify the same reduction-identifier as the in_reduction
11838 // clause.
11839 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011840 SourceRange ParentSR;
11841 BinaryOperatorKind ParentBOK;
11842 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011843 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011844 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011845 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11846 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011847 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011848 Stack->getTopMostTaskgroupReductionData(
11849 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011850 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11851 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11852 if (!IsParentBOK && !IsParentReductionOp) {
11853 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11854 continue;
11855 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011856 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11857 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11858 IsParentReductionOp) {
11859 bool EmitError = true;
11860 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11861 llvm::FoldingSetNodeID RedId, ParentRedId;
11862 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11863 DeclareReductionRef.get()->Profile(RedId, Context,
11864 /*Canonical=*/true);
11865 EmitError = RedId != ParentRedId;
11866 }
11867 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011868 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011869 diag::err_omp_reduction_identifier_mismatch)
11870 << ReductionIdRange << RefExpr->getSourceRange();
11871 S.Diag(ParentSR.getBegin(),
11872 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011873 << ParentSR
11874 << (IsParentBOK ? ParentBOKDSA.RefExpr
11875 : ParentReductionOpDSA.RefExpr)
11876 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011877 continue;
11878 }
11879 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011880 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11881 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011882 }
11883
Alexey Bataev60da77e2016-02-29 05:54:20 +000011884 DeclRefExpr *Ref = nullptr;
11885 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011886 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011887 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011888 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011889 VarsExpr =
11890 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11891 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011892 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011893 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011894 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011895 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011896 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011897 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011898 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011899 if (!RefRes.isUsable())
11900 continue;
11901 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011902 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11903 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011904 if (!PostUpdateRes.isUsable())
11905 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011906 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11907 Stack->getCurrentDirective() == OMPD_taskgroup) {
11908 S.Diag(RefExpr->getExprLoc(),
11909 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011910 << RefExpr->getSourceRange();
11911 continue;
11912 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011913 RD.ExprPostUpdates.emplace_back(
11914 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011915 }
11916 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011917 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011918 // All reduction items are still marked as reduction (to do not increase
11919 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011920 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011921 if (CurrDir == OMPD_taskgroup) {
11922 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011923 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11924 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011925 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011926 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011927 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011928 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11929 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011930 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011931 return RD.Vars.empty();
11932}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011933
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011934OMPClause *Sema::ActOnOpenMPReductionClause(
11935 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11936 SourceLocation ColonLoc, SourceLocation EndLoc,
11937 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11938 ArrayRef<Expr *> UnresolvedReductions) {
11939 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011940 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011941 StartLoc, LParenLoc, ColonLoc, EndLoc,
11942 ReductionIdScopeSpec, ReductionId,
11943 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011944 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011945
Alexey Bataevc5e02582014-06-16 07:08:35 +000011946 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011947 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11948 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11949 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11950 buildPreInits(Context, RD.ExprCaptures),
11951 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011952}
11953
Alexey Bataev169d96a2017-07-18 20:17:46 +000011954OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11955 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11956 SourceLocation ColonLoc, SourceLocation EndLoc,
11957 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11958 ArrayRef<Expr *> UnresolvedReductions) {
11959 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011960 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11961 StartLoc, LParenLoc, ColonLoc, EndLoc,
11962 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011963 UnresolvedReductions, RD))
11964 return nullptr;
11965
11966 return OMPTaskReductionClause::Create(
11967 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11968 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11969 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11970 buildPreInits(Context, RD.ExprCaptures),
11971 buildPostUpdate(*this, RD.ExprPostUpdates));
11972}
11973
Alexey Bataevfa312f32017-07-21 18:48:21 +000011974OMPClause *Sema::ActOnOpenMPInReductionClause(
11975 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11976 SourceLocation ColonLoc, SourceLocation EndLoc,
11977 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11978 ArrayRef<Expr *> UnresolvedReductions) {
11979 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011980 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011981 StartLoc, LParenLoc, ColonLoc, EndLoc,
11982 ReductionIdScopeSpec, ReductionId,
11983 UnresolvedReductions, RD))
11984 return nullptr;
11985
11986 return OMPInReductionClause::Create(
11987 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11988 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011989 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011990 buildPreInits(Context, RD.ExprCaptures),
11991 buildPostUpdate(*this, RD.ExprPostUpdates));
11992}
11993
Alexey Bataevecba70f2016-04-12 11:02:11 +000011994bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11995 SourceLocation LinLoc) {
11996 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11997 LinKind == OMPC_LINEAR_unknown) {
11998 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11999 return true;
12000 }
12001 return false;
12002}
12003
Alexey Bataeve3727102018-04-18 15:57:46 +000012004bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000012005 OpenMPLinearClauseKind LinKind,
12006 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012007 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000012008 // A variable must not have an incomplete type or a reference type.
12009 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12010 return true;
12011 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12012 !Type->isReferenceType()) {
12013 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12014 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12015 return true;
12016 }
12017 Type = Type.getNonReferenceType();
12018
Joel E. Dennybae586f2019-01-04 22:12:13 +000012019 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12020 // A variable that is privatized must not have a const-qualified type
12021 // unless it is of class type with a mutable member. This restriction does
12022 // not apply to the firstprivate clause.
12023 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012024 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012025
12026 // A list item must be of integral or pointer type.
12027 Type = Type.getUnqualifiedType().getCanonicalType();
12028 const auto *Ty = Type.getTypePtrOrNull();
12029 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12030 !Ty->isPointerType())) {
12031 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12032 if (D) {
12033 bool IsDecl =
12034 !VD ||
12035 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12036 Diag(D->getLocation(),
12037 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12038 << D;
12039 }
12040 return true;
12041 }
12042 return false;
12043}
12044
Alexey Bataev182227b2015-08-20 10:54:39 +000012045OMPClause *Sema::ActOnOpenMPLinearClause(
12046 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12047 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12048 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012049 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012050 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012051 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012052 SmallVector<Decl *, 4> ExprCaptures;
12053 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012054 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012055 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012056 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012057 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012058 SourceLocation ELoc;
12059 SourceRange ERange;
12060 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012061 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012062 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012063 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012064 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012065 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012066 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012067 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012068 ValueDecl *D = Res.first;
12069 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012070 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012071
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012072 QualType Type = D->getType();
12073 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012074
12075 // OpenMP [2.14.3.7, linear clause]
12076 // A list-item cannot appear in more than one linear clause.
12077 // A list-item that appears in a linear clause cannot appear in any
12078 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012079 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012080 if (DVar.RefExpr) {
12081 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12082 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012083 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012084 continue;
12085 }
12086
Alexey Bataevecba70f2016-04-12 11:02:11 +000012087 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012088 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012089 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012090
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012091 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012092 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012093 buildVarDecl(*this, ELoc, Type, D->getName(),
12094 D->hasAttrs() ? &D->getAttrs() : nullptr,
12095 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012096 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012097 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012098 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012099 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012100 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012101 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012102 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012103 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012104 ExprCaptures.push_back(Ref->getDecl());
12105 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12106 ExprResult RefRes = DefaultLvalueConversion(Ref);
12107 if (!RefRes.isUsable())
12108 continue;
12109 ExprResult PostUpdateRes =
12110 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12111 SimpleRefExpr, RefRes.get());
12112 if (!PostUpdateRes.isUsable())
12113 continue;
12114 ExprPostUpdates.push_back(
12115 IgnoredValueConversions(PostUpdateRes.get()).get());
12116 }
12117 }
12118 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012119 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012120 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012121 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012122 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012123 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012124 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012125 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012126
12127 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012128 Vars.push_back((VD || CurContext->isDependentContext())
12129 ? RefExpr->IgnoreParens()
12130 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012131 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012132 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012133 }
12134
12135 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012136 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012137
12138 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012139 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012140 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12141 !Step->isInstantiationDependent() &&
12142 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012143 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012144 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012145 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012146 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012147 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012148
Alexander Musman3276a272015-03-21 10:12:56 +000012149 // Build var to save the step value.
12150 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012151 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012152 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012153 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012154 ExprResult CalcStep =
12155 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012156 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012157
Alexander Musman8dba6642014-04-22 13:09:42 +000012158 // Warn about zero linear step (it would be probably better specified as
12159 // making corresponding variables 'const').
12160 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012161 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12162 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012163 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12164 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012165 if (!IsConstant && CalcStep.isUsable()) {
12166 // Calculate the step beforehand instead of doing this on each iteration.
12167 // (This is not used if the number of iterations may be kfold-ed).
12168 CalcStepExpr = CalcStep.get();
12169 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012170 }
12171
Alexey Bataev182227b2015-08-20 10:54:39 +000012172 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12173 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012174 StepExpr, CalcStepExpr,
12175 buildPreInits(Context, ExprCaptures),
12176 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012177}
12178
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012179static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12180 Expr *NumIterations, Sema &SemaRef,
12181 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012182 // Walk the vars and build update/final expressions for the CodeGen.
12183 SmallVector<Expr *, 8> Updates;
12184 SmallVector<Expr *, 8> Finals;
12185 Expr *Step = Clause.getStep();
12186 Expr *CalcStep = Clause.getCalcStep();
12187 // OpenMP [2.14.3.7, linear clause]
12188 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012189 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012190 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012191 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012192 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12193 bool HasErrors = false;
12194 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012195 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012196 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12197 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012198 SourceLocation ELoc;
12199 SourceRange ERange;
12200 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012201 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012202 ValueDecl *D = Res.first;
12203 if (Res.second || !D) {
12204 Updates.push_back(nullptr);
12205 Finals.push_back(nullptr);
12206 HasErrors = true;
12207 continue;
12208 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012209 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012210 // OpenMP [2.15.11, distribute simd Construct]
12211 // A list item may not appear in a linear clause, unless it is the loop
12212 // iteration variable.
12213 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12214 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12215 SemaRef.Diag(ELoc,
12216 diag::err_omp_linear_distribute_var_non_loop_iteration);
12217 Updates.push_back(nullptr);
12218 Finals.push_back(nullptr);
12219 HasErrors = true;
12220 continue;
12221 }
Alexander Musman3276a272015-03-21 10:12:56 +000012222 Expr *InitExpr = *CurInit;
12223
12224 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012225 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012226 Expr *CapturedRef;
12227 if (LinKind == OMPC_LINEAR_uval)
12228 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12229 else
12230 CapturedRef =
12231 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12232 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12233 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012234
12235 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012236 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012237 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012238 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012239 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012240 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012241 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012242 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012243 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012244 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012245
12246 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012247 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012248 if (!Info.first)
12249 Final =
12250 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12251 InitExpr, NumIterations, Step, /*Subtract=*/false);
12252 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012253 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012254 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012255 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012256
Alexander Musman3276a272015-03-21 10:12:56 +000012257 if (!Update.isUsable() || !Final.isUsable()) {
12258 Updates.push_back(nullptr);
12259 Finals.push_back(nullptr);
12260 HasErrors = true;
12261 } else {
12262 Updates.push_back(Update.get());
12263 Finals.push_back(Final.get());
12264 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012265 ++CurInit;
12266 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012267 }
12268 Clause.setUpdates(Updates);
12269 Clause.setFinals(Finals);
12270 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012271}
12272
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012273OMPClause *Sema::ActOnOpenMPAlignedClause(
12274 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12275 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012276 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012277 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012278 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12279 SourceLocation ELoc;
12280 SourceRange ERange;
12281 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012282 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012283 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012284 // It will be analyzed later.
12285 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012286 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012287 ValueDecl *D = Res.first;
12288 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012289 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012290
Alexey Bataev1efd1662016-03-29 10:59:56 +000012291 QualType QType = D->getType();
12292 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012293
12294 // OpenMP [2.8.1, simd construct, Restrictions]
12295 // The type of list items appearing in the aligned clause must be
12296 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012297 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012298 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012299 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012300 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012301 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012302 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012303 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012304 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012305 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012306 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012307 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012308 continue;
12309 }
12310
12311 // OpenMP [2.8.1, simd construct, Restrictions]
12312 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012313 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012314 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012315 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12316 << getOpenMPClauseName(OMPC_aligned);
12317 continue;
12318 }
12319
Alexey Bataev1efd1662016-03-29 10:59:56 +000012320 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012321 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012322 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12323 Vars.push_back(DefaultFunctionArrayConversion(
12324 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12325 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012326 }
12327
12328 // OpenMP [2.8.1, simd construct, Description]
12329 // The parameter of the aligned clause, alignment, must be a constant
12330 // positive integer expression.
12331 // If no optional parameter is specified, implementation-defined default
12332 // alignments for SIMD instructions on the target platforms are assumed.
12333 if (Alignment != nullptr) {
12334 ExprResult AlignResult =
12335 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12336 if (AlignResult.isInvalid())
12337 return nullptr;
12338 Alignment = AlignResult.get();
12339 }
12340 if (Vars.empty())
12341 return nullptr;
12342
12343 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12344 EndLoc, Vars, Alignment);
12345}
12346
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012347OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12348 SourceLocation StartLoc,
12349 SourceLocation LParenLoc,
12350 SourceLocation EndLoc) {
12351 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012352 SmallVector<Expr *, 8> SrcExprs;
12353 SmallVector<Expr *, 8> DstExprs;
12354 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012355 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012356 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12357 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012358 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012359 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012360 SrcExprs.push_back(nullptr);
12361 DstExprs.push_back(nullptr);
12362 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012363 continue;
12364 }
12365
Alexey Bataeved09d242014-05-28 05:53:51 +000012366 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012367 // OpenMP [2.1, C/C++]
12368 // A list item is a variable name.
12369 // OpenMP [2.14.4.1, Restrictions, p.1]
12370 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012371 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012372 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012373 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12374 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012375 continue;
12376 }
12377
12378 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012379 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012380
12381 QualType Type = VD->getType();
12382 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12383 // It will be analyzed later.
12384 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012385 SrcExprs.push_back(nullptr);
12386 DstExprs.push_back(nullptr);
12387 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012388 continue;
12389 }
12390
12391 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12392 // A list item that appears in a copyin clause must be threadprivate.
12393 if (!DSAStack->isThreadPrivate(VD)) {
12394 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012395 << getOpenMPClauseName(OMPC_copyin)
12396 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012397 continue;
12398 }
12399
12400 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12401 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012402 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012403 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012404 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12405 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012406 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012407 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012408 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012409 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012410 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012411 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012412 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012413 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012414 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012415 // For arrays generate assignment operation for single element and replace
12416 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012417 ExprResult AssignmentOp =
12418 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12419 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012420 if (AssignmentOp.isInvalid())
12421 continue;
12422 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012423 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012424 if (AssignmentOp.isInvalid())
12425 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012426
12427 DSAStack->addDSA(VD, DE, OMPC_copyin);
12428 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012429 SrcExprs.push_back(PseudoSrcExpr);
12430 DstExprs.push_back(PseudoDstExpr);
12431 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012432 }
12433
Alexey Bataeved09d242014-05-28 05:53:51 +000012434 if (Vars.empty())
12435 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012436
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012437 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12438 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012439}
12440
Alexey Bataevbae9a792014-06-27 10:37:06 +000012441OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12442 SourceLocation StartLoc,
12443 SourceLocation LParenLoc,
12444 SourceLocation EndLoc) {
12445 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012446 SmallVector<Expr *, 8> SrcExprs;
12447 SmallVector<Expr *, 8> DstExprs;
12448 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012449 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012450 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12451 SourceLocation ELoc;
12452 SourceRange ERange;
12453 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012454 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012455 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012456 // It will be analyzed later.
12457 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012458 SrcExprs.push_back(nullptr);
12459 DstExprs.push_back(nullptr);
12460 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012461 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012462 ValueDecl *D = Res.first;
12463 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012464 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012465
Alexey Bataeve122da12016-03-17 10:50:17 +000012466 QualType Type = D->getType();
12467 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012468
12469 // OpenMP [2.14.4.2, Restrictions, p.2]
12470 // A list item that appears in a copyprivate clause may not appear in a
12471 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012472 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012473 DSAStackTy::DSAVarData DVar =
12474 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012475 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12476 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012477 Diag(ELoc, diag::err_omp_wrong_dsa)
12478 << getOpenMPClauseName(DVar.CKind)
12479 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012480 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012481 continue;
12482 }
12483
12484 // OpenMP [2.11.4.2, Restrictions, p.1]
12485 // All list items that appear in a copyprivate clause must be either
12486 // threadprivate or private in the enclosing context.
12487 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012488 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012489 if (DVar.CKind == OMPC_shared) {
12490 Diag(ELoc, diag::err_omp_required_access)
12491 << getOpenMPClauseName(OMPC_copyprivate)
12492 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012493 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012494 continue;
12495 }
12496 }
12497 }
12498
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012499 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012500 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012501 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012502 << getOpenMPClauseName(OMPC_copyprivate) << Type
12503 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012504 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012505 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012506 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012507 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012508 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012509 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012510 continue;
12511 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012512
Alexey Bataevbae9a792014-06-27 10:37:06 +000012513 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12514 // A variable of class type (or array thereof) that appears in a
12515 // copyin clause requires an accessible, unambiguous copy assignment
12516 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012517 Type = Context.getBaseElementType(Type.getNonReferenceType())
12518 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012519 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012520 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012521 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012522 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12523 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012524 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012525 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012526 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12527 ExprResult AssignmentOp = BuildBinOp(
12528 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012529 if (AssignmentOp.isInvalid())
12530 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012531 AssignmentOp =
12532 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012533 if (AssignmentOp.isInvalid())
12534 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012535
12536 // No need to mark vars as copyprivate, they are already threadprivate or
12537 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012538 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012539 Vars.push_back(
12540 VD ? RefExpr->IgnoreParens()
12541 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012542 SrcExprs.push_back(PseudoSrcExpr);
12543 DstExprs.push_back(PseudoDstExpr);
12544 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012545 }
12546
12547 if (Vars.empty())
12548 return nullptr;
12549
Alexey Bataeva63048e2015-03-23 06:18:07 +000012550 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12551 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012552}
12553
Alexey Bataev6125da92014-07-21 11:26:11 +000012554OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12555 SourceLocation StartLoc,
12556 SourceLocation LParenLoc,
12557 SourceLocation EndLoc) {
12558 if (VarList.empty())
12559 return nullptr;
12560
12561 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12562}
Alexey Bataevdea47612014-07-23 07:46:59 +000012563
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012564OMPClause *
12565Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12566 SourceLocation DepLoc, SourceLocation ColonLoc,
12567 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12568 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012569 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012570 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012571 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012572 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012573 return nullptr;
12574 }
12575 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012576 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12577 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012578 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012579 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012580 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12581 /*Last=*/OMPC_DEPEND_unknown, Except)
12582 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012583 return nullptr;
12584 }
12585 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012586 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012587 llvm::APSInt DepCounter(/*BitWidth=*/32);
12588 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012589 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12590 if (const Expr *OrderedCountExpr =
12591 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012592 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12593 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012594 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012595 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012596 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012597 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12598 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12599 // It will be analyzed later.
12600 Vars.push_back(RefExpr);
12601 continue;
12602 }
12603
12604 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012605 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012606 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012607 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012608 DepCounter >= TotalDepCount) {
12609 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12610 continue;
12611 }
12612 ++DepCounter;
12613 // OpenMP [2.13.9, Summary]
12614 // depend(dependence-type : vec), where dependence-type is:
12615 // 'sink' and where vec is the iteration vector, which has the form:
12616 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12617 // where n is the value specified by the ordered clause in the loop
12618 // directive, xi denotes the loop iteration variable of the i-th nested
12619 // loop associated with the loop directive, and di is a constant
12620 // non-negative integer.
12621 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012622 // It will be analyzed later.
12623 Vars.push_back(RefExpr);
12624 continue;
12625 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012626 SimpleExpr = SimpleExpr->IgnoreImplicit();
12627 OverloadedOperatorKind OOK = OO_None;
12628 SourceLocation OOLoc;
12629 Expr *LHS = SimpleExpr;
12630 Expr *RHS = nullptr;
12631 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12632 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12633 OOLoc = BO->getOperatorLoc();
12634 LHS = BO->getLHS()->IgnoreParenImpCasts();
12635 RHS = BO->getRHS()->IgnoreParenImpCasts();
12636 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12637 OOK = OCE->getOperator();
12638 OOLoc = OCE->getOperatorLoc();
12639 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12640 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12641 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12642 OOK = MCE->getMethodDecl()
12643 ->getNameInfo()
12644 .getName()
12645 .getCXXOverloadedOperator();
12646 OOLoc = MCE->getCallee()->getExprLoc();
12647 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12648 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012649 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012650 SourceLocation ELoc;
12651 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012652 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012653 if (Res.second) {
12654 // It will be analyzed later.
12655 Vars.push_back(RefExpr);
12656 }
12657 ValueDecl *D = Res.first;
12658 if (!D)
12659 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012660
Alexey Bataev17daedf2018-02-15 22:42:57 +000012661 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12662 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12663 continue;
12664 }
12665 if (RHS) {
12666 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12667 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12668 if (RHSRes.isInvalid())
12669 continue;
12670 }
12671 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012672 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012673 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012674 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012675 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012676 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012677 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12678 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012679 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012680 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012681 continue;
12682 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012683 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012684 } else {
12685 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12686 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12687 (ASE &&
12688 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12689 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12690 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12691 << RefExpr->getSourceRange();
12692 continue;
12693 }
12694 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12695 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12696 ExprResult Res =
12697 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12698 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12699 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12700 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12701 << RefExpr->getSourceRange();
12702 continue;
12703 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012704 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012705 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012706 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012707
12708 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12709 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012710 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012711 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12712 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12713 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12714 }
12715 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12716 Vars.empty())
12717 return nullptr;
12718
Alexey Bataev8b427062016-05-25 12:36:08 +000012719 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012720 DepKind, DepLoc, ColonLoc, Vars,
12721 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012722 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12723 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012724 DSAStack->addDoacrossDependClause(C, OpsOffs);
12725 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012726}
Michael Wonge710d542015-08-07 16:16:36 +000012727
12728OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12729 SourceLocation LParenLoc,
12730 SourceLocation EndLoc) {
12731 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012732 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012733
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012734 // OpenMP [2.9.1, Restrictions]
12735 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012736 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012737 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012738 return nullptr;
12739
Alexey Bataev931e19b2017-10-02 16:32:39 +000012740 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012741 OpenMPDirectiveKind CaptureRegion =
12742 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12743 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012744 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012745 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012746 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12747 HelperValStmt = buildPreInits(Context, Captures);
12748 }
12749
Alexey Bataev8451efa2018-01-15 19:06:12 +000012750 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12751 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012752}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012753
Alexey Bataeve3727102018-04-18 15:57:46 +000012754static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012755 DSAStackTy *Stack, QualType QTy,
12756 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012757 NamedDecl *ND;
12758 if (QTy->isIncompleteType(&ND)) {
12759 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12760 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012761 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012762 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12763 !QTy.isTrivialType(SemaRef.Context))
12764 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012765 return true;
12766}
12767
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012768/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012769/// (array section or array subscript) does NOT specify the whole size of the
12770/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012771static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012772 const Expr *E,
12773 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012774 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012775
12776 // If this is an array subscript, it refers to the whole size if the size of
12777 // the dimension is constant and equals 1. Also, an array section assumes the
12778 // format of an array subscript if no colon is used.
12779 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012780 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012781 return ATy->getSize().getSExtValue() != 1;
12782 // Size can't be evaluated statically.
12783 return false;
12784 }
12785
12786 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012787 const Expr *LowerBound = OASE->getLowerBound();
12788 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012789
12790 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012791 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012792 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012793 Expr::EvalResult Result;
12794 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012795 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012796
12797 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012798 if (ConstLowerBound.getSExtValue())
12799 return true;
12800 }
12801
12802 // If we don't have a length we covering the whole dimension.
12803 if (!Length)
12804 return false;
12805
12806 // If the base is a pointer, we don't have a way to get the size of the
12807 // pointee.
12808 if (BaseQTy->isPointerType())
12809 return false;
12810
12811 // We can only check if the length is the same as the size of the dimension
12812 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012813 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012814 if (!CATy)
12815 return false;
12816
Fangrui Song407659a2018-11-30 23:41:18 +000012817 Expr::EvalResult Result;
12818 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012819 return false; // Can't get the integer value as a constant.
12820
Fangrui Song407659a2018-11-30 23:41:18 +000012821 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012822 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12823}
12824
12825// Return true if it can be proven that the provided array expression (array
12826// section or array subscript) does NOT specify a single element of the array
12827// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012828static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012829 const Expr *E,
12830 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012831 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012832
12833 // An array subscript always refer to a single element. Also, an array section
12834 // assumes the format of an array subscript if no colon is used.
12835 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12836 return false;
12837
12838 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012839 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012840
12841 // If we don't have a length we have to check if the array has unitary size
12842 // for this dimension. Also, we should always expect a length if the base type
12843 // is pointer.
12844 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012845 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012846 return ATy->getSize().getSExtValue() != 1;
12847 // We cannot assume anything.
12848 return false;
12849 }
12850
12851 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012852 Expr::EvalResult Result;
12853 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012854 return false; // Can't get the integer value as a constant.
12855
Fangrui Song407659a2018-11-30 23:41:18 +000012856 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012857 return ConstLength.getSExtValue() != 1;
12858}
12859
Samuel Antao661c0902016-05-26 17:39:58 +000012860// Return the expression of the base of the mappable expression or null if it
12861// cannot be determined and do all the necessary checks to see if the expression
12862// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012863// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012864static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012865 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012866 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012867 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012868 SourceLocation ELoc = E->getExprLoc();
12869 SourceRange ERange = E->getSourceRange();
12870
12871 // The base of elements of list in a map clause have to be either:
12872 // - a reference to variable or field.
12873 // - a member expression.
12874 // - an array expression.
12875 //
12876 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12877 // reference to 'r'.
12878 //
12879 // If we have:
12880 //
12881 // struct SS {
12882 // Bla S;
12883 // foo() {
12884 // #pragma omp target map (S.Arr[:12]);
12885 // }
12886 // }
12887 //
12888 // We want to retrieve the member expression 'this->S';
12889
Alexey Bataeve3727102018-04-18 15:57:46 +000012890 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012891
Samuel Antao5de996e2016-01-22 20:21:36 +000012892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12893 // If a list item is an array section, it must specify contiguous storage.
12894 //
12895 // For this restriction it is sufficient that we make sure only references
12896 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012897 // exist except in the rightmost expression (unless they cover the whole
12898 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012899 //
12900 // r.ArrS[3:5].Arr[6:7]
12901 //
12902 // r.ArrS[3:5].x
12903 //
12904 // but these would be valid:
12905 // r.ArrS[3].Arr[6:7]
12906 //
12907 // r.ArrS[3].x
12908
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012909 bool AllowUnitySizeArraySection = true;
12910 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012911
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012912 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012913 E = E->IgnoreParenImpCasts();
12914
12915 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12916 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012917 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012918
12919 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012920
12921 // If we got a reference to a declaration, we should not expect any array
12922 // section before that.
12923 AllowUnitySizeArraySection = false;
12924 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012925
12926 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012927 CurComponents.emplace_back(CurE, CurE->getDecl());
12928 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012929 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012930
12931 if (isa<CXXThisExpr>(BaseE))
12932 // We found a base expression: this->Val.
12933 RelevantExpr = CurE;
12934 else
12935 E = BaseE;
12936
12937 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012938 if (!NoDiagnose) {
12939 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12940 << CurE->getSourceRange();
12941 return nullptr;
12942 }
12943 if (RelevantExpr)
12944 return nullptr;
12945 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012946 }
12947
12948 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12949
12950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12951 // A bit-field cannot appear in a map clause.
12952 //
12953 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012954 if (!NoDiagnose) {
12955 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12956 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12957 return nullptr;
12958 }
12959 if (RelevantExpr)
12960 return nullptr;
12961 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012962 }
12963
12964 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12965 // If the type of a list item is a reference to a type T then the type
12966 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012967 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012968
12969 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12970 // A list item cannot be a variable that is a member of a structure with
12971 // a union type.
12972 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012973 if (CurType->isUnionType()) {
12974 if (!NoDiagnose) {
12975 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12976 << CurE->getSourceRange();
12977 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012978 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012979 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012980 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012981
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012982 // If we got a member expression, we should not expect any array section
12983 // before that:
12984 //
12985 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12986 // If a list item is an element of a structure, only the rightmost symbol
12987 // of the variable reference can be an array section.
12988 //
12989 AllowUnitySizeArraySection = false;
12990 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012991
12992 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012993 CurComponents.emplace_back(CurE, FD);
12994 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012995 E = CurE->getBase()->IgnoreParenImpCasts();
12996
12997 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012998 if (!NoDiagnose) {
12999 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13000 << 0 << CurE->getSourceRange();
13001 return nullptr;
13002 }
13003 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013004 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013005
13006 // If we got an array subscript that express the whole dimension we
13007 // can have any array expressions before. If it only expressing part of
13008 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000013009 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013010 E->getType()))
13011 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013012
Patrick Lystere13b1e32019-01-02 19:28:48 +000013013 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13014 Expr::EvalResult Result;
13015 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13016 if (!Result.Val.getInt().isNullValue()) {
13017 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13018 diag::err_omp_invalid_map_this_expr);
13019 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13020 diag::note_omp_invalid_subscript_on_this_ptr_map);
13021 }
13022 }
13023 RelevantExpr = TE;
13024 }
13025
Samuel Antao90927002016-04-26 14:54:23 +000013026 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013027 CurComponents.emplace_back(CurE, nullptr);
13028 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013029 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013030 E = CurE->getBase()->IgnoreParenImpCasts();
13031
Alexey Bataev27041fa2017-12-05 15:22:49 +000013032 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013033 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13034
Samuel Antao5de996e2016-01-22 20:21:36 +000013035 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13036 // If the type of a list item is a reference to a type T then the type
13037 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013038 if (CurType->isReferenceType())
13039 CurType = CurType->getPointeeType();
13040
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013041 bool IsPointer = CurType->isAnyPointerType();
13042
13043 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013044 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13045 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013046 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013047 }
13048
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013049 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013050 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013051 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013052 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013053
Samuel Antaodab51bb2016-07-18 23:22:11 +000013054 if (AllowWholeSizeArraySection) {
13055 // Any array section is currently allowed. Allowing a whole size array
13056 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013057 //
13058 // If this array section refers to the whole dimension we can still
13059 // accept other array sections before this one, except if the base is a
13060 // pointer. Otherwise, only unitary sections are accepted.
13061 if (NotWhole || IsPointer)
13062 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013063 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013064 // A unity or whole array section is not allowed and that is not
13065 // compatible with the properties of the current array section.
13066 SemaRef.Diag(
13067 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13068 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013069 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013070 }
Samuel Antao90927002016-04-26 14:54:23 +000013071
Patrick Lystere13b1e32019-01-02 19:28:48 +000013072 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13073 Expr::EvalResult ResultR;
13074 Expr::EvalResult ResultL;
13075 if (CurE->getLength()->EvaluateAsInt(ResultR,
13076 SemaRef.getASTContext())) {
13077 if (!ResultR.Val.getInt().isOneValue()) {
13078 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13079 diag::err_omp_invalid_map_this_expr);
13080 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13081 diag::note_omp_invalid_length_on_this_ptr_mapping);
13082 }
13083 }
13084 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13085 ResultL, SemaRef.getASTContext())) {
13086 if (!ResultL.Val.getInt().isNullValue()) {
13087 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13088 diag::err_omp_invalid_map_this_expr);
13089 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13090 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13091 }
13092 }
13093 RelevantExpr = TE;
13094 }
13095
Samuel Antao90927002016-04-26 14:54:23 +000013096 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013097 CurComponents.emplace_back(CurE, nullptr);
13098 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013099 if (!NoDiagnose) {
13100 // If nothing else worked, this is not a valid map clause expression.
13101 SemaRef.Diag(
13102 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13103 << ERange;
13104 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013105 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013106 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013107 }
13108
13109 return RelevantExpr;
13110}
13111
13112// Return true if expression E associated with value VD has conflicts with other
13113// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013114static bool checkMapConflicts(
13115 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013116 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013117 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13118 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013119 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013120 SourceLocation ELoc = E->getExprLoc();
13121 SourceRange ERange = E->getSourceRange();
13122
13123 // In order to easily check the conflicts we need to match each component of
13124 // the expression under test with the components of the expressions that are
13125 // already in the stack.
13126
Samuel Antao5de996e2016-01-22 20:21:36 +000013127 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013128 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013129 "Map clause expression with unexpected base!");
13130
13131 // Variables to help detecting enclosing problems in data environment nests.
13132 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013133 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013134
Samuel Antao90927002016-04-26 14:54:23 +000013135 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13136 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013137 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13138 ERange, CKind, &EnclosingExpr,
13139 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13140 StackComponents,
13141 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013142 assert(!StackComponents.empty() &&
13143 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013144 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013145 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013146 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013147
Samuel Antao90927002016-04-26 14:54:23 +000013148 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013149 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013150
Samuel Antao5de996e2016-01-22 20:21:36 +000013151 // Expressions must start from the same base. Here we detect at which
13152 // point both expressions diverge from each other and see if we can
13153 // detect if the memory referred to both expressions is contiguous and
13154 // do not overlap.
13155 auto CI = CurComponents.rbegin();
13156 auto CE = CurComponents.rend();
13157 auto SI = StackComponents.rbegin();
13158 auto SE = StackComponents.rend();
13159 for (; CI != CE && SI != SE; ++CI, ++SI) {
13160
13161 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13162 // At most one list item can be an array item derived from a given
13163 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013164 if (CurrentRegionOnly &&
13165 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13166 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13167 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13168 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13169 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013170 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013171 << CI->getAssociatedExpression()->getSourceRange();
13172 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13173 diag::note_used_here)
13174 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013175 return true;
13176 }
13177
13178 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013179 if (CI->getAssociatedExpression()->getStmtClass() !=
13180 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013181 break;
13182
13183 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013184 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013185 break;
13186 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013187 // Check if the extra components of the expressions in the enclosing
13188 // data environment are redundant for the current base declaration.
13189 // If they are, the maps completely overlap, which is legal.
13190 for (; SI != SE; ++SI) {
13191 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013192 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013193 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013194 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013195 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013196 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013197 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013198 Type =
13199 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13200 }
13201 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013202 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013203 SemaRef, SI->getAssociatedExpression(), Type))
13204 break;
13205 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013206
13207 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13208 // List items of map clauses in the same construct must not share
13209 // original storage.
13210 //
13211 // If the expressions are exactly the same or one is a subset of the
13212 // other, it means they are sharing storage.
13213 if (CI == CE && SI == SE) {
13214 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013215 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013216 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013217 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013218 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013219 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13220 << ERange;
13221 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013222 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13223 << RE->getSourceRange();
13224 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013225 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013226 // If we find the same expression in the enclosing data environment,
13227 // that is legal.
13228 IsEnclosedByDataEnvironmentExpr = true;
13229 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013230 }
13231
Samuel Antao90927002016-04-26 14:54:23 +000013232 QualType DerivedType =
13233 std::prev(CI)->getAssociatedDeclaration()->getType();
13234 SourceLocation DerivedLoc =
13235 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013236
13237 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13238 // If the type of a list item is a reference to a type T then the type
13239 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013240 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013241
13242 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13243 // A variable for which the type is pointer and an array section
13244 // derived from that variable must not appear as list items of map
13245 // clauses of the same construct.
13246 //
13247 // Also, cover one of the cases in:
13248 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13249 // If any part of the original storage of a list item has corresponding
13250 // storage in the device data environment, all of the original storage
13251 // must have corresponding storage in the device data environment.
13252 //
13253 if (DerivedType->isAnyPointerType()) {
13254 if (CI == CE || SI == SE) {
13255 SemaRef.Diag(
13256 DerivedLoc,
13257 diag::err_omp_pointer_mapped_along_with_derived_section)
13258 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013259 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13260 << RE->getSourceRange();
13261 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013262 }
13263 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013264 SI->getAssociatedExpression()->getStmtClass() ||
13265 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13266 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013267 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013268 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013269 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013270 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13271 << RE->getSourceRange();
13272 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013273 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013274 }
13275
13276 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13277 // List items of map clauses in the same construct must not share
13278 // original storage.
13279 //
13280 // An expression is a subset of the other.
13281 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013282 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013283 if (CI != CE || SI != SE) {
13284 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13285 // a pointer.
13286 auto Begin =
13287 CI != CE ? CurComponents.begin() : StackComponents.begin();
13288 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13289 auto It = Begin;
13290 while (It != End && !It->getAssociatedDeclaration())
13291 std::advance(It, 1);
13292 assert(It != End &&
13293 "Expected at least one component with the declaration.");
13294 if (It != Begin && It->getAssociatedDeclaration()
13295 ->getType()
13296 .getCanonicalType()
13297 ->isAnyPointerType()) {
13298 IsEnclosedByDataEnvironmentExpr = false;
13299 EnclosingExpr = nullptr;
13300 return false;
13301 }
13302 }
Samuel Antao661c0902016-05-26 17:39:58 +000013303 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013304 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013305 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013306 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13307 << ERange;
13308 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013309 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13310 << RE->getSourceRange();
13311 return true;
13312 }
13313
13314 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013315 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013316 if (!CurrentRegionOnly && SI != SE)
13317 EnclosingExpr = RE;
13318
13319 // The current expression is a subset of the expression in the data
13320 // environment.
13321 IsEnclosedByDataEnvironmentExpr |=
13322 (!CurrentRegionOnly && CI != CE && SI == SE);
13323
13324 return false;
13325 });
13326
13327 if (CurrentRegionOnly)
13328 return FoundError;
13329
13330 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13331 // If any part of the original storage of a list item has corresponding
13332 // storage in the device data environment, all of the original storage must
13333 // have corresponding storage in the device data environment.
13334 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13335 // If a list item is an element of a structure, and a different element of
13336 // the structure has a corresponding list item in the device data environment
13337 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013338 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013339 // data environment prior to the task encountering the construct.
13340 //
13341 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13342 SemaRef.Diag(ELoc,
13343 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13344 << ERange;
13345 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13346 << EnclosingExpr->getSourceRange();
13347 return true;
13348 }
13349
13350 return FoundError;
13351}
13352
Michael Kruse4304e9d2019-02-19 16:38:20 +000013353// Look up the user-defined mapper given the mapper name and mapped type, and
13354// build a reference to it.
13355ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13356 CXXScopeSpec &MapperIdScopeSpec,
13357 const DeclarationNameInfo &MapperId,
13358 QualType Type, Expr *UnresolvedMapper) {
13359 if (MapperIdScopeSpec.isInvalid())
13360 return ExprError();
13361 // Find all user-defined mappers with the given MapperId.
13362 SmallVector<UnresolvedSet<8>, 4> Lookups;
13363 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13364 Lookup.suppressDiagnostics();
13365 if (S) {
13366 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13367 NamedDecl *D = Lookup.getRepresentativeDecl();
13368 while (S && !S->isDeclScope(D))
13369 S = S->getParent();
13370 if (S)
13371 S = S->getParent();
13372 Lookups.emplace_back();
13373 Lookups.back().append(Lookup.begin(), Lookup.end());
13374 Lookup.clear();
13375 }
13376 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13377 // Extract the user-defined mappers with the given MapperId.
13378 Lookups.push_back(UnresolvedSet<8>());
13379 for (NamedDecl *D : ULE->decls()) {
13380 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13381 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13382 Lookups.back().addDecl(DMD);
13383 }
13384 }
13385 // Defer the lookup for dependent types. The results will be passed through
13386 // UnresolvedMapper on instantiation.
13387 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13388 Type->isInstantiationDependentType() ||
13389 Type->containsUnexpandedParameterPack() ||
13390 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13391 return !D->isInvalidDecl() &&
13392 (D->getType()->isDependentType() ||
13393 D->getType()->isInstantiationDependentType() ||
13394 D->getType()->containsUnexpandedParameterPack());
13395 })) {
13396 UnresolvedSet<8> URS;
13397 for (const UnresolvedSet<8> &Set : Lookups) {
13398 if (Set.empty())
13399 continue;
13400 URS.append(Set.begin(), Set.end());
13401 }
13402 return UnresolvedLookupExpr::Create(
13403 SemaRef.Context, /*NamingClass=*/nullptr,
13404 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13405 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13406 }
13407 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13408 // The type must be of struct, union or class type in C and C++
13409 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13410 return ExprEmpty();
13411 SourceLocation Loc = MapperId.getLoc();
13412 // Perform argument dependent lookup.
13413 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13414 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13415 // Return the first user-defined mapper with the desired type.
13416 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13417 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13418 if (!D->isInvalidDecl() &&
13419 SemaRef.Context.hasSameType(D->getType(), Type))
13420 return D;
13421 return nullptr;
13422 }))
13423 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13424 // Find the first user-defined mapper with a type derived from the desired
13425 // type.
13426 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13427 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13428 if (!D->isInvalidDecl() &&
13429 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13430 !Type.isMoreQualifiedThan(D->getType()))
13431 return D;
13432 return nullptr;
13433 })) {
13434 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13435 /*DetectVirtual=*/false);
13436 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13437 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13438 VD->getType().getUnqualifiedType()))) {
13439 if (SemaRef.CheckBaseClassAccess(
13440 Loc, VD->getType(), Type, Paths.front(),
13441 /*DiagID=*/0) != Sema::AR_inaccessible) {
13442 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13443 }
13444 }
13445 }
13446 }
13447 // Report error if a mapper is specified, but cannot be found.
13448 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13449 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13450 << Type << MapperId.getName();
13451 return ExprError();
13452 }
13453 return ExprEmpty();
13454}
13455
Samuel Antao661c0902016-05-26 17:39:58 +000013456namespace {
13457// Utility struct that gathers all the related lists associated with a mappable
13458// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013459struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013460 // The list of expressions.
13461 ArrayRef<Expr *> VarList;
13462 // The list of processed expressions.
13463 SmallVector<Expr *, 16> ProcessedVarList;
13464 // The mappble components for each expression.
13465 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13466 // The base declaration of the variable.
13467 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013468 // The reference to the user-defined mapper associated with every expression.
13469 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013470
13471 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13472 // We have a list of components and base declarations for each entry in the
13473 // variable list.
13474 VarComponents.reserve(VarList.size());
13475 VarBaseDeclarations.reserve(VarList.size());
13476 }
13477};
13478}
13479
13480// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013481// \a CKind. In the check process the valid expressions, mappable expression
13482// components, variables, and user-defined mappers are extracted and used to
13483// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13484// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13485// and \a MapperId are expected to be valid if the clause kind is 'map'.
13486static void checkMappableExpressionList(
13487 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13488 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013489 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13490 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013491 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013492 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013493 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13494 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013495 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013496
13497 // If the identifier of user-defined mapper is not specified, it is "default".
13498 // We do not change the actual name in this clause to distinguish whether a
13499 // mapper is specified explicitly, i.e., it is not explicitly specified when
13500 // MapperId.getName() is empty.
13501 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13502 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13503 MapperId.setName(DeclNames.getIdentifier(
13504 &SemaRef.getASTContext().Idents.get("default")));
13505 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013506
13507 // Iterators to find the current unresolved mapper expression.
13508 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13509 bool UpdateUMIt = false;
13510 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013511
Samuel Antao90927002016-04-26 14:54:23 +000013512 // Keep track of the mappable components and base declarations in this clause.
13513 // Each entry in the list is going to have a list of components associated. We
13514 // record each set of the components so that we can build the clause later on.
13515 // In the end we should have the same amount of declarations and component
13516 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013517
Alexey Bataeve3727102018-04-18 15:57:46 +000013518 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013519 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013520 SourceLocation ELoc = RE->getExprLoc();
13521
Michael Kruse4304e9d2019-02-19 16:38:20 +000013522 // Find the current unresolved mapper expression.
13523 if (UpdateUMIt && UMIt != UMEnd) {
13524 UMIt++;
13525 assert(
13526 UMIt != UMEnd &&
13527 "Expect the size of UnresolvedMappers to match with that of VarList");
13528 }
13529 UpdateUMIt = true;
13530 if (UMIt != UMEnd)
13531 UnresolvedMapper = *UMIt;
13532
Alexey Bataeve3727102018-04-18 15:57:46 +000013533 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013534
13535 if (VE->isValueDependent() || VE->isTypeDependent() ||
13536 VE->isInstantiationDependent() ||
13537 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013538 // Try to find the associated user-defined mapper.
13539 ExprResult ER = buildUserDefinedMapperRef(
13540 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13541 VE->getType().getCanonicalType(), UnresolvedMapper);
13542 if (ER.isInvalid())
13543 continue;
13544 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013545 // We can only analyze this information once the missing information is
13546 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013547 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013548 continue;
13549 }
13550
Alexey Bataeve3727102018-04-18 15:57:46 +000013551 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013552
Samuel Antao5de996e2016-01-22 20:21:36 +000013553 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013554 SemaRef.Diag(ELoc,
13555 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013556 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013557 continue;
13558 }
13559
Samuel Antao90927002016-04-26 14:54:23 +000013560 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13561 ValueDecl *CurDeclaration = nullptr;
13562
13563 // Obtain the array or member expression bases if required. Also, fill the
13564 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013565 const Expr *BE = checkMapClauseExpressionBase(
13566 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013567 if (!BE)
13568 continue;
13569
Samuel Antao90927002016-04-26 14:54:23 +000013570 assert(!CurComponents.empty() &&
13571 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013572
Patrick Lystere13b1e32019-01-02 19:28:48 +000013573 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13574 // Add store "this" pointer to class in DSAStackTy for future checking
13575 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013576 // Try to find the associated user-defined mapper.
13577 ExprResult ER = buildUserDefinedMapperRef(
13578 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13579 VE->getType().getCanonicalType(), UnresolvedMapper);
13580 if (ER.isInvalid())
13581 continue;
13582 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013583 // Skip restriction checking for variable or field declarations
13584 MVLI.ProcessedVarList.push_back(RE);
13585 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13586 MVLI.VarComponents.back().append(CurComponents.begin(),
13587 CurComponents.end());
13588 MVLI.VarBaseDeclarations.push_back(nullptr);
13589 continue;
13590 }
13591
Samuel Antao90927002016-04-26 14:54:23 +000013592 // For the following checks, we rely on the base declaration which is
13593 // expected to be associated with the last component. The declaration is
13594 // expected to be a variable or a field (if 'this' is being mapped).
13595 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13596 assert(CurDeclaration && "Null decl on map clause.");
13597 assert(
13598 CurDeclaration->isCanonicalDecl() &&
13599 "Expecting components to have associated only canonical declarations.");
13600
13601 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013602 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013603
13604 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013605 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013606
13607 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013608 // threadprivate variables cannot appear in a map clause.
13609 // OpenMP 4.5 [2.10.5, target update Construct]
13610 // threadprivate variables cannot appear in a from clause.
13611 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013612 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013613 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13614 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013615 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013616 continue;
13617 }
13618
Samuel Antao5de996e2016-01-22 20:21:36 +000013619 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13620 // A list item cannot appear in both a map clause and a data-sharing
13621 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013622
Samuel Antao5de996e2016-01-22 20:21:36 +000013623 // Check conflicts with other map clause expressions. We check the conflicts
13624 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013625 // environment, because the restrictions are different. We only have to
13626 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013627 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013628 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013629 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013630 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013631 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013632 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013633 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013634
Samuel Antao661c0902016-05-26 17:39:58 +000013635 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013636 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13637 // If the type of a list item is a reference to a type T then the type will
13638 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013639 auto I = llvm::find_if(
13640 CurComponents,
13641 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13642 return MC.getAssociatedDeclaration();
13643 });
13644 assert(I != CurComponents.end() && "Null decl on map clause.");
13645 QualType Type =
13646 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013647
Samuel Antao661c0902016-05-26 17:39:58 +000013648 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13649 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013650 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013651 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013652 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013653 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013654 continue;
13655
Samuel Antao661c0902016-05-26 17:39:58 +000013656 if (CKind == OMPC_map) {
13657 // target enter data
13658 // OpenMP [2.10.2, Restrictions, p. 99]
13659 // A map-type must be specified in all map clauses and must be either
13660 // to or alloc.
13661 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13662 if (DKind == OMPD_target_enter_data &&
13663 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13664 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13665 << (IsMapTypeImplicit ? 1 : 0)
13666 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13667 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013668 continue;
13669 }
Samuel Antao661c0902016-05-26 17:39:58 +000013670
13671 // target exit_data
13672 // OpenMP [2.10.3, Restrictions, p. 102]
13673 // A map-type must be specified in all map clauses and must be either
13674 // from, release, or delete.
13675 if (DKind == OMPD_target_exit_data &&
13676 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13677 MapType == OMPC_MAP_delete)) {
13678 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13679 << (IsMapTypeImplicit ? 1 : 0)
13680 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13681 << getOpenMPDirectiveName(DKind);
13682 continue;
13683 }
13684
13685 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13686 // A list item cannot appear in both a map clause and a data-sharing
13687 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013688 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13689 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013690 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013691 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013692 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013693 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013694 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013695 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013696 continue;
13697 }
13698 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013699 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013700
Michael Kruse01f670d2019-02-22 22:29:42 +000013701 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013702 ExprResult ER = buildUserDefinedMapperRef(
13703 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13704 Type.getCanonicalType(), UnresolvedMapper);
13705 if (ER.isInvalid())
13706 continue;
13707 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013708
Samuel Antao90927002016-04-26 14:54:23 +000013709 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013710 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013711
13712 // Store the components in the stack so that they can be used to check
13713 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013714 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13715 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013716
13717 // Save the components and declaration to create the clause. For purposes of
13718 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013719 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013720 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13721 MVLI.VarComponents.back().append(CurComponents.begin(),
13722 CurComponents.end());
13723 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13724 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013725 }
Samuel Antao661c0902016-05-26 17:39:58 +000013726}
13727
Michael Kruse4304e9d2019-02-19 16:38:20 +000013728OMPClause *Sema::ActOnOpenMPMapClause(
13729 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13730 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13731 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13732 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13733 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13734 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13735 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13736 OMPC_MAP_MODIFIER_unknown,
13737 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013738 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13739
13740 // Process map-type-modifiers, flag errors for duplicate modifiers.
13741 unsigned Count = 0;
13742 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13743 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13744 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13745 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13746 continue;
13747 }
13748 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013749 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013750 Modifiers[Count] = MapTypeModifiers[I];
13751 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13752 ++Count;
13753 }
13754
Michael Kruse4304e9d2019-02-19 16:38:20 +000013755 MappableVarListInfo MVLI(VarList);
13756 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013757 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13758 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013759
Samuel Antao5de996e2016-01-22 20:21:36 +000013760 // We need to produce a map clause even if we don't have variables so that
13761 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013762 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13763 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13764 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13765 MapperIdScopeSpec.getWithLocInContext(Context),
13766 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013767}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013768
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013769QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13770 TypeResult ParsedType) {
13771 assert(ParsedType.isUsable());
13772
13773 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13774 if (ReductionType.isNull())
13775 return QualType();
13776
13777 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13778 // A type name in a declare reduction directive cannot be a function type, an
13779 // array type, a reference type, or a type qualified with const, volatile or
13780 // restrict.
13781 if (ReductionType.hasQualifiers()) {
13782 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13783 return QualType();
13784 }
13785
13786 if (ReductionType->isFunctionType()) {
13787 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13788 return QualType();
13789 }
13790 if (ReductionType->isReferenceType()) {
13791 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13792 return QualType();
13793 }
13794 if (ReductionType->isArrayType()) {
13795 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13796 return QualType();
13797 }
13798 return ReductionType;
13799}
13800
13801Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13802 Scope *S, DeclContext *DC, DeclarationName Name,
13803 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13804 AccessSpecifier AS, Decl *PrevDeclInScope) {
13805 SmallVector<Decl *, 8> Decls;
13806 Decls.reserve(ReductionTypes.size());
13807
13808 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013809 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013810 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13811 // A reduction-identifier may not be re-declared in the current scope for the
13812 // same type or for a type that is compatible according to the base language
13813 // rules.
13814 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13815 OMPDeclareReductionDecl *PrevDRD = nullptr;
13816 bool InCompoundScope = true;
13817 if (S != nullptr) {
13818 // Find previous declaration with the same name not referenced in other
13819 // declarations.
13820 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13821 InCompoundScope =
13822 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13823 LookupName(Lookup, S);
13824 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13825 /*AllowInlineNamespace=*/false);
13826 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013827 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013828 while (Filter.hasNext()) {
13829 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13830 if (InCompoundScope) {
13831 auto I = UsedAsPrevious.find(PrevDecl);
13832 if (I == UsedAsPrevious.end())
13833 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013834 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013835 UsedAsPrevious[D] = true;
13836 }
13837 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13838 PrevDecl->getLocation();
13839 }
13840 Filter.done();
13841 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013842 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013843 if (!PrevData.second) {
13844 PrevDRD = PrevData.first;
13845 break;
13846 }
13847 }
13848 }
13849 } else if (PrevDeclInScope != nullptr) {
13850 auto *PrevDRDInScope = PrevDRD =
13851 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13852 do {
13853 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13854 PrevDRDInScope->getLocation();
13855 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13856 } while (PrevDRDInScope != nullptr);
13857 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013858 for (const auto &TyData : ReductionTypes) {
13859 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013860 bool Invalid = false;
13861 if (I != PreviousRedeclTypes.end()) {
13862 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13863 << TyData.first;
13864 Diag(I->second, diag::note_previous_definition);
13865 Invalid = true;
13866 }
13867 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13868 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13869 Name, TyData.first, PrevDRD);
13870 DC->addDecl(DRD);
13871 DRD->setAccess(AS);
13872 Decls.push_back(DRD);
13873 if (Invalid)
13874 DRD->setInvalidDecl();
13875 else
13876 PrevDRD = DRD;
13877 }
13878
13879 return DeclGroupPtrTy::make(
13880 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13881}
13882
13883void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13884 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13885
13886 // Enter new function scope.
13887 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013888 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013889 getCurFunction()->setHasOMPDeclareReductionCombiner();
13890
13891 if (S != nullptr)
13892 PushDeclContext(S, DRD);
13893 else
13894 CurContext = DRD;
13895
Faisal Valid143a0c2017-04-01 21:30:49 +000013896 PushExpressionEvaluationContext(
13897 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013898
13899 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013900 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13901 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13902 // uses semantics of argument handles by value, but it should be passed by
13903 // reference. C lang does not support references, so pass all parameters as
13904 // pointers.
13905 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013906 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013907 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013908 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13909 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13910 // uses semantics of argument handles by value, but it should be passed by
13911 // reference. C lang does not support references, so pass all parameters as
13912 // pointers.
13913 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013914 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013915 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13916 if (S != nullptr) {
13917 PushOnScopeChains(OmpInParm, S);
13918 PushOnScopeChains(OmpOutParm, S);
13919 } else {
13920 DRD->addDecl(OmpInParm);
13921 DRD->addDecl(OmpOutParm);
13922 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013923 Expr *InE =
13924 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13925 Expr *OutE =
13926 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13927 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013928}
13929
13930void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13931 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13932 DiscardCleanupsInEvaluationContext();
13933 PopExpressionEvaluationContext();
13934
13935 PopDeclContext();
13936 PopFunctionScopeInfo();
13937
13938 if (Combiner != nullptr)
13939 DRD->setCombiner(Combiner);
13940 else
13941 DRD->setInvalidDecl();
13942}
13943
Alexey Bataev070f43a2017-09-06 14:49:58 +000013944VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013945 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13946
13947 // Enter new function scope.
13948 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013949 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013950
13951 if (S != nullptr)
13952 PushDeclContext(S, DRD);
13953 else
13954 CurContext = DRD;
13955
Faisal Valid143a0c2017-04-01 21:30:49 +000013956 PushExpressionEvaluationContext(
13957 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013958
13959 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013960 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13961 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13962 // uses semantics of argument handles by value, but it should be passed by
13963 // reference. C lang does not support references, so pass all parameters as
13964 // pointers.
13965 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013966 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013967 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013968 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13969 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13970 // uses semantics of argument handles by value, but it should be passed by
13971 // reference. C lang does not support references, so pass all parameters as
13972 // pointers.
13973 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013974 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013975 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013976 if (S != nullptr) {
13977 PushOnScopeChains(OmpPrivParm, S);
13978 PushOnScopeChains(OmpOrigParm, S);
13979 } else {
13980 DRD->addDecl(OmpPrivParm);
13981 DRD->addDecl(OmpOrigParm);
13982 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013983 Expr *OrigE =
13984 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13985 Expr *PrivE =
13986 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13987 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013988 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013989}
13990
Alexey Bataev070f43a2017-09-06 14:49:58 +000013991void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13992 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013993 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13994 DiscardCleanupsInEvaluationContext();
13995 PopExpressionEvaluationContext();
13996
13997 PopDeclContext();
13998 PopFunctionScopeInfo();
13999
Alexey Bataev070f43a2017-09-06 14:49:58 +000014000 if (Initializer != nullptr) {
14001 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14002 } else if (OmpPrivParm->hasInit()) {
14003 DRD->setInitializer(OmpPrivParm->getInit(),
14004 OmpPrivParm->isDirectInit()
14005 ? OMPDeclareReductionDecl::DirectInit
14006 : OMPDeclareReductionDecl::CopyInit);
14007 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014008 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000014009 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014010}
14011
14012Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14013 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014014 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014015 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014016 if (S)
14017 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14018 /*AddToContext=*/false);
14019 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014020 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014021 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014022 }
14023 return DeclReductions;
14024}
14025
Michael Kruse251e1482019-02-01 20:25:04 +000014026TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14027 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14028 QualType T = TInfo->getType();
14029 if (D.isInvalidType())
14030 return true;
14031
14032 if (getLangOpts().CPlusPlus) {
14033 // Check that there are no default arguments (C++ only).
14034 CheckExtraCXXDefaultArguments(D);
14035 }
14036
14037 return CreateParsedType(T, TInfo);
14038}
14039
14040QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14041 TypeResult ParsedType) {
14042 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14043
14044 QualType MapperType = GetTypeFromParser(ParsedType.get());
14045 assert(!MapperType.isNull() && "Expect valid mapper type");
14046
14047 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14048 // The type must be of struct, union or class type in C and C++
14049 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14050 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14051 return QualType();
14052 }
14053 return MapperType;
14054}
14055
14056OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14057 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14058 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14059 Decl *PrevDeclInScope) {
14060 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14061 forRedeclarationInCurContext());
14062 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14063 // A mapper-identifier may not be redeclared in the current scope for the
14064 // same type or for a type that is compatible according to the base language
14065 // rules.
14066 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14067 OMPDeclareMapperDecl *PrevDMD = nullptr;
14068 bool InCompoundScope = true;
14069 if (S != nullptr) {
14070 // Find previous declaration with the same name not referenced in other
14071 // declarations.
14072 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14073 InCompoundScope =
14074 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14075 LookupName(Lookup, S);
14076 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14077 /*AllowInlineNamespace=*/false);
14078 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14079 LookupResult::Filter Filter = Lookup.makeFilter();
14080 while (Filter.hasNext()) {
14081 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14082 if (InCompoundScope) {
14083 auto I = UsedAsPrevious.find(PrevDecl);
14084 if (I == UsedAsPrevious.end())
14085 UsedAsPrevious[PrevDecl] = false;
14086 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14087 UsedAsPrevious[D] = true;
14088 }
14089 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14090 PrevDecl->getLocation();
14091 }
14092 Filter.done();
14093 if (InCompoundScope) {
14094 for (const auto &PrevData : UsedAsPrevious) {
14095 if (!PrevData.second) {
14096 PrevDMD = PrevData.first;
14097 break;
14098 }
14099 }
14100 }
14101 } else if (PrevDeclInScope) {
14102 auto *PrevDMDInScope = PrevDMD =
14103 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14104 do {
14105 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14106 PrevDMDInScope->getLocation();
14107 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14108 } while (PrevDMDInScope != nullptr);
14109 }
14110 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14111 bool Invalid = false;
14112 if (I != PreviousRedeclTypes.end()) {
14113 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14114 << MapperType << Name;
14115 Diag(I->second, diag::note_previous_definition);
14116 Invalid = true;
14117 }
14118 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14119 MapperType, VN, PrevDMD);
14120 DC->addDecl(DMD);
14121 DMD->setAccess(AS);
14122 if (Invalid)
14123 DMD->setInvalidDecl();
14124
14125 // Enter new function scope.
14126 PushFunctionScope();
14127 setFunctionHasBranchProtectedScope();
14128
14129 CurContext = DMD;
14130
14131 return DMD;
14132}
14133
14134void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14135 Scope *S,
14136 QualType MapperType,
14137 SourceLocation StartLoc,
14138 DeclarationName VN) {
14139 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14140 if (S)
14141 PushOnScopeChains(VD, S);
14142 else
14143 DMD->addDecl(VD);
14144 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14145 DMD->setMapperVarRef(MapperVarRefExpr);
14146}
14147
14148Sema::DeclGroupPtrTy
14149Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14150 ArrayRef<OMPClause *> ClauseList) {
14151 PopDeclContext();
14152 PopFunctionScopeInfo();
14153
14154 if (D) {
14155 if (S)
14156 PushOnScopeChains(D, S, /*AddToContext=*/false);
14157 D->CreateClauses(Context, ClauseList);
14158 }
14159
14160 return DeclGroupPtrTy::make(DeclGroupRef(D));
14161}
14162
David Majnemer9d168222016-08-05 17:44:54 +000014163OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014164 SourceLocation StartLoc,
14165 SourceLocation LParenLoc,
14166 SourceLocation EndLoc) {
14167 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014168 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014169
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014170 // OpenMP [teams Constrcut, Restrictions]
14171 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014172 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014173 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014174 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014175
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014176 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014177 OpenMPDirectiveKind CaptureRegion =
14178 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14179 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014180 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014181 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014182 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14183 HelperValStmt = buildPreInits(Context, Captures);
14184 }
14185
14186 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14187 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014188}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014189
14190OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14191 SourceLocation StartLoc,
14192 SourceLocation LParenLoc,
14193 SourceLocation EndLoc) {
14194 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014195 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014196
14197 // OpenMP [teams Constrcut, Restrictions]
14198 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014199 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014200 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014201 return nullptr;
14202
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014203 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014204 OpenMPDirectiveKind CaptureRegion =
14205 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14206 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014207 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014208 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014209 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14210 HelperValStmt = buildPreInits(Context, Captures);
14211 }
14212
14213 return new (Context) OMPThreadLimitClause(
14214 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014215}
Alexey Bataeva0569352015-12-01 10:17:31 +000014216
14217OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14218 SourceLocation StartLoc,
14219 SourceLocation LParenLoc,
14220 SourceLocation EndLoc) {
14221 Expr *ValExpr = Priority;
14222
14223 // OpenMP [2.9.1, task Constrcut]
14224 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014225 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014226 /*StrictlyPositive=*/false))
14227 return nullptr;
14228
14229 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14230}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014231
14232OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14233 SourceLocation StartLoc,
14234 SourceLocation LParenLoc,
14235 SourceLocation EndLoc) {
14236 Expr *ValExpr = Grainsize;
14237
14238 // OpenMP [2.9.2, taskloop Constrcut]
14239 // The parameter of the grainsize clause must be a positive integer
14240 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014241 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014242 /*StrictlyPositive=*/true))
14243 return nullptr;
14244
14245 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14246}
Alexey Bataev382967a2015-12-08 12:06:20 +000014247
14248OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14249 SourceLocation StartLoc,
14250 SourceLocation LParenLoc,
14251 SourceLocation EndLoc) {
14252 Expr *ValExpr = NumTasks;
14253
14254 // OpenMP [2.9.2, taskloop Constrcut]
14255 // The parameter of the num_tasks clause must be a positive integer
14256 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014257 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014258 /*StrictlyPositive=*/true))
14259 return nullptr;
14260
14261 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14262}
14263
Alexey Bataev28c75412015-12-15 08:19:24 +000014264OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14265 SourceLocation LParenLoc,
14266 SourceLocation EndLoc) {
14267 // OpenMP [2.13.2, critical construct, Description]
14268 // ... where hint-expression is an integer constant expression that evaluates
14269 // to a valid lock hint.
14270 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14271 if (HintExpr.isInvalid())
14272 return nullptr;
14273 return new (Context)
14274 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14275}
14276
Carlo Bertollib4adf552016-01-15 18:50:31 +000014277OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14278 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14279 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14280 SourceLocation EndLoc) {
14281 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14282 std::string Values;
14283 Values += "'";
14284 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14285 Values += "'";
14286 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14287 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14288 return nullptr;
14289 }
14290 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014291 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014292 if (ChunkSize) {
14293 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14294 !ChunkSize->isInstantiationDependent() &&
14295 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014296 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014297 ExprResult Val =
14298 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14299 if (Val.isInvalid())
14300 return nullptr;
14301
14302 ValExpr = Val.get();
14303
14304 // OpenMP [2.7.1, Restrictions]
14305 // chunk_size must be a loop invariant integer expression with a positive
14306 // value.
14307 llvm::APSInt Result;
14308 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14309 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14310 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14311 << "dist_schedule" << ChunkSize->getSourceRange();
14312 return nullptr;
14313 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014314 } else if (getOpenMPCaptureRegionForClause(
14315 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14316 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014317 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014318 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014319 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014320 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14321 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014322 }
14323 }
14324 }
14325
14326 return new (Context)
14327 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014328 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014329}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014330
14331OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14332 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14333 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14334 SourceLocation KindLoc, SourceLocation EndLoc) {
14335 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014336 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014337 std::string Value;
14338 SourceLocation Loc;
14339 Value += "'";
14340 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14341 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014342 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014343 Loc = MLoc;
14344 } else {
14345 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014346 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014347 Loc = KindLoc;
14348 }
14349 Value += "'";
14350 Diag(Loc, diag::err_omp_unexpected_clause_value)
14351 << Value << getOpenMPClauseName(OMPC_defaultmap);
14352 return nullptr;
14353 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014354 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014355
14356 return new (Context)
14357 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14358}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014359
14360bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14361 DeclContext *CurLexicalContext = getCurLexicalContext();
14362 if (!CurLexicalContext->isFileContext() &&
14363 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014364 !CurLexicalContext->isExternCXXContext() &&
14365 !isa<CXXRecordDecl>(CurLexicalContext) &&
14366 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14367 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14368 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014369 Diag(Loc, diag::err_omp_region_not_file_context);
14370 return false;
14371 }
Kelvin Libc38e632018-09-10 02:07:09 +000014372 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014373 return true;
14374}
14375
14376void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014377 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014378 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014379 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014380}
14381
David Majnemer9d168222016-08-05 17:44:54 +000014382void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14383 CXXScopeSpec &ScopeSpec,
14384 const DeclarationNameInfo &Id,
14385 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14386 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014387 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14388 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14389
14390 if (Lookup.isAmbiguous())
14391 return;
14392 Lookup.suppressDiagnostics();
14393
14394 if (!Lookup.isSingleResult()) {
14395 if (TypoCorrection Corrected =
14396 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14397 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14398 CTK_ErrorRecovery)) {
14399 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14400 << Id.getName());
14401 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14402 return;
14403 }
14404
14405 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14406 return;
14407 }
14408
14409 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014410 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14411 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014412 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14413 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014414 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14415 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14416 cast<ValueDecl>(ND));
14417 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014418 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014419 ND->addAttr(A);
14420 if (ASTMutationListener *ML = Context.getASTMutationListener())
14421 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014422 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014423 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014424 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14425 << Id.getName();
14426 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014427 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014428 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014429 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014430}
14431
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014432static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14433 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014434 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014435 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014436 auto *VD = cast<VarDecl>(D);
14437 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14438 return;
14439 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14440 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014441}
14442
14443static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14444 Sema &SemaRef, DSAStackTy *Stack,
14445 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014446 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14447 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14448 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014449}
14450
Kelvin Li1ce87c72017-12-12 20:08:12 +000014451void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14452 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014453 if (!D || D->isInvalidDecl())
14454 return;
14455 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014456 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014457 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014458 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014459 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14460 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014461 return;
14462 // 2.10.6: threadprivate variable cannot appear in a declare target
14463 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014464 if (DSAStack->isThreadPrivate(VD)) {
14465 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014466 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014467 return;
14468 }
14469 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014470 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14471 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014472 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014473 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14474 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14475 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014476 assert(IdLoc.isValid() && "Source location is expected");
14477 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14478 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14479 return;
14480 }
14481 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014482 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14483 // Problem if any with var declared with incomplete type will be reported
14484 // as normal, so no need to check it here.
14485 if ((E || !VD->getType()->isIncompleteType()) &&
14486 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14487 return;
14488 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14489 // Checking declaration inside declare target region.
14490 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14491 isa<FunctionTemplateDecl>(D)) {
14492 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14493 Context, OMPDeclareTargetDeclAttr::MT_To);
14494 D->addAttr(A);
14495 if (ASTMutationListener *ML = Context.getASTMutationListener())
14496 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14497 }
14498 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014499 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014500 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014501 if (!E)
14502 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014503 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14504}
Samuel Antao661c0902016-05-26 17:39:58 +000014505
14506OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014507 CXXScopeSpec &MapperIdScopeSpec,
14508 DeclarationNameInfo &MapperId,
14509 const OMPVarListLocTy &Locs,
14510 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014511 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014512 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14513 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014514 if (MVLI.ProcessedVarList.empty())
14515 return nullptr;
14516
Michael Kruse01f670d2019-02-22 22:29:42 +000014517 return OMPToClause::Create(
14518 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14519 MVLI.VarComponents, MVLI.UDMapperList,
14520 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014521}
Samuel Antaoec172c62016-05-26 17:49:04 +000014522
14523OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014524 CXXScopeSpec &MapperIdScopeSpec,
14525 DeclarationNameInfo &MapperId,
14526 const OMPVarListLocTy &Locs,
14527 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014528 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014529 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14530 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014531 if (MVLI.ProcessedVarList.empty())
14532 return nullptr;
14533
Michael Kruse0336c752019-02-25 20:34:15 +000014534 return OMPFromClause::Create(
14535 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14536 MVLI.VarComponents, MVLI.UDMapperList,
14537 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014538}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014539
14540OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014541 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014542 MappableVarListInfo MVLI(VarList);
14543 SmallVector<Expr *, 8> PrivateCopies;
14544 SmallVector<Expr *, 8> Inits;
14545
Alexey Bataeve3727102018-04-18 15:57:46 +000014546 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014547 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14548 SourceLocation ELoc;
14549 SourceRange ERange;
14550 Expr *SimpleRefExpr = RefExpr;
14551 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14552 if (Res.second) {
14553 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014554 MVLI.ProcessedVarList.push_back(RefExpr);
14555 PrivateCopies.push_back(nullptr);
14556 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014557 }
14558 ValueDecl *D = Res.first;
14559 if (!D)
14560 continue;
14561
14562 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014563 Type = Type.getNonReferenceType().getUnqualifiedType();
14564
14565 auto *VD = dyn_cast<VarDecl>(D);
14566
14567 // Item should be a pointer or reference to pointer.
14568 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014569 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14570 << 0 << RefExpr->getSourceRange();
14571 continue;
14572 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014573
14574 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014575 auto VDPrivate =
14576 buildVarDecl(*this, ELoc, Type, D->getName(),
14577 D->hasAttrs() ? &D->getAttrs() : nullptr,
14578 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014579 if (VDPrivate->isInvalidDecl())
14580 continue;
14581
14582 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014583 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014584 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14585
14586 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014587 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014588 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014589 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14590 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014591 AddInitializerToDecl(VDPrivate,
14592 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014593 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014594
14595 // If required, build a capture to implement the privatization initialized
14596 // with the current list item value.
14597 DeclRefExpr *Ref = nullptr;
14598 if (!VD)
14599 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14600 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14601 PrivateCopies.push_back(VDPrivateRefExpr);
14602 Inits.push_back(VDInitRefExpr);
14603
14604 // We need to add a data sharing attribute for this variable to make sure it
14605 // is correctly captured. A variable that shows up in a use_device_ptr has
14606 // similar properties of a first private variable.
14607 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14608
14609 // Create a mappable component for the list item. List items in this clause
14610 // only need a component.
14611 MVLI.VarBaseDeclarations.push_back(D);
14612 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14613 MVLI.VarComponents.back().push_back(
14614 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014615 }
14616
Samuel Antaocc10b852016-07-28 14:23:26 +000014617 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014618 return nullptr;
14619
Samuel Antaocc10b852016-07-28 14:23:26 +000014620 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014621 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14622 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014623}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014624
14625OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014626 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014627 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014628 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014629 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014630 SourceLocation ELoc;
14631 SourceRange ERange;
14632 Expr *SimpleRefExpr = RefExpr;
14633 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14634 if (Res.second) {
14635 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014636 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014637 }
14638 ValueDecl *D = Res.first;
14639 if (!D)
14640 continue;
14641
14642 QualType Type = D->getType();
14643 // item should be a pointer or array or reference to pointer or array
14644 if (!Type.getNonReferenceType()->isPointerType() &&
14645 !Type.getNonReferenceType()->isArrayType()) {
14646 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14647 << 0 << RefExpr->getSourceRange();
14648 continue;
14649 }
Samuel Antao6890b092016-07-28 14:25:09 +000014650
14651 // Check if the declaration in the clause does not show up in any data
14652 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014653 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014654 if (isOpenMPPrivate(DVar.CKind)) {
14655 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14656 << getOpenMPClauseName(DVar.CKind)
14657 << getOpenMPClauseName(OMPC_is_device_ptr)
14658 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014659 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014660 continue;
14661 }
14662
Alexey Bataeve3727102018-04-18 15:57:46 +000014663 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014664 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014665 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014666 [&ConflictExpr](
14667 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14668 OpenMPClauseKind) -> bool {
14669 ConflictExpr = R.front().getAssociatedExpression();
14670 return true;
14671 })) {
14672 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14673 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14674 << ConflictExpr->getSourceRange();
14675 continue;
14676 }
14677
14678 // Store the components in the stack so that they can be used to check
14679 // against other clauses later on.
14680 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14681 DSAStack->addMappableExpressionComponents(
14682 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14683
14684 // Record the expression we've just processed.
14685 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14686
14687 // Create a mappable component for the list item. List items in this clause
14688 // only need a component. We use a null declaration to signal fields in
14689 // 'this'.
14690 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14691 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14692 "Unexpected device pointer expression!");
14693 MVLI.VarBaseDeclarations.push_back(
14694 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14695 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14696 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014697 }
14698
Samuel Antao6890b092016-07-28 14:25:09 +000014699 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014700 return nullptr;
14701
Michael Kruse4304e9d2019-02-19 16:38:20 +000014702 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14703 MVLI.VarBaseDeclarations,
14704 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014705}