blob: 49c7c3aca1447d444697c7f8ead062577b4f1644 [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;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000142 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000143 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000144 bool NowaitRegion = false;
145 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000146 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000147 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000148 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000149 /// Reference to the taskgroup task_reduction reference expression.
150 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000151 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000152 /// List of globals marked as declare target link in this target region
153 /// (isOpenMPTargetExecutionDirective(Directive) == true).
154 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000155 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000156 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000157 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
158 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000159 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 };
161
Alexey Bataeve3727102018-04-18 15:57:46 +0000162 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000164 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000165 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000166 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
167 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000168 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000169 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000171 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000172 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000173 /// true if all the vaiables in the target executable directives must be
174 /// captured by reference.
175 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000176 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000177 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000178
Richard Smith375dec52019-05-30 23:21:14 +0000179 /// Iterators over the stack iterate in order from innermost to outermost
180 /// directive.
181 using const_iterator = StackTy::const_reverse_iterator;
182 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000183 return Stack.empty() ? const_iterator()
184 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000185 }
186 const_iterator end() const {
187 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
188 }
189 using iterator = StackTy::reverse_iterator;
190 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000191 return Stack.empty() ? iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000193 }
194 iterator end() {
195 return Stack.empty() ? iterator() : Stack.back().first.rend();
196 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197
Richard Smith375dec52019-05-30 23:21:14 +0000198 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000199
Alexey Bataev4b465392017-04-26 15:06:24 +0000200 bool isStackEmpty() const {
201 return Stack.empty() ||
202 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000203 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000204 }
Richard Smith375dec52019-05-30 23:21:14 +0000205 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000206 return isStackEmpty() ? 0
207 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000208 }
209
210 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000211 size_t Size = getStackSize();
212 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000213 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000214 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000215 }
216 const SharingMapTy *getTopOfStackOrNull() const {
217 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
218 }
219 SharingMapTy &getTopOfStack() {
220 assert(!isStackEmpty() && "no current directive");
221 return *getTopOfStackOrNull();
222 }
223 const SharingMapTy &getTopOfStack() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStack();
225 }
226
227 SharingMapTy *getSecondOnStackOrNull() {
228 size_t Size = getStackSize();
229 if (Size <= 1)
230 return nullptr;
231 return &Stack.back().first[Size - 2];
232 }
233 const SharingMapTy *getSecondOnStackOrNull() const {
234 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
235 }
236
237 /// Get the stack element at a certain level (previously returned by
238 /// \c getNestingLevel).
239 ///
240 /// Note that nesting levels count from outermost to innermost, and this is
241 /// the reverse of our iteration order where new inner levels are pushed at
242 /// the front of the stack.
243 SharingMapTy &getStackElemAtLevel(unsigned Level) {
244 assert(Level < getStackSize() && "no such stack element");
245 return Stack.back().first[Level];
246 }
247 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
248 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
249 }
250
251 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
252
253 /// Checks if the variable is a local for OpenMP region.
254 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000255
Kelvin Li1408f912018-09-26 04:28:39 +0000256 /// Vector of previously declared requires directives
257 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000258 /// omp_allocator_handle_t type.
259 QualType OMPAllocatorHandleT;
260 /// Expression for the predefined allocators.
261 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
262 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000263 /// Vector of previously encountered target directives
264 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000265
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000267 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000268
Alexey Bataev27ef9512019-03-20 20:14:22 +0000269 /// Sets omp_allocator_handle_t type.
270 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
271 /// Gets omp_allocator_handle_t type.
272 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
273 /// Sets the given default allocator.
274 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
275 Expr *Allocator) {
276 OMPPredefinedAllocators[AllocatorKind] = Allocator;
277 }
278 /// Returns the specified default allocator.
279 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
280 return OMPPredefinedAllocators[AllocatorKind];
281 }
282
Alexey Bataevaac108a2015-06-23 04:51:00 +0000283 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000284 OpenMPClauseKind getClauseParsingMode() const {
285 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
286 return ClauseKindMode;
287 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000288 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000289
Richard Smith0621a8f2019-05-31 00:45:10 +0000290 bool isBodyComplete() const {
291 const SharingMapTy *Top = getTopOfStackOrNull();
292 return Top && Top->BodyComplete;
293 }
294 void setBodyComplete() {
295 getTopOfStack().BodyComplete = true;
296 }
297
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000298 bool isForceVarCapturing() const { return ForceCapturing; }
299 void setForceVarCapturing(bool V) { ForceCapturing = V; }
300
Alexey Bataev60705422018-10-30 15:50:12 +0000301 void setForceCaptureByReferenceInTargetExecutable(bool V) {
302 ForceCaptureByReferenceInTargetExecutable = V;
303 }
304 bool isForceCaptureByReferenceInTargetExecutable() const {
305 return ForceCaptureByReferenceInTargetExecutable;
306 }
307
Alexey Bataev758e55e2013-09-06 18:03:48 +0000308 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000309 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000310 assert(!IgnoredStackElements &&
311 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000312 if (Stack.empty() ||
313 Stack.back().second != CurrentNonCapturingFunctionScope)
314 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
315 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
316 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000317 }
318
319 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000320 assert(!IgnoredStackElements &&
321 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000322 assert(!Stack.back().first.empty() &&
323 "Data-sharing attributes stack is empty!");
324 Stack.back().first.pop_back();
325 }
326
Richard Smith0621a8f2019-05-31 00:45:10 +0000327 /// RAII object to temporarily leave the scope of a directive when we want to
328 /// logically operate in its parent.
329 class ParentDirectiveScope {
330 DSAStackTy &Self;
331 bool Active;
332 public:
333 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
334 : Self(Self), Active(false) {
335 if (Activate)
336 enable();
337 }
338 ~ParentDirectiveScope() { disable(); }
339 void disable() {
340 if (Active) {
341 --Self.IgnoredStackElements;
342 Active = false;
343 }
344 }
345 void enable() {
346 if (!Active) {
347 ++Self.IgnoredStackElements;
348 Active = true;
349 }
350 }
351 };
352
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000353 /// Marks that we're started loop parsing.
354 void loopInit() {
355 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
356 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000357 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000358 }
359 /// Start capturing of the variables in the loop context.
360 void loopStart() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
362 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000363 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000364 }
365 /// true, if variables are captured, false otherwise.
366 bool isLoopStarted() const {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
368 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000369 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000370 }
371 /// Marks (or clears) declaration as possibly loop counter.
372 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000373 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000374 D ? D->getCanonicalDecl() : D;
375 }
376 /// Gets the possible loop counter decl.
377 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000378 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000379 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 /// Start new OpenMP region stack in new non-capturing function.
381 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000382 assert(!IgnoredStackElements &&
383 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
385 assert(!isa<CapturingScopeInfo>(CurFnScope));
386 CurrentNonCapturingFunctionScope = CurFnScope;
387 }
388 /// Pop region stack for non-capturing function.
389 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000390 assert(!IgnoredStackElements &&
391 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000392 if (!Stack.empty() && Stack.back().second == OldFSI) {
393 assert(Stack.back().first.empty());
394 Stack.pop_back();
395 }
396 CurrentNonCapturingFunctionScope = nullptr;
397 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
398 if (!isa<CapturingScopeInfo>(FSI)) {
399 CurrentNonCapturingFunctionScope = FSI;
400 break;
401 }
402 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000403 }
404
Alexey Bataeve3727102018-04-18 15:57:46 +0000405 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000406 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000407 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000408 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000409 getCriticalWithHint(const DeclarationNameInfo &Name) const {
410 auto I = Criticals.find(Name.getAsString());
411 if (I != Criticals.end())
412 return I->second;
413 return std::make_pair(nullptr, llvm::APSInt());
414 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000416 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000417 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000418 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000420 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000421 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000423 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000424 /// \return The index of the loop control variable in the list of associated
425 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000426 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000427 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000428 /// parent region.
429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000431 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000433 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000434 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000437 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000438 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439
Alexey Bataevfa312f32017-07-21 18:48:21 +0000440 /// Adds additional information for the reduction items with the reduction id
441 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000442 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000443 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000444 /// Adds additional information for the reduction items with the reduction id
445 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000446 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000447 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000448 /// Returns the location and reduction operation from the innermost parent
449 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000450 const DSAVarData
451 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
452 BinaryOperatorKind &BOK,
453 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000454 /// Returns the location and reduction operation from the innermost parent
455 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000456 const DSAVarData
457 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
458 const Expr *&ReductionRef,
459 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000460 /// Return reduction reference expression for the current taskgroup.
461 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000462 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000463 "taskgroup reference expression requested for non taskgroup "
464 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000465 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000466 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000467 /// Checks if the given \p VD declaration is actually a taskgroup reduction
468 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000469 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000470 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
471 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000472 ->getDecl() == VD;
473 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000474
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000475 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000476 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000477 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000478 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000479 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000480 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000481 /// match specified \a CPred predicate in any directive which matches \a DPred
482 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000483 const DSAVarData
484 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
485 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
486 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000488 /// match specified \a CPred predicate in any innermost directive which
489 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000490 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000491 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000492 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
493 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000494 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000496 /// attributes which match specified \a CPred predicate at the specified
497 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000498 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000499 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000500 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000502 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000503 /// specified \a DPred predicate.
504 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000506 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000509 bool hasDirective(
510 const llvm::function_ref<bool(
511 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
512 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000513 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000517 const SharingMapTy *Top = getTopOfStackOrNull();
518 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000521 OpenMPDirectiveKind getDirective(unsigned Level) const {
522 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000523 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000524 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000526 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000527 const SharingMapTy *Parent = getSecondOnStackOrNull();
528 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000529 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000530
Kelvin Li1408f912018-09-26 04:28:39 +0000531 /// Add requires decl to internal vector
532 void addRequiresDecl(OMPRequiresDecl *RD) {
533 RequiresDecls.push_back(RD);
534 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000535
Alexey Bataev318f431b2019-03-22 15:25:12 +0000536 /// Checks if the defined 'requires' directive has specified type of clause.
537 template <typename ClauseType>
538 bool hasRequiresDeclWithClause() {
539 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
540 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
541 return isa<ClauseType>(C);
542 });
543 });
544 }
545
Kelvin Li1408f912018-09-26 04:28:39 +0000546 /// Checks for a duplicate clause amongst previously declared requires
547 /// directives
548 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
549 bool IsDuplicate = false;
550 for (OMPClause *CNew : ClauseList) {
551 for (const OMPRequiresDecl *D : RequiresDecls) {
552 for (const OMPClause *CPrev : D->clauselists()) {
553 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
554 SemaRef.Diag(CNew->getBeginLoc(),
555 diag::err_omp_requires_clause_redeclaration)
556 << getOpenMPClauseName(CNew->getClauseKind());
557 SemaRef.Diag(CPrev->getBeginLoc(),
558 diag::note_omp_requires_previous_clause)
559 << getOpenMPClauseName(CPrev->getClauseKind());
560 IsDuplicate = true;
561 }
562 }
563 }
564 }
565 return IsDuplicate;
566 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000567
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000568 /// Add location of previously encountered target to internal vector
569 void addTargetDirLocation(SourceLocation LocStart) {
570 TargetLocations.push_back(LocStart);
571 }
572
573 // Return previously encountered target region locations.
574 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
575 return TargetLocations;
576 }
577
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000578 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000579 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000580 getTopOfStack().DefaultAttr = DSA_none;
581 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000582 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000583 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000584 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000585 getTopOfStack().DefaultAttr = DSA_shared;
586 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000587 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000588 /// Set default data mapping attribute to 'tofrom:scalar'.
589 void setDefaultDMAToFromScalar(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000590 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
591 getTopOfStack().DefaultMapAttrLoc = Loc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000592 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000593
594 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000595 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000596 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000597 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000598 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000599 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000600 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000601 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000602 DefaultMapAttributes getDefaultDMA() const {
603 return isStackEmpty() ? DMA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000604 : getTopOfStack().DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000605 }
606 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000607 return getStackElemAtLevel(Level).DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000608 }
609 SourceLocation getDefaultDMALocation() const {
610 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000611 : getTopOfStack().DefaultMapAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000612 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000613
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000614 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000615 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000616 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000617 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000618 }
619
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000620 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000621 void setOrderedRegion(bool IsOrdered, const Expr *Param,
622 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000623 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000624 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000625 else
Richard Smith375dec52019-05-30 23:21:14 +0000626 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000627 }
628 /// Returns true, if region is ordered (has associated 'ordered' clause),
629 /// false - otherwise.
630 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000631 if (const SharingMapTy *Top = getTopOfStackOrNull())
632 return Top->OrderedRegion.hasValue();
633 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000634 }
635 /// Returns optional parameter for the ordered region.
636 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000637 if (const SharingMapTy *Top = getTopOfStackOrNull())
638 if (Top->OrderedRegion.hasValue())
639 return Top->OrderedRegion.getValue();
640 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000641 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000642 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000643 /// 'ordered' clause), false - otherwise.
644 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000645 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
646 return Parent->OrderedRegion.hasValue();
647 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000648 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000649 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000650 std::pair<const Expr *, OMPOrderedClause *>
651 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000652 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
653 if (Parent->OrderedRegion.hasValue())
654 return Parent->OrderedRegion.getValue();
655 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000656 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000657 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000658 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000659 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000660 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000661 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000662 /// 'nowait' clause), false - otherwise.
663 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000664 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
665 return Parent->NowaitRegion;
666 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000667 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000668 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000669 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000670 if (SharingMapTy *Parent = getSecondOnStackOrNull())
671 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000672 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000673 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000674 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000675 const SharingMapTy *Top = getTopOfStackOrNull();
676 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000677 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000679 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000680 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000681 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000682 if (Val > 1)
683 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000684 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000685 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000686 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000687 const SharingMapTy *Top = getTopOfStackOrNull();
688 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000689 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000690 /// Returns true if the construct is associated with multiple loops.
691 bool hasMutipleLoops() const {
692 const SharingMapTy *Top = getTopOfStackOrNull();
693 return Top ? Top->HasMutipleLoops : false;
694 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000695
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000696 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000697 /// region.
698 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000699 if (SharingMapTy *Parent = getSecondOnStackOrNull())
700 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000701 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000702 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000703 bool hasInnerTeamsRegion() const {
704 return getInnerTeamsRegionLoc().isValid();
705 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000706 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000707 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000708 const SharingMapTy *Top = getTopOfStackOrNull();
709 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000710 }
711
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000712 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000713 const SharingMapTy *Top = getTopOfStackOrNull();
714 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000715 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000716 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000717 const SharingMapTy *Top = getTopOfStackOrNull();
718 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000719 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000720
Samuel Antao4c8035b2016-12-12 18:00:20 +0000721 /// Do the check specified in \a Check to all component lists and return true
722 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000723 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000724 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000725 const llvm::function_ref<
726 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000727 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000728 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000729 if (isStackEmpty())
730 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000731 auto SI = begin();
732 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000733
734 if (SI == SE)
735 return false;
736
Alexey Bataeve3727102018-04-18 15:57:46 +0000737 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000738 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000739 else
740 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000741
742 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000743 auto MI = SI->MappedExprComponents.find(VD);
744 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000745 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
746 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000747 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000748 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000749 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000750 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000751 }
752
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000753 /// Do the check specified in \a Check to all component lists at a given level
754 /// and return true if any issue is found.
755 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000756 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000757 const llvm::function_ref<
758 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000759 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000760 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000761 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000762 return false;
763
Richard Smith375dec52019-05-30 23:21:14 +0000764 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
765 auto MI = StackElem.MappedExprComponents.find(VD);
766 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000767 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
768 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000769 if (Check(L, MI->second.Kind))
770 return true;
771 return false;
772 }
773
Samuel Antao4c8035b2016-12-12 18:00:20 +0000774 /// Create a new mappable expression component list associated with a given
775 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000776 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000777 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000778 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
779 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000780 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000781 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000782 MEC.Components.resize(MEC.Components.size() + 1);
783 MEC.Components.back().append(Components.begin(), Components.end());
784 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000785 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000786
787 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000788 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000789 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000790 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000791 void addDoacrossDependClause(OMPDependClause *C,
792 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000793 SharingMapTy *Parent = getSecondOnStackOrNull();
794 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
795 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000796 }
797 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
798 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000799 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000800 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000801 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000802 return llvm::make_range(Ref.begin(), Ref.end());
803 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000804 return llvm::make_range(StackElem.DoacrossDepends.end(),
805 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000806 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000807
808 // Store types of classes which have been explicitly mapped
809 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000810 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000811 StackElem.MappedClassesQualTypes.insert(QT);
812 }
813
814 // Return set of mapped classes types
815 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000816 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000817 return StackElem.MappedClassesQualTypes.count(QT) != 0;
818 }
819
Alexey Bataeva495c642019-03-11 19:51:42 +0000820 /// Adds global declare target to the parent target region.
821 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
822 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
823 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
824 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000825 for (auto &Elem : *this) {
826 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
827 Elem.DeclareTargetLinkVarDecls.push_back(E);
828 return;
829 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000830 }
831 }
832
833 /// Returns the list of globals with declare target link if current directive
834 /// is target.
835 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
836 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
837 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000838 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000839 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000840};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000841
842bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
843 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
844}
845
846bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000847 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
848 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000849}
Alexey Bataeve3727102018-04-18 15:57:46 +0000850
Alexey Bataeved09d242014-05-28 05:53:51 +0000851} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000852
Alexey Bataeve3727102018-04-18 15:57:46 +0000853static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000854 if (const auto *FE = dyn_cast<FullExpr>(E))
855 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000856
Alexey Bataeve3727102018-04-18 15:57:46 +0000857 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000858 E = MTE->GetTemporaryExpr();
859
Alexey Bataeve3727102018-04-18 15:57:46 +0000860 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000861 E = Binder->getSubExpr();
862
Alexey Bataeve3727102018-04-18 15:57:46 +0000863 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000864 E = ICE->getSubExprAsWritten();
865 return E->IgnoreParens();
866}
867
Alexey Bataeve3727102018-04-18 15:57:46 +0000868static Expr *getExprAsWritten(Expr *E) {
869 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
870}
871
872static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
873 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
874 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000875 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000876 const auto *VD = dyn_cast<VarDecl>(D);
877 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000878 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000879 VD = VD->getCanonicalDecl();
880 D = VD;
881 } else {
882 assert(FD);
883 FD = FD->getCanonicalDecl();
884 D = FD;
885 }
886 return D;
887}
888
Alexey Bataeve3727102018-04-18 15:57:46 +0000889static ValueDecl *getCanonicalDecl(ValueDecl *D) {
890 return const_cast<ValueDecl *>(
891 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
892}
893
Richard Smith375dec52019-05-30 23:21:14 +0000894DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000895 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000896 D = getCanonicalDecl(D);
897 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000898 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000899 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000900 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000901 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
902 // in a region but not in construct]
903 // File-scope or namespace-scope variables referenced in called routines
904 // in the region are shared unless they appear in a threadprivate
905 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000906 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000907 DVar.CKind = OMPC_shared;
908
909 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
910 // in a region but not in construct]
911 // Variables with static storage duration that are declared in called
912 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000913 if (VD && VD->hasGlobalStorage())
914 DVar.CKind = OMPC_shared;
915
916 // Non-static data members are shared by default.
917 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000918 DVar.CKind = OMPC_shared;
919
Alexey Bataev758e55e2013-09-06 18:03:48 +0000920 return DVar;
921 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000922
Alexey Bataevec3da872014-01-31 05:15:34 +0000923 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
924 // in a Construct, C/C++, predetermined, p.1]
925 // Variables with automatic storage duration that are declared in a scope
926 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000927 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
928 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000929 DVar.CKind = OMPC_private;
930 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000931 }
932
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000933 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000934 // Explicitly specified attributes and local variables with predetermined
935 // attributes.
936 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000937 const DSAInfo &Data = Iter->SharingMap.lookup(D);
938 DVar.RefExpr = Data.RefExpr.getPointer();
939 DVar.PrivateCopy = Data.PrivateCopy;
940 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000941 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000942 return DVar;
943 }
944
945 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
946 // in a Construct, C/C++, implicitly determined, p.1]
947 // In a parallel or task construct, the data-sharing attributes of these
948 // variables are determined by the default clause, if present.
949 switch (Iter->DefaultAttr) {
950 case DSA_shared:
951 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000952 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000953 return DVar;
954 case DSA_none:
955 return DVar;
956 case DSA_unspecified:
957 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
958 // in a Construct, implicitly determined, p.2]
959 // In a parallel construct, if no default clause is present, these
960 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000961 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000962 if (isOpenMPParallelDirective(DVar.DKind) ||
963 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000964 DVar.CKind = OMPC_shared;
965 return DVar;
966 }
967
968 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
969 // in a Construct, implicitly determined, p.4]
970 // In a task construct, if no default clause is present, a variable that in
971 // the enclosing context is determined to be shared by all implicit tasks
972 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000973 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000974 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +0000975 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000976 do {
977 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000978 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000979 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000980 // In a task construct, if no default clause is present, a variable
981 // whose data-sharing attribute is not determined by the rules above is
982 // firstprivate.
983 DVarTemp = getDSA(I, D);
984 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000985 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000986 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987 return DVar;
988 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000989 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000990 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000991 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000992 return DVar;
993 }
994 }
995 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
996 // in a Construct, implicitly determined, p.3]
997 // For constructs other than task, if no default clause is present, these
998 // variables inherit their data-sharing attributes from the enclosing
999 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001000 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001001}
1002
Alexey Bataeve3727102018-04-18 15:57:46 +00001003const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1004 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001005 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001006 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001007 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001008 auto It = StackElem.AlignedMap.find(D);
1009 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001010 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001011 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001012 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001013 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001014 assert(It->second && "Unexpected nullptr expr in the aligned map");
1015 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001016}
1017
Alexey Bataeve3727102018-04-18 15:57:46 +00001018void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001019 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001020 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001021 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 StackElem.LCVMap.try_emplace(
1023 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001024}
1025
Alexey Bataeve3727102018-04-18 15:57:46 +00001026const DSAStackTy::LCDeclInfo
1027DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001028 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001029 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001030 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001031 auto It = StackElem.LCVMap.find(D);
1032 if (It != StackElem.LCVMap.end())
1033 return It->second;
1034 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001035}
1036
Alexey Bataeve3727102018-04-18 15:57:46 +00001037const DSAStackTy::LCDeclInfo
1038DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001039 const SharingMapTy *Parent = getSecondOnStackOrNull();
1040 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001041 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001042 auto It = Parent->LCVMap.find(D);
1043 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001044 return It->second;
1045 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001046}
1047
Alexey Bataeve3727102018-04-18 15:57:46 +00001048const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001049 const SharingMapTy *Parent = getSecondOnStackOrNull();
1050 assert(Parent && "Data-sharing attributes stack is empty");
1051 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001052 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001053 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001054 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001055 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001056 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001057}
1058
Alexey Bataeve3727102018-04-18 15:57:46 +00001059void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001060 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001061 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001062 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001063 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001064 Data.Attributes = A;
1065 Data.RefExpr.setPointer(E);
1066 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001067 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001068 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001069 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1070 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1071 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1072 (isLoopControlVariable(D).first && A == OMPC_private));
1073 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1074 Data.RefExpr.setInt(/*IntVal=*/true);
1075 return;
1076 }
1077 const bool IsLastprivate =
1078 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1079 Data.Attributes = A;
1080 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1081 Data.PrivateCopy = PrivateCopy;
1082 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001083 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001084 Data.Attributes = A;
1085 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1086 Data.PrivateCopy = nullptr;
1087 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001088 }
1089}
1090
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001091/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001092static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001093 StringRef Name, const AttrVec *Attrs = nullptr,
1094 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001095 DeclContext *DC = SemaRef.CurContext;
1096 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1097 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001098 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001099 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1100 if (Attrs) {
1101 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1102 I != E; ++I)
1103 Decl->addAttr(*I);
1104 }
1105 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001106 if (OrigRef) {
1107 Decl->addAttr(
1108 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1109 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001110 return Decl;
1111}
1112
1113static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1114 SourceLocation Loc,
1115 bool RefersToCapture = false) {
1116 D->setReferenced();
1117 D->markUsed(S.Context);
1118 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1119 SourceLocation(), D, RefersToCapture, Loc, Ty,
1120 VK_LValue);
1121}
1122
Alexey Bataeve3727102018-04-18 15:57:46 +00001123void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001124 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001125 D = getCanonicalDecl(D);
1126 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001127 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001128 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001129 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001130 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001131 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001132 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001133 "Additional reduction info may be specified only once for reduction "
1134 "items.");
1135 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001136 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001137 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001138 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001139 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1140 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001141 TaskgroupReductionRef =
1142 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001143 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001144}
1145
Alexey Bataeve3727102018-04-18 15:57:46 +00001146void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001147 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001148 D = getCanonicalDecl(D);
1149 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001150 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001151 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001152 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001153 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001154 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001155 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001156 "Additional reduction info may be specified only once for reduction "
1157 "items.");
1158 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001159 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001160 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001161 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001162 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1163 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001164 TaskgroupReductionRef =
1165 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001166 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001167}
1168
Alexey Bataeve3727102018-04-18 15:57:46 +00001169const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1170 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1171 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001172 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001173 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001174 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001175 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001176 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001177 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001178 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001179 if (!ReductionData.ReductionOp ||
1180 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001181 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001182 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001183 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001184 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1185 "expression for the descriptor is not "
1186 "set.");
1187 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001188 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1189 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001190 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001191 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001192}
1193
Alexey Bataeve3727102018-04-18 15:57:46 +00001194const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1195 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1196 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001197 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001198 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001199 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001200 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001201 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001202 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001203 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001204 if (!ReductionData.ReductionOp ||
1205 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001206 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001207 SR = ReductionData.ReductionRange;
1208 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001209 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1210 "expression for the descriptor is not "
1211 "set.");
1212 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001213 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1214 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001215 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001216 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001217}
1218
Richard Smith375dec52019-05-30 23:21:14 +00001219bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001220 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001221 for (const_iterator E = end(); I != E; ++I) {
1222 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1223 isOpenMPTargetExecutionDirective(I->Directive)) {
1224 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1225 Scope *CurScope = getCurScope();
1226 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1227 CurScope = CurScope->getParent();
1228 return CurScope != TopScope;
1229 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001230 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001231 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001232}
1233
Joel E. Dennyd2649292019-01-04 22:11:56 +00001234static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1235 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001236 bool *IsClassType = nullptr) {
1237 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001238 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001239 bool IsConstant = Type.isConstant(Context);
1240 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001241 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1242 ? Type->getAsCXXRecordDecl()
1243 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001244 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1245 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1246 RD = CTD->getTemplatedDecl();
1247 if (IsClassType)
1248 *IsClassType = RD;
1249 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1250 RD->hasDefinition() && RD->hasMutableFields());
1251}
1252
Joel E. Dennyd2649292019-01-04 22:11:56 +00001253static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1254 QualType Type, OpenMPClauseKind CKind,
1255 SourceLocation ELoc,
1256 bool AcceptIfMutable = true,
1257 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001258 ASTContext &Context = SemaRef.getASTContext();
1259 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001260 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1261 unsigned Diag = ListItemNotVar
1262 ? diag::err_omp_const_list_item
1263 : IsClassType ? diag::err_omp_const_not_mutable_variable
1264 : diag::err_omp_const_variable;
1265 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1266 if (!ListItemNotVar && D) {
1267 const VarDecl *VD = dyn_cast<VarDecl>(D);
1268 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1269 VarDecl::DeclarationOnly;
1270 SemaRef.Diag(D->getLocation(),
1271 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1272 << D;
1273 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001274 return true;
1275 }
1276 return false;
1277}
1278
Alexey Bataeve3727102018-04-18 15:57:46 +00001279const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1280 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001281 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001282 DSAVarData DVar;
1283
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001284 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001285 auto TI = Threadprivates.find(D);
1286 if (TI != Threadprivates.end()) {
1287 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001288 DVar.CKind = OMPC_threadprivate;
1289 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001290 }
1291 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001292 DVar.RefExpr = buildDeclRefExpr(
1293 SemaRef, VD, D->getType().getNonReferenceType(),
1294 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1295 DVar.CKind = OMPC_threadprivate;
1296 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001297 return DVar;
1298 }
1299 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1300 // in a Construct, C/C++, predetermined, p.1]
1301 // Variables appearing in threadprivate directives are threadprivate.
1302 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1303 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1304 SemaRef.getLangOpts().OpenMPUseTLS &&
1305 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1306 (VD && VD->getStorageClass() == SC_Register &&
1307 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1308 DVar.RefExpr = buildDeclRefExpr(
1309 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1310 DVar.CKind = OMPC_threadprivate;
1311 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1312 return DVar;
1313 }
1314 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1315 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1316 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001317 const_iterator IterTarget =
1318 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1319 return isOpenMPTargetExecutionDirective(Data.Directive);
1320 });
1321 if (IterTarget != end()) {
1322 const_iterator ParentIterTarget = IterTarget + 1;
1323 for (const_iterator Iter = begin();
1324 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001325 if (isOpenMPLocal(VD, Iter)) {
1326 DVar.RefExpr =
1327 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1328 D->getLocation());
1329 DVar.CKind = OMPC_threadprivate;
1330 return DVar;
1331 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001332 }
Richard Smith375dec52019-05-30 23:21:14 +00001333 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001334 auto DSAIter = IterTarget->SharingMap.find(D);
1335 if (DSAIter != IterTarget->SharingMap.end() &&
1336 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1337 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1338 DVar.CKind = OMPC_threadprivate;
1339 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001340 }
Richard Smith375dec52019-05-30 23:21:14 +00001341 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001342 if (!SemaRef.isOpenMPCapturedByRef(
1343 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001344 DVar.RefExpr =
1345 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1346 IterTarget->ConstructLoc);
1347 DVar.CKind = OMPC_threadprivate;
1348 return DVar;
1349 }
1350 }
1351 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001352 }
1353
Alexey Bataev4b465392017-04-26 15:06:24 +00001354 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001355 // Not in OpenMP execution region and top scope was already checked.
1356 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001357
Alexey Bataev758e55e2013-09-06 18:03:48 +00001358 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001359 // in a Construct, C/C++, predetermined, p.4]
1360 // Static data members are shared.
1361 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1362 // in a Construct, C/C++, predetermined, p.7]
1363 // Variables with static storage duration that are declared in a scope
1364 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001365 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001366 // Check for explicitly specified attributes.
1367 const_iterator I = begin();
1368 const_iterator EndI = end();
1369 if (FromParent && I != EndI)
1370 ++I;
1371 auto It = I->SharingMap.find(D);
1372 if (It != I->SharingMap.end()) {
1373 const DSAInfo &Data = It->getSecond();
1374 DVar.RefExpr = Data.RefExpr.getPointer();
1375 DVar.PrivateCopy = Data.PrivateCopy;
1376 DVar.CKind = Data.Attributes;
1377 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1378 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001379 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001380 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001381
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001382 DVar.CKind = OMPC_shared;
1383 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001384 }
1385
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001386 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001387 // The predetermined shared attribute for const-qualified types having no
1388 // mutable members was removed after OpenMP 3.1.
1389 if (SemaRef.LangOpts.OpenMP <= 31) {
1390 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1391 // in a Construct, C/C++, predetermined, p.6]
1392 // Variables with const qualified type having no mutable member are
1393 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001394 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001395 // Variables with const-qualified type having no mutable member may be
1396 // listed in a firstprivate clause, even if they are static data members.
1397 DSAVarData DVarTemp = hasInnermostDSA(
1398 D,
1399 [](OpenMPClauseKind C) {
1400 return C == OMPC_firstprivate || C == OMPC_shared;
1401 },
1402 MatchesAlways, FromParent);
1403 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1404 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001405
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001406 DVar.CKind = OMPC_shared;
1407 return DVar;
1408 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001409 }
1410
Alexey Bataev758e55e2013-09-06 18:03:48 +00001411 // Explicitly specified attributes and local variables with predetermined
1412 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001413 const_iterator I = begin();
1414 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001415 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001416 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001417 auto It = I->SharingMap.find(D);
1418 if (It != I->SharingMap.end()) {
1419 const DSAInfo &Data = It->getSecond();
1420 DVar.RefExpr = Data.RefExpr.getPointer();
1421 DVar.PrivateCopy = Data.PrivateCopy;
1422 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001423 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001424 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001425 }
1426
1427 return DVar;
1428}
1429
Alexey Bataeve3727102018-04-18 15:57:46 +00001430const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1431 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001432 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001433 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001434 return getDSA(I, D);
1435 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001436 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001437 const_iterator StartI = begin();
1438 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001439 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001440 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001441 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001442}
1443
Alexey Bataeve3727102018-04-18 15:57:46 +00001444const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001445DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001446 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1447 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001448 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001449 if (isStackEmpty())
1450 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001451 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001452 const_iterator I = begin();
1453 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001454 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001455 ++I;
1456 for (; I != EndI; ++I) {
1457 if (!DPred(I->Directive) &&
1458 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001459 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001460 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001461 DSAVarData DVar = getDSA(NewI, D);
1462 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001463 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001464 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001465 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001466}
1467
Alexey Bataeve3727102018-04-18 15:57:46 +00001468const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001469 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1470 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001471 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001472 if (isStackEmpty())
1473 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001474 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001475 const_iterator StartI = begin();
1476 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001477 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001478 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001479 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001480 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001481 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001482 DSAVarData DVar = getDSA(NewI, D);
1483 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001484}
1485
Alexey Bataevaac108a2015-06-23 04:51:00 +00001486bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001487 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1488 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001489 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001490 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001491 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001492 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1493 auto I = StackElem.SharingMap.find(D);
1494 if (I != StackElem.SharingMap.end() &&
1495 I->getSecond().RefExpr.getPointer() &&
1496 CPred(I->getSecond().Attributes) &&
1497 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001498 return true;
1499 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001500 auto LI = StackElem.LCVMap.find(D);
1501 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001502 return CPred(OMPC_private);
1503 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001504}
1505
Samuel Antao4be30e92015-10-02 17:14:03 +00001506bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001507 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1508 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001509 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001510 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001511 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1512 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001513}
1514
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001515bool DSAStackTy::hasDirective(
1516 const llvm::function_ref<bool(OpenMPDirectiveKind,
1517 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001518 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001519 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001520 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001521 size_t Skip = FromParent ? 2 : 1;
1522 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1523 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001524 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1525 return true;
1526 }
1527 return false;
1528}
1529
Alexey Bataev758e55e2013-09-06 18:03:48 +00001530void Sema::InitDataSharingAttributesStack() {
1531 VarDataSharingAttributesStack = new DSAStackTy(*this);
1532}
1533
1534#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1535
Alexey Bataev4b465392017-04-26 15:06:24 +00001536void Sema::pushOpenMPFunctionRegion() {
1537 DSAStack->pushFunction();
1538}
1539
1540void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1541 DSAStack->popFunction(OldFSI);
1542}
1543
Alexey Bataevc416e642019-02-08 18:02:25 +00001544static bool isOpenMPDeviceDelayedContext(Sema &S) {
1545 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1546 "Expected OpenMP device compilation.");
1547 return !S.isInOpenMPTargetExecutionDirective() &&
1548 !S.isInOpenMPDeclareTargetContext();
1549}
1550
1551/// Do we know that we will eventually codegen the given function?
1552static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1553 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1554 "Expected OpenMP device compilation.");
1555 // Templates are emitted when they're instantiated.
1556 if (FD->isDependentContext())
1557 return false;
1558
1559 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1560 FD->getCanonicalDecl()))
1561 return true;
1562
1563 // Otherwise, the function is known-emitted if it's in our set of
1564 // known-emitted functions.
1565 return S.DeviceKnownEmittedFns.count(FD) > 0;
1566}
1567
1568Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1569 unsigned DiagID) {
1570 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1571 "Expected OpenMP device compilation.");
1572 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1573 !isKnownEmitted(*this, getCurFunctionDecl()))
1574 ? DeviceDiagBuilder::K_Deferred
1575 : DeviceDiagBuilder::K_Immediate,
1576 Loc, DiagID, getCurFunctionDecl(), *this);
1577}
1578
1579void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1580 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1581 "Expected OpenMP device compilation.");
1582 assert(Callee && "Callee may not be null.");
1583 FunctionDecl *Caller = getCurFunctionDecl();
1584
1585 // If the caller is known-emitted, mark the callee as known-emitted.
1586 // Otherwise, mark the call in our call graph so we can traverse it later.
1587 if (!isOpenMPDeviceDelayedContext(*this) ||
1588 (Caller && isKnownEmitted(*this, Caller)))
1589 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1590 else if (Caller)
1591 DeviceCallGraph[Caller].insert({Callee, Loc});
1592}
1593
Alexey Bataev123ad192019-02-27 20:29:45 +00001594void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1595 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1596 "OpenMP device compilation mode is expected.");
1597 QualType Ty = E->getType();
1598 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001599 ((Ty->isFloat128Type() ||
1600 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1601 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001602 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1603 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001604 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1605 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1606 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001607}
1608
Alexey Bataeve3727102018-04-18 15:57:46 +00001609bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001610 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1611
Alexey Bataeve3727102018-04-18 15:57:46 +00001612 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001613 bool IsByRef = true;
1614
1615 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001616 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001617 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001618
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001619 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001620 // This table summarizes how a given variable should be passed to the device
1621 // given its type and the clauses where it appears. This table is based on
1622 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1623 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1624 //
1625 // =========================================================================
1626 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1627 // | |(tofrom:scalar)| | pvt | | | |
1628 // =========================================================================
1629 // | scl | | | | - | | bycopy|
1630 // | scl | | - | x | - | - | bycopy|
1631 // | scl | | x | - | - | - | null |
1632 // | scl | x | | | - | | byref |
1633 // | scl | x | - | x | - | - | bycopy|
1634 // | scl | x | x | - | - | - | null |
1635 // | scl | | - | - | - | x | byref |
1636 // | scl | x | - | - | - | x | byref |
1637 //
1638 // | agg | n.a. | | | - | | byref |
1639 // | agg | n.a. | - | x | - | - | byref |
1640 // | agg | n.a. | x | - | - | - | null |
1641 // | agg | n.a. | - | - | - | x | byref |
1642 // | agg | n.a. | - | - | - | x[] | byref |
1643 //
1644 // | ptr | n.a. | | | - | | bycopy|
1645 // | ptr | n.a. | - | x | - | - | bycopy|
1646 // | ptr | n.a. | x | - | - | - | null |
1647 // | ptr | n.a. | - | - | - | x | byref |
1648 // | ptr | n.a. | - | - | - | x[] | bycopy|
1649 // | ptr | n.a. | - | - | x | | bycopy|
1650 // | ptr | n.a. | - | - | x | x | bycopy|
1651 // | ptr | n.a. | - | - | x | x[] | bycopy|
1652 // =========================================================================
1653 // Legend:
1654 // scl - scalar
1655 // ptr - pointer
1656 // agg - aggregate
1657 // x - applies
1658 // - - invalid in this combination
1659 // [] - mapped with an array section
1660 // byref - should be mapped by reference
1661 // byval - should be mapped by value
1662 // null - initialize a local variable to null on the device
1663 //
1664 // Observations:
1665 // - All scalar declarations that show up in a map clause have to be passed
1666 // by reference, because they may have been mapped in the enclosing data
1667 // environment.
1668 // - If the scalar value does not fit the size of uintptr, it has to be
1669 // passed by reference, regardless the result in the table above.
1670 // - For pointers mapped by value that have either an implicit map or an
1671 // array section, the runtime library may pass the NULL value to the
1672 // device instead of the value passed to it by the compiler.
1673
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001674 if (Ty->isReferenceType())
1675 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001676
1677 // Locate map clauses and see if the variable being captured is referred to
1678 // in any of those clauses. Here we only care about variables, not fields,
1679 // because fields are part of aggregates.
1680 bool IsVariableUsedInMapClause = false;
1681 bool IsVariableAssociatedWithSection = false;
1682
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001683 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001684 D, Level,
1685 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1686 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001687 MapExprComponents,
1688 OpenMPClauseKind WhereFoundClauseKind) {
1689 // Only the map clause information influences how a variable is
1690 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001691 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001692 if (WhereFoundClauseKind != OMPC_map)
1693 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001694
1695 auto EI = MapExprComponents.rbegin();
1696 auto EE = MapExprComponents.rend();
1697
1698 assert(EI != EE && "Invalid map expression!");
1699
1700 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1701 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1702
1703 ++EI;
1704 if (EI == EE)
1705 return false;
1706
1707 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1708 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1709 isa<MemberExpr>(EI->getAssociatedExpression())) {
1710 IsVariableAssociatedWithSection = true;
1711 // There is nothing more we need to know about this variable.
1712 return true;
1713 }
1714
1715 // Keep looking for more map info.
1716 return false;
1717 });
1718
1719 if (IsVariableUsedInMapClause) {
1720 // If variable is identified in a map clause it is always captured by
1721 // reference except if it is a pointer that is dereferenced somehow.
1722 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1723 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001724 // By default, all the data that has a scalar type is mapped by copy
1725 // (except for reduction variables).
1726 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001727 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1728 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001729 !Ty->isScalarType() ||
1730 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1731 DSAStack->hasExplicitDSA(
1732 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001733 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001734 }
1735
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001736 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001737 IsByRef =
Alexey Bataevb600ae32019-07-01 17:46:52 +00001738 !DSAStack->hasExplicitDSA(
1739 D,
1740 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1741 Level, /*NotLastprivate=*/true) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001742 // If the variable is artificial and must be captured by value - try to
1743 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001744 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1745 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001746 }
1747
Samuel Antao86ace552016-04-27 22:40:57 +00001748 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001749 // and alignment, because the runtime library only deals with uintptr types.
1750 // If it does not fit the uintptr size, we need to pass the data by reference
1751 // instead.
1752 if (!IsByRef &&
1753 (Ctx.getTypeSizeInChars(Ty) >
1754 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001755 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001756 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001757 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001758
1759 return IsByRef;
1760}
1761
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001762unsigned Sema::getOpenMPNestingLevel() const {
1763 assert(getLangOpts().OpenMP);
1764 return DSAStack->getNestingLevel();
1765}
1766
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001767bool Sema::isInOpenMPTargetExecutionDirective() const {
1768 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1769 !DSAStack->isClauseParsingMode()) ||
1770 DSAStack->hasDirective(
1771 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1772 SourceLocation) -> bool {
1773 return isOpenMPTargetExecutionDirective(K);
1774 },
1775 false);
1776}
1777
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001778VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1779 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001780 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001781 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001782
Richard Smith0621a8f2019-05-31 00:45:10 +00001783 // If we want to determine whether the variable should be captured from the
1784 // perspective of the current capturing scope, and we've already left all the
1785 // capturing scopes of the top directive on the stack, check from the
1786 // perspective of its parent directive (if any) instead.
1787 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1788 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1789
Samuel Antao4be30e92015-10-02 17:14:03 +00001790 // If we are attempting to capture a global variable in a directive with
1791 // 'target' we return true so that this global is also mapped to the device.
1792 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001793 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001794 if (VD && !VD->hasLocalStorage() &&
1795 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1796 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001797 // Try to mark variable as declare target if it is used in capturing
1798 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001799 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001800 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001801 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001802 } else if (isInOpenMPTargetExecutionDirective()) {
1803 // If the declaration is enclosed in a 'declare target' directive,
1804 // then it should not be captured.
1805 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001806 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001807 return nullptr;
1808 return VD;
1809 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001810 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001811
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001812 if (CheckScopeInfo) {
1813 bool OpenMPFound = false;
1814 for (unsigned I = StopAt + 1; I > 0; --I) {
1815 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1816 if(!isa<CapturingScopeInfo>(FSI))
1817 return nullptr;
1818 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1819 if (RSI->CapRegionKind == CR_OpenMP) {
1820 OpenMPFound = true;
1821 break;
1822 }
1823 }
1824 if (!OpenMPFound)
1825 return nullptr;
1826 }
1827
Alexey Bataev48977c32015-08-04 08:10:48 +00001828 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1829 (!DSAStack->isClauseParsingMode() ||
1830 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001831 auto &&Info = DSAStack->isLoopControlVariable(D);
1832 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001833 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001834 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001835 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001836 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001837 DSAStackTy::DSAVarData DVarPrivate =
1838 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001839 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001840 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00001841 // Threadprivate variables must not be captured.
1842 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
1843 return nullptr;
1844 // The variable is not private or it is the variable in the directive with
1845 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001846 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1847 [](OpenMPDirectiveKind) { return true; },
1848 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001849 if (DVarPrivate.CKind != OMPC_unknown ||
1850 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001851 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001852 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001853 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001854}
1855
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001856void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1857 unsigned Level) const {
1858 SmallVector<OpenMPDirectiveKind, 4> Regions;
1859 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1860 FunctionScopesIndex -= Regions.size();
1861}
1862
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001863void Sema::startOpenMPLoop() {
1864 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1865 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1866 DSAStack->loopInit();
1867}
1868
Alexey Bataeve3727102018-04-18 15:57:46 +00001869bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001870 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001871 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1872 if (DSAStack->getAssociatedLoops() > 0 &&
1873 !DSAStack->isLoopStarted()) {
1874 DSAStack->resetPossibleLoopCounter(D);
1875 DSAStack->loopStart();
1876 return true;
1877 }
1878 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1879 DSAStack->isLoopControlVariable(D).first) &&
1880 !DSAStack->hasExplicitDSA(
1881 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1882 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1883 return true;
1884 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00001885 if (const auto *VD = dyn_cast<VarDecl>(D)) {
1886 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
1887 DSAStack->isForceVarCapturing() &&
1888 !DSAStack->hasExplicitDSA(
1889 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
1890 return true;
1891 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001892 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001893 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001894 (DSAStack->isClauseParsingMode() &&
1895 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001896 // Consider taskgroup reduction descriptor variable a private to avoid
1897 // possible capture in the region.
1898 (DSAStack->hasExplicitDirective(
1899 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1900 Level) &&
1901 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001902}
1903
Alexey Bataeve3727102018-04-18 15:57:46 +00001904void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1905 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001906 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1907 D = getCanonicalDecl(D);
1908 OpenMPClauseKind OMPC = OMPC_unknown;
1909 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1910 const unsigned NewLevel = I - 1;
1911 if (DSAStack->hasExplicitDSA(D,
1912 [&OMPC](const OpenMPClauseKind K) {
1913 if (isOpenMPPrivate(K)) {
1914 OMPC = K;
1915 return true;
1916 }
1917 return false;
1918 },
1919 NewLevel))
1920 break;
1921 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1922 D, NewLevel,
1923 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1924 OpenMPClauseKind) { return true; })) {
1925 OMPC = OMPC_map;
1926 break;
1927 }
1928 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1929 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001930 OMPC = OMPC_map;
1931 if (D->getType()->isScalarType() &&
1932 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1933 DefaultMapAttributes::DMA_tofrom_scalar)
1934 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001935 break;
1936 }
1937 }
1938 if (OMPC != OMPC_unknown)
1939 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1940}
1941
Alexey Bataeve3727102018-04-18 15:57:46 +00001942bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1943 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001944 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1945 // Return true if the current level is no longer enclosed in a target region.
1946
Alexey Bataeve3727102018-04-18 15:57:46 +00001947 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001948 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001949 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1950 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001951}
1952
Alexey Bataeved09d242014-05-28 05:53:51 +00001953void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001954
1955void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1956 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001957 Scope *CurScope, SourceLocation Loc) {
1958 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001959 PushExpressionEvaluationContext(
1960 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001961}
1962
Alexey Bataevaac108a2015-06-23 04:51:00 +00001963void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1964 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001965}
1966
Alexey Bataevaac108a2015-06-23 04:51:00 +00001967void Sema::EndOpenMPClause() {
1968 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001969}
1970
Alexey Bataeve106f252019-04-01 14:25:31 +00001971static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
1972 ArrayRef<OMPClause *> Clauses);
1973
Alexey Bataev758e55e2013-09-06 18:03:48 +00001974void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001975 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1976 // A variable of class type (or array thereof) that appears in a lastprivate
1977 // clause requires an accessible, unambiguous default constructor for the
1978 // class type, unless the list item is also specified in a firstprivate
1979 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001980 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1981 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001982 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1983 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001984 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001985 if (DE->isValueDependent() || DE->isTypeDependent()) {
1986 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001987 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001988 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001989 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001990 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001991 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001992 const DSAStackTy::DSAVarData DVar =
1993 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001994 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001995 // Generate helper private variable and initialize it with the
1996 // default value. The address of the original variable is replaced
1997 // by the address of the new private variable in CodeGen. This new
1998 // variable is not added to IdResolver, so the code in the OpenMP
1999 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002000 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002001 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002002 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002003 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002004 if (VDPrivate->isInvalidDecl()) {
2005 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002006 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002007 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002008 PrivateCopies.push_back(buildDeclRefExpr(
2009 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002010 } else {
2011 // The variable is also a firstprivate, so initialization sequence
2012 // for private copy is generated already.
2013 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002014 }
2015 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002016 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002017 }
2018 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002019 // Check allocate clauses.
2020 if (!CurContext->isDependentContext())
2021 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002022 }
2023
Alexey Bataev758e55e2013-09-06 18:03:48 +00002024 DSAStack->pop();
2025 DiscardCleanupsInEvaluationContext();
2026 PopExpressionEvaluationContext();
2027}
2028
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002029static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2030 Expr *NumIterations, Sema &SemaRef,
2031 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002032
Alexey Bataeva769e072013-03-22 06:34:35 +00002033namespace {
2034
Alexey Bataeve3727102018-04-18 15:57:46 +00002035class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002036private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002037 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002038
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002039public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002040 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002041 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002042 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002043 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002044 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002045 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2046 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002047 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002048 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002049 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002050
2051 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2052 return llvm::make_unique<VarDeclFilterCCC>(*this);
2053 }
2054
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002055};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002056
Alexey Bataeve3727102018-04-18 15:57:46 +00002057class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002058private:
2059 Sema &SemaRef;
2060
2061public:
2062 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2063 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2064 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002065 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2066 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002067 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2068 SemaRef.getCurScope());
2069 }
2070 return false;
2071 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002072
2073 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2074 return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
2075 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002076};
2077
Alexey Bataeved09d242014-05-28 05:53:51 +00002078} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002079
2080ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2081 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002082 const DeclarationNameInfo &Id,
2083 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002084 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2085 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2086
2087 if (Lookup.isAmbiguous())
2088 return ExprError();
2089
2090 VarDecl *VD;
2091 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002092 VarDeclFilterCCC CCC(*this);
2093 if (TypoCorrection Corrected =
2094 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2095 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002096 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002097 PDiag(Lookup.empty()
2098 ? diag::err_undeclared_var_use_suggest
2099 : diag::err_omp_expected_var_arg_suggest)
2100 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002101 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002102 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002103 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2104 : diag::err_omp_expected_var_arg)
2105 << Id.getName();
2106 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002107 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002108 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2109 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2110 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2111 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002112 }
2113 Lookup.suppressDiagnostics();
2114
2115 // OpenMP [2.9.2, Syntax, C/C++]
2116 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002117 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002118 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002119 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002120 bool IsDecl =
2121 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002122 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002123 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2124 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002125 return ExprError();
2126 }
2127
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002128 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002129 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002130 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2131 // A threadprivate directive for file-scope variables must appear outside
2132 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002133 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2134 !getCurLexicalContext()->isTranslationUnit()) {
2135 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002136 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002137 bool IsDecl =
2138 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2139 Diag(VD->getLocation(),
2140 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2141 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002142 return ExprError();
2143 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002144 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2145 // A threadprivate directive for static class member variables must appear
2146 // in the class definition, in the same scope in which the member
2147 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002148 if (CanonicalVD->isStaticDataMember() &&
2149 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2150 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002151 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002152 bool IsDecl =
2153 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2154 Diag(VD->getLocation(),
2155 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2156 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002157 return ExprError();
2158 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002159 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2160 // A threadprivate directive for namespace-scope variables must appear
2161 // outside any definition or declaration other than the namespace
2162 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002163 if (CanonicalVD->getDeclContext()->isNamespace() &&
2164 (!getCurLexicalContext()->isFileContext() ||
2165 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2166 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002167 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002168 bool IsDecl =
2169 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2170 Diag(VD->getLocation(),
2171 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2172 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002173 return ExprError();
2174 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002175 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2176 // A threadprivate directive for static block-scope variables must appear
2177 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002178 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002179 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002180 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002181 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002182 bool IsDecl =
2183 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2184 Diag(VD->getLocation(),
2185 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2186 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002187 return ExprError();
2188 }
2189
2190 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2191 // A threadprivate directive must lexically precede all references to any
2192 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002193 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2194 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002195 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002196 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002197 return ExprError();
2198 }
2199
2200 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002201 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2202 SourceLocation(), VD,
2203 /*RefersToEnclosingVariableOrCapture=*/false,
2204 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002205}
2206
Alexey Bataeved09d242014-05-28 05:53:51 +00002207Sema::DeclGroupPtrTy
2208Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2209 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002210 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002211 CurContext->addDecl(D);
2212 return DeclGroupPtrTy::make(DeclGroupRef(D));
2213 }
David Blaikie0403cb12016-01-15 23:43:25 +00002214 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002215}
2216
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002217namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002218class LocalVarRefChecker final
2219 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002220 Sema &SemaRef;
2221
2222public:
2223 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002224 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002225 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002226 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002227 diag::err_omp_local_var_in_threadprivate_init)
2228 << E->getSourceRange();
2229 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2230 << VD << VD->getSourceRange();
2231 return true;
2232 }
2233 }
2234 return false;
2235 }
2236 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002237 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002238 if (Child && Visit(Child))
2239 return true;
2240 }
2241 return false;
2242 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002243 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002244};
2245} // namespace
2246
Alexey Bataeved09d242014-05-28 05:53:51 +00002247OMPThreadPrivateDecl *
2248Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002249 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002250 for (Expr *RefExpr : VarList) {
2251 auto *DE = cast<DeclRefExpr>(RefExpr);
2252 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002253 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002254
Alexey Bataev376b4a42016-02-09 09:41:09 +00002255 // Mark variable as used.
2256 VD->setReferenced();
2257 VD->markUsed(Context);
2258
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002259 QualType QType = VD->getType();
2260 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2261 // It will be analyzed later.
2262 Vars.push_back(DE);
2263 continue;
2264 }
2265
Alexey Bataeva769e072013-03-22 06:34:35 +00002266 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2267 // A threadprivate variable must not have an incomplete type.
2268 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002269 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002270 continue;
2271 }
2272
2273 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2274 // A threadprivate variable must not have a reference type.
2275 if (VD->getType()->isReferenceType()) {
2276 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002277 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2278 bool IsDecl =
2279 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2280 Diag(VD->getLocation(),
2281 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2282 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002283 continue;
2284 }
2285
Samuel Antaof8b50122015-07-13 22:54:53 +00002286 // Check if this is a TLS variable. If TLS is not being supported, produce
2287 // the corresponding diagnostic.
2288 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2289 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2290 getLangOpts().OpenMPUseTLS &&
2291 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002292 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2293 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002294 Diag(ILoc, diag::err_omp_var_thread_local)
2295 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002296 bool IsDecl =
2297 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2298 Diag(VD->getLocation(),
2299 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2300 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002301 continue;
2302 }
2303
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002304 // Check if initial value of threadprivate variable reference variable with
2305 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002306 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002307 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002308 if (Checker.Visit(Init))
2309 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002310 }
2311
Alexey Bataeved09d242014-05-28 05:53:51 +00002312 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002313 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002314 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2315 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002316 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002317 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002318 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002319 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002320 if (!Vars.empty()) {
2321 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2322 Vars);
2323 D->setAccess(AS_public);
2324 }
2325 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002326}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002327
Alexey Bataev27ef9512019-03-20 20:14:22 +00002328static OMPAllocateDeclAttr::AllocatorTypeTy
2329getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2330 if (!Allocator)
2331 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2332 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2333 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002334 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002335 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002336 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002337 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002338 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2339 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2340 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002341 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002342 llvm::FoldingSetNodeID AEId, DAEId;
2343 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2344 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2345 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002346 AllocatorKindRes = AllocatorKind;
2347 break;
2348 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002349 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002350 return AllocatorKindRes;
2351}
2352
Alexey Bataeve106f252019-04-01 14:25:31 +00002353static bool checkPreviousOMPAllocateAttribute(
2354 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2355 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2356 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2357 return false;
2358 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2359 Expr *PrevAllocator = A->getAllocator();
2360 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2361 getAllocatorKind(S, Stack, PrevAllocator);
2362 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2363 if (AllocatorsMatch &&
2364 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2365 Allocator && PrevAllocator) {
2366 const Expr *AE = Allocator->IgnoreParenImpCasts();
2367 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2368 llvm::FoldingSetNodeID AEId, PAEId;
2369 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2370 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2371 AllocatorsMatch = AEId == PAEId;
2372 }
2373 if (!AllocatorsMatch) {
2374 SmallString<256> AllocatorBuffer;
2375 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2376 if (Allocator)
2377 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2378 SmallString<256> PrevAllocatorBuffer;
2379 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2380 if (PrevAllocator)
2381 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2382 S.getPrintingPolicy());
2383
2384 SourceLocation AllocatorLoc =
2385 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2386 SourceRange AllocatorRange =
2387 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2388 SourceLocation PrevAllocatorLoc =
2389 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2390 SourceRange PrevAllocatorRange =
2391 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2392 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2393 << (Allocator ? 1 : 0) << AllocatorStream.str()
2394 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2395 << AllocatorRange;
2396 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2397 << PrevAllocatorRange;
2398 return true;
2399 }
2400 return false;
2401}
2402
2403static void
2404applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2405 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2406 Expr *Allocator, SourceRange SR) {
2407 if (VD->hasAttr<OMPAllocateDeclAttr>())
2408 return;
2409 if (Allocator &&
2410 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2411 Allocator->isInstantiationDependent() ||
2412 Allocator->containsUnexpandedParameterPack()))
2413 return;
2414 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2415 Allocator, SR);
2416 VD->addAttr(A);
2417 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2418 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2419}
2420
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002421Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2422 SourceLocation Loc, ArrayRef<Expr *> VarList,
2423 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2424 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2425 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002426 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002427 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2428 // allocate directives that appear in a target region must specify an
2429 // allocator clause unless a requires directive with the dynamic_allocators
2430 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002431 if (LangOpts.OpenMPIsDevice &&
2432 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002433 targetDiag(Loc, diag::err_expected_allocator_clause);
2434 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002435 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002436 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002437 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2438 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002439 SmallVector<Expr *, 8> Vars;
2440 for (Expr *RefExpr : VarList) {
2441 auto *DE = cast<DeclRefExpr>(RefExpr);
2442 auto *VD = cast<VarDecl>(DE->getDecl());
2443
2444 // Check if this is a TLS variable or global register.
2445 if (VD->getTLSKind() != VarDecl::TLS_None ||
2446 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2447 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2448 !VD->isLocalVarDecl()))
2449 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002450
Alexey Bataev282555a2019-03-19 20:33:44 +00002451 // If the used several times in the allocate directive, the same allocator
2452 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002453 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2454 AllocatorKind, Allocator))
2455 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002456
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002457 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2458 // If a list item has a static storage type, the allocator expression in the
2459 // allocator clause must be a constant expression that evaluates to one of
2460 // the predefined memory allocator values.
2461 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002462 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002463 Diag(Allocator->getExprLoc(),
2464 diag::err_omp_expected_predefined_allocator)
2465 << Allocator->getSourceRange();
2466 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2467 VarDecl::DeclarationOnly;
2468 Diag(VD->getLocation(),
2469 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2470 << VD;
2471 continue;
2472 }
2473 }
2474
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002475 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002476 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2477 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002478 }
2479 if (Vars.empty())
2480 return nullptr;
2481 if (!Owner)
2482 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002483 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002484 D->setAccess(AS_public);
2485 Owner->addDecl(D);
2486 return DeclGroupPtrTy::make(DeclGroupRef(D));
2487}
2488
2489Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002490Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2491 ArrayRef<OMPClause *> ClauseList) {
2492 OMPRequiresDecl *D = nullptr;
2493 if (!CurContext->isFileContext()) {
2494 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2495 } else {
2496 D = CheckOMPRequiresDecl(Loc, ClauseList);
2497 if (D) {
2498 CurContext->addDecl(D);
2499 DSAStack->addRequiresDecl(D);
2500 }
2501 }
2502 return DeclGroupPtrTy::make(DeclGroupRef(D));
2503}
2504
2505OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2506 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002507 /// For target specific clauses, the requires directive cannot be
2508 /// specified after the handling of any of the target regions in the
2509 /// current compilation unit.
2510 ArrayRef<SourceLocation> TargetLocations =
2511 DSAStack->getEncounteredTargetLocs();
2512 if (!TargetLocations.empty()) {
2513 for (const OMPClause *CNew : ClauseList) {
2514 // Check if any of the requires clauses affect target regions.
2515 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2516 isa<OMPUnifiedAddressClause>(CNew) ||
2517 isa<OMPReverseOffloadClause>(CNew) ||
2518 isa<OMPDynamicAllocatorsClause>(CNew)) {
2519 Diag(Loc, diag::err_omp_target_before_requires)
2520 << getOpenMPClauseName(CNew->getClauseKind());
2521 for (SourceLocation TargetLoc : TargetLocations) {
2522 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2523 }
2524 }
2525 }
2526 }
2527
Kelvin Li1408f912018-09-26 04:28:39 +00002528 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2529 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2530 ClauseList);
2531 return nullptr;
2532}
2533
Alexey Bataeve3727102018-04-18 15:57:46 +00002534static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2535 const ValueDecl *D,
2536 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002537 bool IsLoopIterVar = false) {
2538 if (DVar.RefExpr) {
2539 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2540 << getOpenMPClauseName(DVar.CKind);
2541 return;
2542 }
2543 enum {
2544 PDSA_StaticMemberShared,
2545 PDSA_StaticLocalVarShared,
2546 PDSA_LoopIterVarPrivate,
2547 PDSA_LoopIterVarLinear,
2548 PDSA_LoopIterVarLastprivate,
2549 PDSA_ConstVarShared,
2550 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002551 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002552 PDSA_LocalVarPrivate,
2553 PDSA_Implicit
2554 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002555 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002556 auto ReportLoc = D->getLocation();
2557 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002558 if (IsLoopIterVar) {
2559 if (DVar.CKind == OMPC_private)
2560 Reason = PDSA_LoopIterVarPrivate;
2561 else if (DVar.CKind == OMPC_lastprivate)
2562 Reason = PDSA_LoopIterVarLastprivate;
2563 else
2564 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002565 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2566 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002567 Reason = PDSA_TaskVarFirstprivate;
2568 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002569 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002570 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002571 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002572 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002573 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002574 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002575 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002576 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002577 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002578 ReportHint = true;
2579 Reason = PDSA_LocalVarPrivate;
2580 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002581 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002582 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002583 << Reason << ReportHint
2584 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2585 } else if (DVar.ImplicitDSALoc.isValid()) {
2586 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2587 << getOpenMPClauseName(DVar.CKind);
2588 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002589}
2590
Alexey Bataev758e55e2013-09-06 18:03:48 +00002591namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002592class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002593 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002594 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002595 bool ErrorFound = false;
2596 CapturedStmt *CS = nullptr;
2597 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2598 llvm::SmallVector<Expr *, 4> ImplicitMap;
2599 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2600 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002601
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002602 void VisitSubCaptures(OMPExecutableDirective *S) {
2603 // Check implicitly captured variables.
2604 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2605 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002606 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002607 }
2608
Alexey Bataev758e55e2013-09-06 18:03:48 +00002609public:
2610 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002611 if (E->isTypeDependent() || E->isValueDependent() ||
2612 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2613 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002614 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002615 // Check the datasharing rules for the expressions in the clauses.
2616 if (!CS) {
2617 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2618 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2619 Visit(CED->getInit());
2620 return;
2621 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002622 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2623 // Do not analyze internal variables and do not enclose them into
2624 // implicit clauses.
2625 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002626 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002627 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002628 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002629 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002630
Alexey Bataeve3727102018-04-18 15:57:46 +00002631 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002632 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002633 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002634 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002635
Alexey Bataevafe50572017-10-06 17:00:28 +00002636 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002637 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002638 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002639 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002640 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2641 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002642 return;
2643
Alexey Bataeve3727102018-04-18 15:57:46 +00002644 SourceLocation ELoc = E->getExprLoc();
2645 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002646 // The default(none) clause requires that each variable that is referenced
2647 // in the construct, and does not have a predetermined data-sharing
2648 // attribute, must have its data-sharing attribute explicitly determined
2649 // by being listed in a data-sharing attribute clause.
2650 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002651 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002652 VarsWithInheritedDSA.count(VD) == 0) {
2653 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002654 return;
2655 }
2656
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002657 if (isOpenMPTargetExecutionDirective(DKind) &&
2658 !Stack->isLoopControlVariable(VD).first) {
2659 if (!Stack->checkMappableExprComponentListsForDecl(
2660 VD, /*CurrentRegionOnly=*/true,
2661 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2662 StackComponents,
2663 OpenMPClauseKind) {
2664 // Variable is used if it has been marked as an array, array
2665 // section or the variable iself.
2666 return StackComponents.size() == 1 ||
2667 std::all_of(
2668 std::next(StackComponents.rbegin()),
2669 StackComponents.rend(),
2670 [](const OMPClauseMappableExprCommon::
2671 MappableComponent &MC) {
2672 return MC.getAssociatedDeclaration() ==
2673 nullptr &&
2674 (isa<OMPArraySectionExpr>(
2675 MC.getAssociatedExpression()) ||
2676 isa<ArraySubscriptExpr>(
2677 MC.getAssociatedExpression()));
2678 });
2679 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002680 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002681 // By default lambdas are captured as firstprivates.
2682 if (const auto *RD =
2683 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002684 IsFirstprivate = RD->isLambda();
2685 IsFirstprivate =
2686 IsFirstprivate ||
2687 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002688 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002689 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002690 ImplicitFirstprivate.emplace_back(E);
2691 else
2692 ImplicitMap.emplace_back(E);
2693 return;
2694 }
2695 }
2696
Alexey Bataev758e55e2013-09-06 18:03:48 +00002697 // OpenMP [2.9.3.6, Restrictions, p.2]
2698 // A list item that appears in a reduction clause of the innermost
2699 // enclosing worksharing or parallel construct may not be accessed in an
2700 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002701 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002702 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2703 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002704 return isOpenMPParallelDirective(K) ||
2705 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2706 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002707 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002708 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002709 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002710 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002711 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002712 return;
2713 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002714
2715 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002716 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002717 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002718 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002719 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002720 return;
2721 }
2722
2723 // Store implicitly used globals with declare target link for parent
2724 // target.
2725 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2726 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2727 Stack->addToParentTargetRegionLinkGlobals(E);
2728 return;
2729 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002730 }
2731 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002732 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002733 if (E->isTypeDependent() || E->isValueDependent() ||
2734 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2735 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002736 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002737 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002738 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002739 if (!FD)
2740 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002741 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002742 // Check if the variable has explicit DSA set and stop analysis if it
2743 // so.
2744 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2745 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002746
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002747 if (isOpenMPTargetExecutionDirective(DKind) &&
2748 !Stack->isLoopControlVariable(FD).first &&
2749 !Stack->checkMappableExprComponentListsForDecl(
2750 FD, /*CurrentRegionOnly=*/true,
2751 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2752 StackComponents,
2753 OpenMPClauseKind) {
2754 return isa<CXXThisExpr>(
2755 cast<MemberExpr>(
2756 StackComponents.back().getAssociatedExpression())
2757 ->getBase()
2758 ->IgnoreParens());
2759 })) {
2760 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2761 // A bit-field cannot appear in a map clause.
2762 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002763 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002764 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002765
2766 // Check to see if the member expression is referencing a class that
2767 // has already been explicitly mapped
2768 if (Stack->isClassPreviouslyMapped(TE->getType()))
2769 return;
2770
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002771 ImplicitMap.emplace_back(E);
2772 return;
2773 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002774
Alexey Bataeve3727102018-04-18 15:57:46 +00002775 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002776 // OpenMP [2.9.3.6, Restrictions, p.2]
2777 // A list item that appears in a reduction clause of the innermost
2778 // enclosing worksharing or parallel construct may not be accessed in
2779 // an explicit task.
2780 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002781 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2782 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002783 return isOpenMPParallelDirective(K) ||
2784 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2785 },
2786 /*FromParent=*/true);
2787 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2788 ErrorFound = true;
2789 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002790 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002791 return;
2792 }
2793
2794 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002795 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002796 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002797 !Stack->isLoopControlVariable(FD).first) {
2798 // Check if there is a captured expression for the current field in the
2799 // region. Do not mark it as firstprivate unless there is no captured
2800 // expression.
2801 // TODO: try to make it firstprivate.
2802 if (DVar.CKind != OMPC_unknown)
2803 ImplicitFirstprivate.push_back(E);
2804 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002805 return;
2806 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002807 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002808 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002809 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002810 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002811 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002812 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002813 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2814 if (!Stack->checkMappableExprComponentListsForDecl(
2815 VD, /*CurrentRegionOnly=*/true,
2816 [&CurComponents](
2817 OMPClauseMappableExprCommon::MappableExprComponentListRef
2818 StackComponents,
2819 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002820 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002821 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002822 for (const auto &SC : llvm::reverse(StackComponents)) {
2823 // Do both expressions have the same kind?
2824 if (CCI->getAssociatedExpression()->getStmtClass() !=
2825 SC.getAssociatedExpression()->getStmtClass())
2826 if (!(isa<OMPArraySectionExpr>(
2827 SC.getAssociatedExpression()) &&
2828 isa<ArraySubscriptExpr>(
2829 CCI->getAssociatedExpression())))
2830 return false;
2831
Alexey Bataeve3727102018-04-18 15:57:46 +00002832 const Decl *CCD = CCI->getAssociatedDeclaration();
2833 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002834 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2835 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2836 if (SCD != CCD)
2837 return false;
2838 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002839 if (CCI == CCE)
2840 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002841 }
2842 return true;
2843 })) {
2844 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002845 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002846 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002847 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002848 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002849 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002850 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002851 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002852 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002853 // for task|target directives.
2854 // Skip analysis of arguments of implicitly defined map clause for target
2855 // directives.
2856 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2857 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002858 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002859 if (CC)
2860 Visit(CC);
2861 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002862 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002863 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002864 // Check implicitly captured variables.
2865 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002866 }
2867 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002868 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002869 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002870 // Check implicitly captured variables in the task-based directives to
2871 // check if they must be firstprivatized.
2872 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002873 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002874 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002875 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002876
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002877 void visitSubCaptures(CapturedStmt *S) {
2878 for (const CapturedStmt::Capture &Cap : S->captures()) {
2879 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
2880 continue;
2881 VarDecl *VD = Cap.getCapturedVar();
2882 // Do not try to map the variable if it or its sub-component was mapped
2883 // already.
2884 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2885 Stack->checkMappableExprComponentListsForDecl(
2886 VD, /*CurrentRegionOnly=*/true,
2887 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2888 OpenMPClauseKind) { return true; }))
2889 continue;
2890 DeclRefExpr *DRE = buildDeclRefExpr(
2891 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2892 Cap.getLocation(), /*RefersToCapture=*/true);
2893 Visit(DRE);
2894 }
2895 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002896 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002897 ArrayRef<Expr *> getImplicitFirstprivate() const {
2898 return ImplicitFirstprivate;
2899 }
2900 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002902 return VarsWithInheritedDSA;
2903 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002904
Alexey Bataev7ff55242014-06-19 09:13:45 +00002905 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002906 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2907 // Process declare target link variables for the target directives.
2908 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2909 for (DeclRefExpr *E : Stack->getLinkGlobals())
2910 Visit(E);
2911 }
2912 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002913};
Alexey Bataeved09d242014-05-28 05:53:51 +00002914} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002915
Alexey Bataevbae9a792014-06-27 10:37:06 +00002916void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002917 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002918 case OMPD_parallel:
2919 case OMPD_parallel_for:
2920 case OMPD_parallel_for_simd:
2921 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002922 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002923 case OMPD_teams_distribute:
2924 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002925 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002926 QualType KmpInt32PtrTy =
2927 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002928 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002929 std::make_pair(".global_tid.", KmpInt32PtrTy),
2930 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2931 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002932 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002933 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2934 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002935 break;
2936 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002937 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002938 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002939 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002940 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002941 case OMPD_target_teams_distribute:
2942 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002943 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2944 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2945 QualType KmpInt32PtrTy =
2946 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2947 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002948 FunctionProtoType::ExtProtoInfo EPI;
2949 EPI.Variadic = true;
2950 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2951 Sema::CapturedParamNameType Params[] = {
2952 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002953 std::make_pair(".part_id.", KmpInt32PtrTy),
2954 std::make_pair(".privates.", VoidPtrTy),
2955 std::make_pair(
2956 ".copy_fn.",
2957 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002958 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2959 std::make_pair(StringRef(), QualType()) // __context with shared vars
2960 };
2961 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2962 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002963 // Mark this captured region as inlined, because we don't use outlined
2964 // function directly.
2965 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2966 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002967 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002968 Sema::CapturedParamNameType ParamsTarget[] = {
2969 std::make_pair(StringRef(), QualType()) // __context with shared vars
2970 };
2971 // Start a captured region for 'target' with no implicit parameters.
2972 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2973 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002974 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002975 std::make_pair(".global_tid.", KmpInt32PtrTy),
2976 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2977 std::make_pair(StringRef(), QualType()) // __context with shared vars
2978 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002979 // Start a captured region for 'teams' or 'parallel'. Both regions have
2980 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002981 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002982 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002983 break;
2984 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002985 case OMPD_target:
2986 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002987 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2988 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2989 QualType KmpInt32PtrTy =
2990 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2991 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002992 FunctionProtoType::ExtProtoInfo EPI;
2993 EPI.Variadic = true;
2994 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2995 Sema::CapturedParamNameType Params[] = {
2996 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002997 std::make_pair(".part_id.", KmpInt32PtrTy),
2998 std::make_pair(".privates.", VoidPtrTy),
2999 std::make_pair(
3000 ".copy_fn.",
3001 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003002 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3003 std::make_pair(StringRef(), QualType()) // __context with shared vars
3004 };
3005 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3006 Params);
3007 // Mark this captured region as inlined, because we don't use outlined
3008 // function directly.
3009 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3010 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003011 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003012 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3013 std::make_pair(StringRef(), QualType()));
3014 break;
3015 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003016 case OMPD_simd:
3017 case OMPD_for:
3018 case OMPD_for_simd:
3019 case OMPD_sections:
3020 case OMPD_section:
3021 case OMPD_single:
3022 case OMPD_master:
3023 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003024 case OMPD_taskgroup:
3025 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003026 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003027 case OMPD_ordered:
3028 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003029 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003030 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003031 std::make_pair(StringRef(), QualType()) // __context with shared vars
3032 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003033 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3034 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003035 break;
3036 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003037 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003038 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3039 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3040 QualType KmpInt32PtrTy =
3041 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3042 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003043 FunctionProtoType::ExtProtoInfo EPI;
3044 EPI.Variadic = true;
3045 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003046 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003047 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003048 std::make_pair(".part_id.", KmpInt32PtrTy),
3049 std::make_pair(".privates.", VoidPtrTy),
3050 std::make_pair(
3051 ".copy_fn.",
3052 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003053 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003054 std::make_pair(StringRef(), QualType()) // __context with shared vars
3055 };
3056 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3057 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003058 // Mark this captured region as inlined, because we don't use outlined
3059 // function directly.
3060 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3061 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003062 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003063 break;
3064 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003065 case OMPD_taskloop:
3066 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003067 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003068 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3069 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003070 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003071 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3072 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003073 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003074 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3075 .withConst();
3076 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3077 QualType KmpInt32PtrTy =
3078 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3079 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003080 FunctionProtoType::ExtProtoInfo EPI;
3081 EPI.Variadic = true;
3082 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003083 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003084 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003085 std::make_pair(".part_id.", KmpInt32PtrTy),
3086 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003087 std::make_pair(
3088 ".copy_fn.",
3089 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3090 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3091 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003092 std::make_pair(".ub.", KmpUInt64Ty),
3093 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003094 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003095 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003096 std::make_pair(StringRef(), QualType()) // __context with shared vars
3097 };
3098 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3099 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003100 // Mark this captured region as inlined, because we don't use outlined
3101 // function directly.
3102 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3103 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003104 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003105 break;
3106 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003107 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003108 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003109 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003110 QualType KmpInt32PtrTy =
3111 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3112 Sema::CapturedParamNameType Params[] = {
3113 std::make_pair(".global_tid.", KmpInt32PtrTy),
3114 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003115 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3116 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003117 std::make_pair(StringRef(), QualType()) // __context with shared vars
3118 };
3119 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3120 Params);
3121 break;
3122 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003123 case OMPD_target_teams_distribute_parallel_for:
3124 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003125 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003126 QualType KmpInt32PtrTy =
3127 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003128 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003129
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003130 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003131 FunctionProtoType::ExtProtoInfo EPI;
3132 EPI.Variadic = true;
3133 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3134 Sema::CapturedParamNameType Params[] = {
3135 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003136 std::make_pair(".part_id.", KmpInt32PtrTy),
3137 std::make_pair(".privates.", VoidPtrTy),
3138 std::make_pair(
3139 ".copy_fn.",
3140 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003141 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3142 std::make_pair(StringRef(), QualType()) // __context with shared vars
3143 };
3144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3145 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003146 // Mark this captured region as inlined, because we don't use outlined
3147 // function directly.
3148 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3149 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003150 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003151 Sema::CapturedParamNameType ParamsTarget[] = {
3152 std::make_pair(StringRef(), QualType()) // __context with shared vars
3153 };
3154 // Start a captured region for 'target' with no implicit parameters.
3155 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3156 ParamsTarget);
3157
3158 Sema::CapturedParamNameType ParamsTeams[] = {
3159 std::make_pair(".global_tid.", KmpInt32PtrTy),
3160 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3161 std::make_pair(StringRef(), QualType()) // __context with shared vars
3162 };
3163 // Start a captured region for 'target' with no implicit parameters.
3164 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3165 ParamsTeams);
3166
3167 Sema::CapturedParamNameType ParamsParallel[] = {
3168 std::make_pair(".global_tid.", KmpInt32PtrTy),
3169 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003170 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3171 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003172 std::make_pair(StringRef(), QualType()) // __context with shared vars
3173 };
3174 // Start a captured region for 'teams' or 'parallel'. Both regions have
3175 // the same implicit parameters.
3176 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3177 ParamsParallel);
3178 break;
3179 }
3180
Alexey Bataev46506272017-12-05 17:41:34 +00003181 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003182 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003183 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003184 QualType KmpInt32PtrTy =
3185 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3186
3187 Sema::CapturedParamNameType ParamsTeams[] = {
3188 std::make_pair(".global_tid.", KmpInt32PtrTy),
3189 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3190 std::make_pair(StringRef(), QualType()) // __context with shared vars
3191 };
3192 // Start a captured region for 'target' with no implicit parameters.
3193 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3194 ParamsTeams);
3195
3196 Sema::CapturedParamNameType ParamsParallel[] = {
3197 std::make_pair(".global_tid.", KmpInt32PtrTy),
3198 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003199 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3200 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003201 std::make_pair(StringRef(), QualType()) // __context with shared vars
3202 };
3203 // Start a captured region for 'teams' or 'parallel'. Both regions have
3204 // the same implicit parameters.
3205 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3206 ParamsParallel);
3207 break;
3208 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003209 case OMPD_target_update:
3210 case OMPD_target_enter_data:
3211 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003212 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3213 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3214 QualType KmpInt32PtrTy =
3215 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3216 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003217 FunctionProtoType::ExtProtoInfo EPI;
3218 EPI.Variadic = true;
3219 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3220 Sema::CapturedParamNameType Params[] = {
3221 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003222 std::make_pair(".part_id.", KmpInt32PtrTy),
3223 std::make_pair(".privates.", VoidPtrTy),
3224 std::make_pair(
3225 ".copy_fn.",
3226 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003227 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3228 std::make_pair(StringRef(), QualType()) // __context with shared vars
3229 };
3230 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3231 Params);
3232 // Mark this captured region as inlined, because we don't use outlined
3233 // function directly.
3234 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3235 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003236 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003237 break;
3238 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003239 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003240 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003241 case OMPD_taskyield:
3242 case OMPD_barrier:
3243 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003244 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003245 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003246 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003247 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003248 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003249 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003250 case OMPD_declare_target:
3251 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003252 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003253 llvm_unreachable("OpenMP Directive is not allowed");
3254 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003255 llvm_unreachable("Unknown OpenMP directive");
3256 }
3257}
3258
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003259int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3260 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3261 getOpenMPCaptureRegions(CaptureRegions, DKind);
3262 return CaptureRegions.size();
3263}
3264
Alexey Bataev3392d762016-02-16 11:18:12 +00003265static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003266 Expr *CaptureExpr, bool WithInit,
3267 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003268 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003269 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003270 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003271 QualType Ty = Init->getType();
3272 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003273 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003274 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003275 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003276 Ty = C.getPointerType(Ty);
3277 ExprResult Res =
3278 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3279 if (!Res.isUsable())
3280 return nullptr;
3281 Init = Res.get();
3282 }
Alexey Bataev61205072016-03-02 04:57:40 +00003283 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003284 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003285 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003286 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003287 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003288 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003289 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003290 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003291 return CED;
3292}
3293
Alexey Bataev61205072016-03-02 04:57:40 +00003294static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3295 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003296 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003297 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003298 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003299 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003300 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3301 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003302 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003303 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003304}
3305
Alexey Bataev5a3af132016-03-29 08:58:54 +00003306static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003307 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003308 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003309 OMPCapturedExprDecl *CD = buildCaptureDecl(
3310 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3311 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003312 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3313 CaptureExpr->getExprLoc());
3314 }
3315 ExprResult Res = Ref;
3316 if (!S.getLangOpts().CPlusPlus &&
3317 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003318 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003319 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003320 if (!Res.isUsable())
3321 return ExprError();
3322 }
3323 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003324}
3325
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003326namespace {
3327// OpenMP directives parsed in this section are represented as a
3328// CapturedStatement with an associated statement. If a syntax error
3329// is detected during the parsing of the associated statement, the
3330// compiler must abort processing and close the CapturedStatement.
3331//
3332// Combined directives such as 'target parallel' have more than one
3333// nested CapturedStatements. This RAII ensures that we unwind out
3334// of all the nested CapturedStatements when an error is found.
3335class CaptureRegionUnwinderRAII {
3336private:
3337 Sema &S;
3338 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003339 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003340
3341public:
3342 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3343 OpenMPDirectiveKind DKind)
3344 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3345 ~CaptureRegionUnwinderRAII() {
3346 if (ErrorFound) {
3347 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3348 while (--ThisCaptureLevel >= 0)
3349 S.ActOnCapturedRegionError();
3350 }
3351 }
3352};
3353} // namespace
3354
Alexey Bataevb600ae32019-07-01 17:46:52 +00003355void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3356 // Capture variables captured by reference in lambdas for target-based
3357 // directives.
3358 if (!CurContext->isDependentContext() &&
3359 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3360 isOpenMPTargetDataManagementDirective(
3361 DSAStack->getCurrentDirective()))) {
3362 QualType Type = V->getType();
3363 if (const auto *RD = Type.getCanonicalType()
3364 .getNonReferenceType()
3365 ->getAsCXXRecordDecl()) {
3366 bool SavedForceCaptureByReferenceInTargetExecutable =
3367 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3368 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3369 /*V=*/true);
3370 if (RD->isLambda()) {
3371 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3372 FieldDecl *ThisCapture;
3373 RD->getCaptureFields(Captures, ThisCapture);
3374 for (const LambdaCapture &LC : RD->captures()) {
3375 if (LC.getCaptureKind() == LCK_ByRef) {
3376 VarDecl *VD = LC.getCapturedVar();
3377 DeclContext *VDC = VD->getDeclContext();
3378 if (!VDC->Encloses(CurContext))
3379 continue;
3380 MarkVariableReferenced(LC.getLocation(), VD);
3381 } else if (LC.getCaptureKind() == LCK_This) {
3382 QualType ThisTy = getCurrentThisType();
3383 if (!ThisTy.isNull() &&
3384 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3385 CheckCXXThisCapture(LC.getLocation());
3386 }
3387 }
3388 }
3389 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3390 SavedForceCaptureByReferenceInTargetExecutable);
3391 }
3392 }
3393}
3394
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003395StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3396 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003397 bool ErrorFound = false;
3398 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3399 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003400 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003401 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003402 return StmtError();
3403 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003404
Alexey Bataev2ba67042017-11-28 21:11:44 +00003405 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3406 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003407 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003408 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003409 SmallVector<const OMPLinearClause *, 4> LCs;
3410 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003411 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003412 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003413 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3414 Clause->getClauseKind() == OMPC_in_reduction) {
3415 // Capture taskgroup task_reduction descriptors inside the tasking regions
3416 // with the corresponding in_reduction items.
3417 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003418 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003419 if (E)
3420 MarkDeclarationsReferencedInExpr(E);
3421 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003422 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003423 Clause->getClauseKind() == OMPC_copyprivate ||
3424 (getLangOpts().OpenMPUseTLS &&
3425 getASTContext().getTargetInfo().isTLSSupported() &&
3426 Clause->getClauseKind() == OMPC_copyin)) {
3427 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003428 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003429 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003430 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003431 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003432 }
3433 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003434 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003435 } else if (CaptureRegions.size() > 1 ||
3436 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003437 if (auto *C = OMPClauseWithPreInit::get(Clause))
3438 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003439 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003440 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003441 MarkDeclarationsReferencedInExpr(E);
3442 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003443 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003444 if (Clause->getClauseKind() == OMPC_schedule)
3445 SC = cast<OMPScheduleClause>(Clause);
3446 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003447 OC = cast<OMPOrderedClause>(Clause);
3448 else if (Clause->getClauseKind() == OMPC_linear)
3449 LCs.push_back(cast<OMPLinearClause>(Clause));
3450 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003451 // OpenMP, 2.7.1 Loop Construct, Restrictions
3452 // The nonmonotonic modifier cannot be specified if an ordered clause is
3453 // specified.
3454 if (SC &&
3455 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3456 SC->getSecondScheduleModifier() ==
3457 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3458 OC) {
3459 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3460 ? SC->getFirstScheduleModifierLoc()
3461 : SC->getSecondScheduleModifierLoc(),
3462 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003463 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003464 ErrorFound = true;
3465 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003466 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003467 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003468 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003469 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003470 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003471 ErrorFound = true;
3472 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003473 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3474 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3475 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003476 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003477 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3478 ErrorFound = true;
3479 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003480 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003481 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003482 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003483 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003484 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003485 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003486 // Mark all variables in private list clauses as used in inner region.
3487 // Required for proper codegen of combined directives.
3488 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003489 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003490 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003491 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3492 // Find the particular capture region for the clause if the
3493 // directive is a combined one with multiple capture regions.
3494 // If the directive is not a combined one, the capture region
3495 // associated with the clause is OMPD_unknown and is generated
3496 // only once.
3497 if (CaptureRegion == ThisCaptureRegion ||
3498 CaptureRegion == OMPD_unknown) {
3499 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003500 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003501 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3502 }
3503 }
3504 }
3505 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003506 if (++CompletedRegions == CaptureRegions.size())
3507 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003508 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003509 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003510 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003511}
3512
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003513static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3514 OpenMPDirectiveKind CancelRegion,
3515 SourceLocation StartLoc) {
3516 // CancelRegion is only needed for cancel and cancellation_point.
3517 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3518 return false;
3519
3520 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3521 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3522 return false;
3523
3524 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3525 << getOpenMPDirectiveName(CancelRegion);
3526 return true;
3527}
3528
Alexey Bataeve3727102018-04-18 15:57:46 +00003529static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003530 OpenMPDirectiveKind CurrentRegion,
3531 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003532 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003533 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003534 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003535 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3536 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003537 bool NestingProhibited = false;
3538 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003539 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003540 enum {
3541 NoRecommend,
3542 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003543 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003544 ShouldBeInTargetRegion,
3545 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003546 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003547 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003548 // OpenMP [2.16, Nesting of Regions]
3549 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003550 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003551 // An ordered construct with the simd clause is the only OpenMP
3552 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003553 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003554 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3555 // message.
3556 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3557 ? diag::err_omp_prohibited_region_simd
3558 : diag::warn_omp_nesting_simd);
3559 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003560 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003561 if (ParentRegion == OMPD_atomic) {
3562 // OpenMP [2.16, Nesting of Regions]
3563 // OpenMP constructs may not be nested inside an atomic region.
3564 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3565 return true;
3566 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003567 if (CurrentRegion == OMPD_section) {
3568 // OpenMP [2.7.2, sections Construct, Restrictions]
3569 // Orphaned section directives are prohibited. That is, the section
3570 // directives must appear within the sections construct and must not be
3571 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003572 if (ParentRegion != OMPD_sections &&
3573 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003574 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3575 << (ParentRegion != OMPD_unknown)
3576 << getOpenMPDirectiveName(ParentRegion);
3577 return true;
3578 }
3579 return false;
3580 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003581 // Allow some constructs (except teams and cancellation constructs) to be
3582 // orphaned (they could be used in functions, called from OpenMP regions
3583 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003584 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003585 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3586 CurrentRegion != OMPD_cancellation_point &&
3587 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003588 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003589 if (CurrentRegion == OMPD_cancellation_point ||
3590 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003591 // OpenMP [2.16, Nesting of Regions]
3592 // A cancellation point construct for which construct-type-clause is
3593 // taskgroup must be nested inside a task construct. A cancellation
3594 // point construct for which construct-type-clause is not taskgroup must
3595 // be closely nested inside an OpenMP construct that matches the type
3596 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003597 // A cancel construct for which construct-type-clause is taskgroup must be
3598 // nested inside a task construct. A cancel construct for which
3599 // construct-type-clause is not taskgroup must be closely nested inside an
3600 // OpenMP construct that matches the type specified in
3601 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003602 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003603 !((CancelRegion == OMPD_parallel &&
3604 (ParentRegion == OMPD_parallel ||
3605 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003606 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003607 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003608 ParentRegion == OMPD_target_parallel_for ||
3609 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003610 ParentRegion == OMPD_teams_distribute_parallel_for ||
3611 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003612 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3613 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003614 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3615 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003616 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003617 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003618 // OpenMP [2.16, Nesting of Regions]
3619 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003620 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003621 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003622 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003623 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3624 // OpenMP [2.16, Nesting of Regions]
3625 // A critical region may not be nested (closely or otherwise) inside a
3626 // critical region with the same name. Note that this restriction is not
3627 // sufficient to prevent deadlock.
3628 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003629 bool DeadLock = Stack->hasDirective(
3630 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3631 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003632 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003633 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3634 PreviousCriticalLoc = Loc;
3635 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003636 }
3637 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003638 },
3639 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003640 if (DeadLock) {
3641 SemaRef.Diag(StartLoc,
3642 diag::err_omp_prohibited_region_critical_same_name)
3643 << CurrentName.getName();
3644 if (PreviousCriticalLoc.isValid())
3645 SemaRef.Diag(PreviousCriticalLoc,
3646 diag::note_omp_previous_critical_region);
3647 return true;
3648 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003649 } else if (CurrentRegion == OMPD_barrier) {
3650 // OpenMP [2.16, Nesting of Regions]
3651 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003652 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003653 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3654 isOpenMPTaskingDirective(ParentRegion) ||
3655 ParentRegion == OMPD_master ||
3656 ParentRegion == OMPD_critical ||
3657 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003658 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003659 !isOpenMPParallelDirective(CurrentRegion) &&
3660 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003661 // OpenMP [2.16, Nesting of Regions]
3662 // A worksharing region may not be closely nested inside a worksharing,
3663 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003664 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3665 isOpenMPTaskingDirective(ParentRegion) ||
3666 ParentRegion == OMPD_master ||
3667 ParentRegion == OMPD_critical ||
3668 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003669 Recommend = ShouldBeInParallelRegion;
3670 } else if (CurrentRegion == OMPD_ordered) {
3671 // OpenMP [2.16, Nesting of Regions]
3672 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003673 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003674 // An ordered region must be closely nested inside a loop region (or
3675 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003676 // OpenMP [2.8.1,simd Construct, Restrictions]
3677 // An ordered construct with the simd clause is the only OpenMP construct
3678 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003679 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003680 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003681 !(isOpenMPSimdDirective(ParentRegion) ||
3682 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003683 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003684 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003685 // OpenMP [2.16, Nesting of Regions]
3686 // If specified, a teams construct must be contained within a target
3687 // construct.
3688 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003689 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003690 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003691 }
Kelvin Libf594a52016-12-17 05:48:59 +00003692 if (!NestingProhibited &&
3693 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3694 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3695 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003696 // OpenMP [2.16, Nesting of Regions]
3697 // distribute, parallel, parallel sections, parallel workshare, and the
3698 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3699 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003700 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3701 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003702 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003703 }
David Majnemer9d168222016-08-05 17:44:54 +00003704 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003705 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003706 // OpenMP 4.5 [2.17 Nesting of Regions]
3707 // The region associated with the distribute construct must be strictly
3708 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003709 NestingProhibited =
3710 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003711 Recommend = ShouldBeInTeamsRegion;
3712 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003713 if (!NestingProhibited &&
3714 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3715 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3716 // OpenMP 4.5 [2.17 Nesting of Regions]
3717 // If a target, target update, target data, target enter data, or
3718 // target exit data construct is encountered during execution of a
3719 // target region, the behavior is unspecified.
3720 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003721 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003722 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003723 if (isOpenMPTargetExecutionDirective(K)) {
3724 OffendingRegion = K;
3725 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003726 }
3727 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003728 },
3729 false /* don't skip top directive */);
3730 CloseNesting = false;
3731 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003732 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003733 if (OrphanSeen) {
3734 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3735 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3736 } else {
3737 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3738 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3739 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3740 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003741 return true;
3742 }
3743 }
3744 return false;
3745}
3746
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003747static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3748 ArrayRef<OMPClause *> Clauses,
3749 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3750 bool ErrorFound = false;
3751 unsigned NamedModifiersNumber = 0;
3752 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3753 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003754 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003755 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003756 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3757 // At most one if clause without a directive-name-modifier can appear on
3758 // the directive.
3759 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3760 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003761 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003762 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3763 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3764 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003765 } else if (CurNM != OMPD_unknown) {
3766 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003767 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003768 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003769 FoundNameModifiers[CurNM] = IC;
3770 if (CurNM == OMPD_unknown)
3771 continue;
3772 // Check if the specified name modifier is allowed for the current
3773 // directive.
3774 // At most one if clause with the particular directive-name-modifier can
3775 // appear on the directive.
3776 bool MatchFound = false;
3777 for (auto NM : AllowedNameModifiers) {
3778 if (CurNM == NM) {
3779 MatchFound = true;
3780 break;
3781 }
3782 }
3783 if (!MatchFound) {
3784 S.Diag(IC->getNameModifierLoc(),
3785 diag::err_omp_wrong_if_directive_name_modifier)
3786 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3787 ErrorFound = true;
3788 }
3789 }
3790 }
3791 // If any if clause on the directive includes a directive-name-modifier then
3792 // all if clauses on the directive must include a directive-name-modifier.
3793 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3794 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003795 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003796 diag::err_omp_no_more_if_clause);
3797 } else {
3798 std::string Values;
3799 std::string Sep(", ");
3800 unsigned AllowedCnt = 0;
3801 unsigned TotalAllowedNum =
3802 AllowedNameModifiers.size() - NamedModifiersNumber;
3803 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3804 ++Cnt) {
3805 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3806 if (!FoundNameModifiers[NM]) {
3807 Values += "'";
3808 Values += getOpenMPDirectiveName(NM);
3809 Values += "'";
3810 if (AllowedCnt + 2 == TotalAllowedNum)
3811 Values += " or ";
3812 else if (AllowedCnt + 1 != TotalAllowedNum)
3813 Values += Sep;
3814 ++AllowedCnt;
3815 }
3816 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003817 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003818 diag::err_omp_unnamed_if_clause)
3819 << (TotalAllowedNum > 1) << Values;
3820 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003821 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003822 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3823 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003824 ErrorFound = true;
3825 }
3826 return ErrorFound;
3827}
3828
Alexey Bataeve106f252019-04-01 14:25:31 +00003829static std::pair<ValueDecl *, bool>
3830getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
3831 SourceRange &ERange, bool AllowArraySection = false) {
3832 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3833 RefExpr->containsUnexpandedParameterPack())
3834 return std::make_pair(nullptr, true);
3835
3836 // OpenMP [3.1, C/C++]
3837 // A list item is a variable name.
3838 // OpenMP [2.9.3.3, Restrictions, p.1]
3839 // A variable that is part of another variable (as an array or
3840 // structure element) cannot appear in a private clause.
3841 RefExpr = RefExpr->IgnoreParens();
3842 enum {
3843 NoArrayExpr = -1,
3844 ArraySubscript = 0,
3845 OMPArraySection = 1
3846 } IsArrayExpr = NoArrayExpr;
3847 if (AllowArraySection) {
3848 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
3849 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
3850 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3851 Base = TempASE->getBase()->IgnoreParenImpCasts();
3852 RefExpr = Base;
3853 IsArrayExpr = ArraySubscript;
3854 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
3855 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
3856 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
3857 Base = TempOASE->getBase()->IgnoreParenImpCasts();
3858 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3859 Base = TempASE->getBase()->IgnoreParenImpCasts();
3860 RefExpr = Base;
3861 IsArrayExpr = OMPArraySection;
3862 }
3863 }
3864 ELoc = RefExpr->getExprLoc();
3865 ERange = RefExpr->getSourceRange();
3866 RefExpr = RefExpr->IgnoreParenImpCasts();
3867 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3868 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
3869 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
3870 (S.getCurrentThisType().isNull() || !ME ||
3871 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
3872 !isa<FieldDecl>(ME->getMemberDecl()))) {
3873 if (IsArrayExpr != NoArrayExpr) {
3874 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
3875 << ERange;
3876 } else {
3877 S.Diag(ELoc,
3878 AllowArraySection
3879 ? diag::err_omp_expected_var_name_member_expr_or_array_item
3880 : diag::err_omp_expected_var_name_member_expr)
3881 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
3882 }
3883 return std::make_pair(nullptr, false);
3884 }
3885 return std::make_pair(
3886 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
3887}
3888
3889static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00003890 ArrayRef<OMPClause *> Clauses) {
3891 assert(!S.CurContext->isDependentContext() &&
3892 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00003893 auto AllocateRange =
3894 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00003895 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
3896 DeclToCopy;
3897 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
3898 return isOpenMPPrivate(C->getClauseKind());
3899 });
3900 for (OMPClause *Cl : PrivateRange) {
3901 MutableArrayRef<Expr *>::iterator I, It, Et;
3902 if (Cl->getClauseKind() == OMPC_private) {
3903 auto *PC = cast<OMPPrivateClause>(Cl);
3904 I = PC->private_copies().begin();
3905 It = PC->varlist_begin();
3906 Et = PC->varlist_end();
3907 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
3908 auto *PC = cast<OMPFirstprivateClause>(Cl);
3909 I = PC->private_copies().begin();
3910 It = PC->varlist_begin();
3911 Et = PC->varlist_end();
3912 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
3913 auto *PC = cast<OMPLastprivateClause>(Cl);
3914 I = PC->private_copies().begin();
3915 It = PC->varlist_begin();
3916 Et = PC->varlist_end();
3917 } else if (Cl->getClauseKind() == OMPC_linear) {
3918 auto *PC = cast<OMPLinearClause>(Cl);
3919 I = PC->privates().begin();
3920 It = PC->varlist_begin();
3921 Et = PC->varlist_end();
3922 } else if (Cl->getClauseKind() == OMPC_reduction) {
3923 auto *PC = cast<OMPReductionClause>(Cl);
3924 I = PC->privates().begin();
3925 It = PC->varlist_begin();
3926 Et = PC->varlist_end();
3927 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
3928 auto *PC = cast<OMPTaskReductionClause>(Cl);
3929 I = PC->privates().begin();
3930 It = PC->varlist_begin();
3931 Et = PC->varlist_end();
3932 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
3933 auto *PC = cast<OMPInReductionClause>(Cl);
3934 I = PC->privates().begin();
3935 It = PC->varlist_begin();
3936 Et = PC->varlist_end();
3937 } else {
3938 llvm_unreachable("Expected private clause.");
3939 }
3940 for (Expr *E : llvm::make_range(It, Et)) {
3941 if (!*I) {
3942 ++I;
3943 continue;
3944 }
3945 SourceLocation ELoc;
3946 SourceRange ERange;
3947 Expr *SimpleRefExpr = E;
3948 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3949 /*AllowArraySection=*/true);
3950 DeclToCopy.try_emplace(Res.first,
3951 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
3952 ++I;
3953 }
3954 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003955 for (OMPClause *C : AllocateRange) {
3956 auto *AC = cast<OMPAllocateClause>(C);
3957 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3958 getAllocatorKind(S, Stack, AC->getAllocator());
3959 // OpenMP, 2.11.4 allocate Clause, Restrictions.
3960 // For task, taskloop or target directives, allocation requests to memory
3961 // allocators with the trait access set to thread result in unspecified
3962 // behavior.
3963 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
3964 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
3965 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
3966 S.Diag(AC->getAllocator()->getExprLoc(),
3967 diag::warn_omp_allocate_thread_on_task_target_directive)
3968 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00003969 }
3970 for (Expr *E : AC->varlists()) {
3971 SourceLocation ELoc;
3972 SourceRange ERange;
3973 Expr *SimpleRefExpr = E;
3974 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
3975 ValueDecl *VD = Res.first;
3976 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
3977 if (!isOpenMPPrivate(Data.CKind)) {
3978 S.Diag(E->getExprLoc(),
3979 diag::err_omp_expected_private_copy_for_allocate);
3980 continue;
3981 }
3982 VarDecl *PrivateVD = DeclToCopy[VD];
3983 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
3984 AllocatorKind, AC->getAllocator()))
3985 continue;
3986 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
3987 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00003988 }
3989 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003990}
3991
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003992StmtResult Sema::ActOnOpenMPExecutableDirective(
3993 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3994 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3995 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003996 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003997 // First check CancelRegion which is then used in checkNestingOfRegions.
3998 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3999 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004000 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004001 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004002
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004003 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004004 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004005 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004006 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004007 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004008 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4009
4010 // Check default data sharing attributes for referenced variables.
4011 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004012 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4013 Stmt *S = AStmt;
4014 while (--ThisCaptureLevel >= 0)
4015 S = cast<CapturedStmt>(S)->getCapturedStmt();
4016 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004017 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4018 !isOpenMPTaskingDirective(Kind)) {
4019 // Visit subcaptures to generate implicit clauses for captured vars.
4020 auto *CS = cast<CapturedStmt>(AStmt);
4021 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4022 getOpenMPCaptureRegions(CaptureRegions, Kind);
4023 // Ignore outer tasking regions for target directives.
4024 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4025 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4026 DSAChecker.visitSubCaptures(CS);
4027 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004028 if (DSAChecker.isErrorFound())
4029 return StmtError();
4030 // Generate list of implicitly defined firstprivate variables.
4031 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004032
Alexey Bataev88202be2017-07-27 13:20:36 +00004033 SmallVector<Expr *, 4> ImplicitFirstprivates(
4034 DSAChecker.getImplicitFirstprivate().begin(),
4035 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004036 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4037 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004038 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004039 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004040 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004041 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004042 if (E)
4043 ImplicitFirstprivates.emplace_back(E);
4044 }
4045 }
4046 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004047 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004048 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4049 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004050 ClausesWithImplicit.push_back(Implicit);
4051 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004052 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004053 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004054 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004055 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004056 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004057 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004058 CXXScopeSpec MapperIdScopeSpec;
4059 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004060 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004061 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4062 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4063 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004064 ClausesWithImplicit.emplace_back(Implicit);
4065 ErrorFound |=
4066 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004067 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004068 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004069 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004070 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004071 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004072
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004073 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004074 switch (Kind) {
4075 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004076 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4077 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004078 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004079 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004080 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004081 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4082 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004083 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004084 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004085 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4086 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004087 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004088 case OMPD_for_simd:
4089 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4090 EndLoc, VarsWithInheritedDSA);
4091 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004092 case OMPD_sections:
4093 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4094 EndLoc);
4095 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004096 case OMPD_section:
4097 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004098 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004099 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4100 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004101 case OMPD_single:
4102 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4103 EndLoc);
4104 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004105 case OMPD_master:
4106 assert(ClausesWithImplicit.empty() &&
4107 "No clauses are allowed for 'omp master' directive");
4108 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4109 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004110 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004111 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4112 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004113 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004114 case OMPD_parallel_for:
4115 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4116 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004117 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004118 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004119 case OMPD_parallel_for_simd:
4120 Res = ActOnOpenMPParallelForSimdDirective(
4121 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004122 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004123 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004124 case OMPD_parallel_sections:
4125 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4126 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004127 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004128 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004129 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004130 Res =
4131 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004132 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004133 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004134 case OMPD_taskyield:
4135 assert(ClausesWithImplicit.empty() &&
4136 "No clauses are allowed for 'omp taskyield' directive");
4137 assert(AStmt == nullptr &&
4138 "No associated statement allowed for 'omp taskyield' directive");
4139 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4140 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004141 case OMPD_barrier:
4142 assert(ClausesWithImplicit.empty() &&
4143 "No clauses are allowed for 'omp barrier' directive");
4144 assert(AStmt == nullptr &&
4145 "No associated statement allowed for 'omp barrier' directive");
4146 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4147 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004148 case OMPD_taskwait:
4149 assert(ClausesWithImplicit.empty() &&
4150 "No clauses are allowed for 'omp taskwait' directive");
4151 assert(AStmt == nullptr &&
4152 "No associated statement allowed for 'omp taskwait' directive");
4153 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4154 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004155 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004156 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4157 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004158 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004159 case OMPD_flush:
4160 assert(AStmt == nullptr &&
4161 "No associated statement allowed for 'omp flush' directive");
4162 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4163 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004164 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004165 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4166 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004167 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004168 case OMPD_atomic:
4169 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4170 EndLoc);
4171 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004172 case OMPD_teams:
4173 Res =
4174 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4175 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004176 case OMPD_target:
4177 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4178 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004179 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004180 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004181 case OMPD_target_parallel:
4182 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4183 StartLoc, EndLoc);
4184 AllowedNameModifiers.push_back(OMPD_target);
4185 AllowedNameModifiers.push_back(OMPD_parallel);
4186 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004187 case OMPD_target_parallel_for:
4188 Res = ActOnOpenMPTargetParallelForDirective(
4189 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4190 AllowedNameModifiers.push_back(OMPD_target);
4191 AllowedNameModifiers.push_back(OMPD_parallel);
4192 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004193 case OMPD_cancellation_point:
4194 assert(ClausesWithImplicit.empty() &&
4195 "No clauses are allowed for 'omp cancellation point' directive");
4196 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4197 "cancellation point' directive");
4198 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4199 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004200 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004201 assert(AStmt == nullptr &&
4202 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004203 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4204 CancelRegion);
4205 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004206 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004207 case OMPD_target_data:
4208 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4209 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004210 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004211 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004212 case OMPD_target_enter_data:
4213 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004214 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004215 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4216 break;
Samuel Antao72590762016-01-19 20:04:50 +00004217 case OMPD_target_exit_data:
4218 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004219 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004220 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4221 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004222 case OMPD_taskloop:
4223 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4224 EndLoc, VarsWithInheritedDSA);
4225 AllowedNameModifiers.push_back(OMPD_taskloop);
4226 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004227 case OMPD_taskloop_simd:
4228 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4229 EndLoc, VarsWithInheritedDSA);
4230 AllowedNameModifiers.push_back(OMPD_taskloop);
4231 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004232 case OMPD_distribute:
4233 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4234 EndLoc, VarsWithInheritedDSA);
4235 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004236 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004237 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4238 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004239 AllowedNameModifiers.push_back(OMPD_target_update);
4240 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004241 case OMPD_distribute_parallel_for:
4242 Res = ActOnOpenMPDistributeParallelForDirective(
4243 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4244 AllowedNameModifiers.push_back(OMPD_parallel);
4245 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004246 case OMPD_distribute_parallel_for_simd:
4247 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4248 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4249 AllowedNameModifiers.push_back(OMPD_parallel);
4250 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004251 case OMPD_distribute_simd:
4252 Res = ActOnOpenMPDistributeSimdDirective(
4253 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4254 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004255 case OMPD_target_parallel_for_simd:
4256 Res = ActOnOpenMPTargetParallelForSimdDirective(
4257 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4258 AllowedNameModifiers.push_back(OMPD_target);
4259 AllowedNameModifiers.push_back(OMPD_parallel);
4260 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004261 case OMPD_target_simd:
4262 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4263 EndLoc, VarsWithInheritedDSA);
4264 AllowedNameModifiers.push_back(OMPD_target);
4265 break;
Kelvin Li02532872016-08-05 14:37:37 +00004266 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004267 Res = ActOnOpenMPTeamsDistributeDirective(
4268 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004269 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004270 case OMPD_teams_distribute_simd:
4271 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4272 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4273 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004274 case OMPD_teams_distribute_parallel_for_simd:
4275 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4276 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4277 AllowedNameModifiers.push_back(OMPD_parallel);
4278 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004279 case OMPD_teams_distribute_parallel_for:
4280 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4281 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4282 AllowedNameModifiers.push_back(OMPD_parallel);
4283 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004284 case OMPD_target_teams:
4285 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4286 EndLoc);
4287 AllowedNameModifiers.push_back(OMPD_target);
4288 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004289 case OMPD_target_teams_distribute:
4290 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4291 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4292 AllowedNameModifiers.push_back(OMPD_target);
4293 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004294 case OMPD_target_teams_distribute_parallel_for:
4295 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4296 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4297 AllowedNameModifiers.push_back(OMPD_target);
4298 AllowedNameModifiers.push_back(OMPD_parallel);
4299 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004300 case OMPD_target_teams_distribute_parallel_for_simd:
4301 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4302 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4303 AllowedNameModifiers.push_back(OMPD_target);
4304 AllowedNameModifiers.push_back(OMPD_parallel);
4305 break;
Kelvin Lida681182017-01-10 18:08:18 +00004306 case OMPD_target_teams_distribute_simd:
4307 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4308 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4309 AllowedNameModifiers.push_back(OMPD_target);
4310 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004311 case OMPD_declare_target:
4312 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004313 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004314 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004315 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004316 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004317 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004318 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004319 llvm_unreachable("OpenMP Directive is not allowed");
4320 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004321 llvm_unreachable("Unknown OpenMP directive");
4322 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004323
Roman Lebedevb5700602019-03-20 16:32:36 +00004324 ErrorFound = Res.isInvalid() || ErrorFound;
4325
Alexey Bataev412254a2019-05-09 18:44:53 +00004326 // Check variables in the clauses if default(none) was specified.
4327 if (DSAStack->getDefaultDSA() == DSA_none) {
4328 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4329 for (OMPClause *C : Clauses) {
4330 switch (C->getClauseKind()) {
4331 case OMPC_num_threads:
4332 case OMPC_dist_schedule:
4333 // Do not analyse if no parent teams directive.
4334 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4335 break;
4336 continue;
4337 case OMPC_if:
4338 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4339 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4340 break;
4341 continue;
4342 case OMPC_schedule:
4343 break;
4344 case OMPC_ordered:
4345 case OMPC_device:
4346 case OMPC_num_teams:
4347 case OMPC_thread_limit:
4348 case OMPC_priority:
4349 case OMPC_grainsize:
4350 case OMPC_num_tasks:
4351 case OMPC_hint:
4352 case OMPC_collapse:
4353 case OMPC_safelen:
4354 case OMPC_simdlen:
4355 case OMPC_final:
4356 case OMPC_default:
4357 case OMPC_proc_bind:
4358 case OMPC_private:
4359 case OMPC_firstprivate:
4360 case OMPC_lastprivate:
4361 case OMPC_shared:
4362 case OMPC_reduction:
4363 case OMPC_task_reduction:
4364 case OMPC_in_reduction:
4365 case OMPC_linear:
4366 case OMPC_aligned:
4367 case OMPC_copyin:
4368 case OMPC_copyprivate:
4369 case OMPC_nowait:
4370 case OMPC_untied:
4371 case OMPC_mergeable:
4372 case OMPC_allocate:
4373 case OMPC_read:
4374 case OMPC_write:
4375 case OMPC_update:
4376 case OMPC_capture:
4377 case OMPC_seq_cst:
4378 case OMPC_depend:
4379 case OMPC_threads:
4380 case OMPC_simd:
4381 case OMPC_map:
4382 case OMPC_nogroup:
4383 case OMPC_defaultmap:
4384 case OMPC_to:
4385 case OMPC_from:
4386 case OMPC_use_device_ptr:
4387 case OMPC_is_device_ptr:
4388 continue;
4389 case OMPC_allocator:
4390 case OMPC_flush:
4391 case OMPC_threadprivate:
4392 case OMPC_uniform:
4393 case OMPC_unknown:
4394 case OMPC_unified_address:
4395 case OMPC_unified_shared_memory:
4396 case OMPC_reverse_offload:
4397 case OMPC_dynamic_allocators:
4398 case OMPC_atomic_default_mem_order:
4399 llvm_unreachable("Unexpected clause");
4400 }
4401 for (Stmt *CC : C->children()) {
4402 if (CC)
4403 DSAChecker.Visit(CC);
4404 }
4405 }
4406 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4407 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4408 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004409 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004410 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4411 continue;
4412 ErrorFound = true;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004413 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4414 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004415 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004416 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004417
4418 if (!AllowedNameModifiers.empty())
4419 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4420 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004421
Alexey Bataeved09d242014-05-28 05:53:51 +00004422 if (ErrorFound)
4423 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004424
4425 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4426 Res.getAs<OMPExecutableDirective>()
4427 ->getStructuredBlock()
4428 ->setIsOMPStructuredBlock(true);
4429 }
4430
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004431 if (!CurContext->isDependentContext() &&
4432 isOpenMPTargetExecutionDirective(Kind) &&
4433 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4434 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4435 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4436 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4437 // Register target to DSA Stack.
4438 DSAStack->addTargetDirLocation(StartLoc);
4439 }
4440
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004441 return Res;
4442}
4443
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004444Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4445 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004446 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004447 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4448 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004449 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004450 assert(Linears.size() == LinModifiers.size());
4451 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004452 if (!DG || DG.get().isNull())
4453 return DeclGroupPtrTy();
4454
4455 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00004456 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004457 return DG;
4458 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004459 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004460 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4461 ADecl = FTD->getTemplatedDecl();
4462
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004463 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4464 if (!FD) {
4465 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004466 return DeclGroupPtrTy();
4467 }
4468
Alexey Bataev2af33e32016-04-07 12:45:37 +00004469 // OpenMP [2.8.2, declare simd construct, Description]
4470 // The parameter of the simdlen clause must be a constant positive integer
4471 // expression.
4472 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004473 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004474 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004475 // OpenMP [2.8.2, declare simd construct, Description]
4476 // The special this pointer can be used as if was one of the arguments to the
4477 // function in any of the linear, aligned, or uniform clauses.
4478 // The uniform clause declares one or more arguments to have an invariant
4479 // value for all concurrent invocations of the function in the execution of a
4480 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004481 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4482 const Expr *UniformedLinearThis = nullptr;
4483 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004484 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004485 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4486 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004487 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4488 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004489 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004490 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004491 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004492 }
4493 if (isa<CXXThisExpr>(E)) {
4494 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004495 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004496 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004497 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4498 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004499 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004500 // OpenMP [2.8.2, declare simd construct, Description]
4501 // The aligned clause declares that the object to which each list item points
4502 // is aligned to the number of bytes expressed in the optional parameter of
4503 // the aligned clause.
4504 // The special this pointer can be used as if was one of the arguments to the
4505 // function in any of the linear, aligned, or uniform clauses.
4506 // The type of list items appearing in the aligned clause must be array,
4507 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004508 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4509 const Expr *AlignedThis = nullptr;
4510 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004511 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004512 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4513 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4514 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004515 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4516 FD->getParamDecl(PVD->getFunctionScopeIndex())
4517 ->getCanonicalDecl() == CanonPVD) {
4518 // OpenMP [2.8.1, simd construct, Restrictions]
4519 // A list-item cannot appear in more than one aligned clause.
4520 if (AlignedArgs.count(CanonPVD) > 0) {
4521 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4522 << 1 << E->getSourceRange();
4523 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4524 diag::note_omp_explicit_dsa)
4525 << getOpenMPClauseName(OMPC_aligned);
4526 continue;
4527 }
4528 AlignedArgs[CanonPVD] = E;
4529 QualType QTy = PVD->getType()
4530 .getNonReferenceType()
4531 .getUnqualifiedType()
4532 .getCanonicalType();
4533 const Type *Ty = QTy.getTypePtrOrNull();
4534 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4535 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4536 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4537 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4538 }
4539 continue;
4540 }
4541 }
4542 if (isa<CXXThisExpr>(E)) {
4543 if (AlignedThis) {
4544 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4545 << 2 << E->getSourceRange();
4546 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4547 << getOpenMPClauseName(OMPC_aligned);
4548 }
4549 AlignedThis = E;
4550 continue;
4551 }
4552 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4553 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4554 }
4555 // The optional parameter of the aligned clause, alignment, must be a constant
4556 // positive integer expression. If no optional parameter is specified,
4557 // implementation-defined default alignments for SIMD instructions on the
4558 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004559 SmallVector<const Expr *, 4> NewAligns;
4560 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004561 ExprResult Align;
4562 if (E)
4563 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4564 NewAligns.push_back(Align.get());
4565 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004566 // OpenMP [2.8.2, declare simd construct, Description]
4567 // The linear clause declares one or more list items to be private to a SIMD
4568 // lane and to have a linear relationship with respect to the iteration space
4569 // of a loop.
4570 // The special this pointer can be used as if was one of the arguments to the
4571 // function in any of the linear, aligned, or uniform clauses.
4572 // When a linear-step expression is specified in a linear clause it must be
4573 // either a constant integer expression or an integer-typed parameter that is
4574 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004575 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004576 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4577 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004578 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004579 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4580 ++MI;
4581 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004582 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4583 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4584 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004585 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4586 FD->getParamDecl(PVD->getFunctionScopeIndex())
4587 ->getCanonicalDecl() == CanonPVD) {
4588 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4589 // A list-item cannot appear in more than one linear clause.
4590 if (LinearArgs.count(CanonPVD) > 0) {
4591 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4592 << getOpenMPClauseName(OMPC_linear)
4593 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4594 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4595 diag::note_omp_explicit_dsa)
4596 << getOpenMPClauseName(OMPC_linear);
4597 continue;
4598 }
4599 // Each argument can appear in at most one uniform or linear clause.
4600 if (UniformedArgs.count(CanonPVD) > 0) {
4601 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4602 << getOpenMPClauseName(OMPC_linear)
4603 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4604 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4605 diag::note_omp_explicit_dsa)
4606 << getOpenMPClauseName(OMPC_uniform);
4607 continue;
4608 }
4609 LinearArgs[CanonPVD] = E;
4610 if (E->isValueDependent() || E->isTypeDependent() ||
4611 E->isInstantiationDependent() ||
4612 E->containsUnexpandedParameterPack())
4613 continue;
4614 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4615 PVD->getOriginalType());
4616 continue;
4617 }
4618 }
4619 if (isa<CXXThisExpr>(E)) {
4620 if (UniformedLinearThis) {
4621 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4622 << getOpenMPClauseName(OMPC_linear)
4623 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4624 << E->getSourceRange();
4625 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4626 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4627 : OMPC_linear);
4628 continue;
4629 }
4630 UniformedLinearThis = E;
4631 if (E->isValueDependent() || E->isTypeDependent() ||
4632 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4633 continue;
4634 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4635 E->getType());
4636 continue;
4637 }
4638 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4639 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4640 }
4641 Expr *Step = nullptr;
4642 Expr *NewStep = nullptr;
4643 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004644 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004645 // Skip the same step expression, it was checked already.
4646 if (Step == E || !E) {
4647 NewSteps.push_back(E ? NewStep : nullptr);
4648 continue;
4649 }
4650 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004651 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4652 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4653 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004654 if (UniformedArgs.count(CanonPVD) == 0) {
4655 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4656 << Step->getSourceRange();
4657 } else if (E->isValueDependent() || E->isTypeDependent() ||
4658 E->isInstantiationDependent() ||
4659 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004660 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004661 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004662 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004663 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4664 << Step->getSourceRange();
4665 }
4666 continue;
4667 }
4668 NewStep = Step;
4669 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4670 !Step->isInstantiationDependent() &&
4671 !Step->containsUnexpandedParameterPack()) {
4672 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4673 .get();
4674 if (NewStep)
4675 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4676 }
4677 NewSteps.push_back(NewStep);
4678 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004679 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4680 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004681 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004682 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4683 const_cast<Expr **>(Linears.data()), Linears.size(),
4684 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4685 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004686 ADecl->addAttr(NewAttr);
4687 return ConvertDeclToDeclGroup(ADecl);
4688}
4689
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004690StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4691 Stmt *AStmt,
4692 SourceLocation StartLoc,
4693 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004694 if (!AStmt)
4695 return StmtError();
4696
Alexey Bataeve3727102018-04-18 15:57:46 +00004697 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004698 // 1.2.2 OpenMP Language Terminology
4699 // Structured block - An executable statement with a single entry at the
4700 // top and a single exit at the bottom.
4701 // The point of exit cannot be a branch out of the structured block.
4702 // longjmp() and throw() must not violate the entry/exit criteria.
4703 CS->getCapturedDecl()->setNothrow();
4704
Reid Kleckner87a31802018-03-12 21:43:02 +00004705 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004706
Alexey Bataev25e5b442015-09-15 12:52:43 +00004707 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4708 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004709}
4710
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004711namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004712/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004713/// extracting iteration space of each loop in the loop nest, that will be used
4714/// for IR generation.
4715class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004716 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004717 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004718 /// Data-sharing stack.
4719 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004720 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004721 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004722 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004723 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004724 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004725 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004726 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004727 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004728 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004729 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004730 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004731 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004732 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004733 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004734 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004735 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004736 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004737 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004738 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004739 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004740 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004741 /// Var < UB
4742 /// Var <= UB
4743 /// UB > Var
4744 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004745 /// This will have no value when the condition is !=
4746 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004747 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004748 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004749 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004750 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004751 /// The outer loop counter this loop depends on (if any).
4752 const ValueDecl *DepDecl = nullptr;
4753 /// Contains number of loop (starts from 1) on which loop counter init
4754 /// expression of this loop depends on.
4755 Optional<unsigned> InitDependOnLC;
4756 /// Contains number of loop (starts from 1) on which loop counter condition
4757 /// expression of this loop depends on.
4758 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004759 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004760 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004761
4762public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00004763 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
4764 SourceLocation DefaultLoc)
4765 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
4766 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004767 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004768 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004769 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004770 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004771 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004772 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004773 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004774 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004775 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004776 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004777 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004778 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004779 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004780 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004781 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004782 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004783 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004784 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004785 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004786 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004787 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004788 /// True, if the compare operator is strict (<, > or !=).
4789 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004790 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004791 Expr *buildNumIterations(
4792 Scope *S, const bool LimitedType,
4793 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004794 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004795 Expr *
4796 buildPreCond(Scope *S, Expr *Cond,
4797 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004798 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004799 DeclRefExpr *
4800 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4801 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004802 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004803 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004804 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004805 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004806 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004807 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004808 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004809 /// Build loop data with counter value for depend clauses in ordered
4810 /// directives.
4811 Expr *
4812 buildOrderedLoopData(Scope *S, Expr *Counter,
4813 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4814 SourceLocation Loc, Expr *Inc = nullptr,
4815 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004816 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004817 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004818
4819private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004820 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004821 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004822 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004823 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00004824 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
4825 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004826 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004827 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4828 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004829 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004830 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004831};
4832
Alexey Bataeve3727102018-04-18 15:57:46 +00004833bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004834 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004835 assert(!LB && !UB && !Step);
4836 return false;
4837 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004838 return LCDecl->getType()->isDependentType() ||
4839 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4840 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004841}
4842
Alexey Bataeve3727102018-04-18 15:57:46 +00004843bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004844 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00004845 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004846 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004847 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004848 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004849 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004850 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004851 LCDecl = getCanonicalDecl(NewLCDecl);
4852 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004853 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4854 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004855 if ((Ctor->isCopyOrMoveConstructor() ||
4856 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4857 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004858 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004859 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004860 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004861 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004862 return false;
4863}
4864
Alexey Bataev316ccf62019-01-29 18:51:58 +00004865bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4866 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004867 bool StrictOp, SourceRange SR,
4868 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004869 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004870 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4871 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004872 if (!NewUB)
4873 return true;
4874 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004875 if (LessOp)
4876 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004877 TestIsStrictOp = StrictOp;
4878 ConditionSrcRange = SR;
4879 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004880 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004881 return false;
4882}
4883
Alexey Bataeve3727102018-04-18 15:57:46 +00004884bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004885 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004886 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004887 if (!NewStep)
4888 return true;
4889 if (!NewStep->isValueDependent()) {
4890 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004891 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004892 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4893 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004894 if (Val.isInvalid())
4895 return true;
4896 NewStep = Val.get();
4897
4898 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4899 // If test-expr is of form var relational-op b and relational-op is < or
4900 // <= then incr-expr must cause var to increase on each iteration of the
4901 // loop. If test-expr is of form var relational-op b and relational-op is
4902 // > or >= then incr-expr must cause var to decrease on each iteration of
4903 // the loop.
4904 // If test-expr is of form b relational-op var and relational-op is < or
4905 // <= then incr-expr must cause var to decrease on each iteration of the
4906 // loop. If test-expr is of form b relational-op var and relational-op is
4907 // > or >= then incr-expr must cause var to increase on each iteration of
4908 // the loop.
4909 llvm::APSInt Result;
4910 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4911 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4912 bool IsConstNeg =
4913 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004914 bool IsConstPos =
4915 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004916 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004917
4918 // != with increment is treated as <; != with decrement is treated as >
4919 if (!TestIsLessOp.hasValue())
4920 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004921 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004922 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004923 (IsConstNeg || (IsUnsigned && Subtract)) :
4924 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004925 SemaRef.Diag(NewStep->getExprLoc(),
4926 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004927 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004928 SemaRef.Diag(ConditionLoc,
4929 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004930 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004931 return true;
4932 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004933 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004934 NewStep =
4935 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4936 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004937 Subtract = !Subtract;
4938 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004939 }
4940
4941 Step = NewStep;
4942 SubtractStep = Subtract;
4943 return false;
4944}
4945
Alexey Bataev622af1d2019-04-24 19:58:30 +00004946namespace {
4947/// Checker for the non-rectangular loops. Checks if the initializer or
4948/// condition expression references loop counter variable.
4949class LoopCounterRefChecker final
4950 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
4951 Sema &SemaRef;
4952 DSAStackTy &Stack;
4953 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004954 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004955 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004956 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004957 unsigned BaseLoopId = 0;
4958 bool checkDecl(const Expr *E, const ValueDecl *VD) {
4959 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
4960 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
4961 << (IsInitializer ? 0 : 1);
4962 return false;
4963 }
4964 const auto &&Data = Stack.isLoopControlVariable(VD);
4965 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
4966 // The type of the loop iterator on which we depend may not have a random
4967 // access iterator type.
4968 if (Data.first && VD->getType()->isRecordType()) {
4969 SmallString<128> Name;
4970 llvm::raw_svector_ostream OS(Name);
4971 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4972 /*Qualified=*/true);
4973 SemaRef.Diag(E->getExprLoc(),
4974 diag::err_omp_wrong_dependency_iterator_type)
4975 << OS.str();
4976 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
4977 return false;
4978 }
4979 if (Data.first &&
4980 (DepDecl || (PrevDepDecl &&
4981 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
4982 if (!DepDecl && PrevDepDecl)
4983 DepDecl = PrevDepDecl;
4984 SmallString<128> Name;
4985 llvm::raw_svector_ostream OS(Name);
4986 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4987 /*Qualified=*/true);
4988 SemaRef.Diag(E->getExprLoc(),
4989 diag::err_omp_invariant_or_linear_dependency)
4990 << OS.str();
4991 return false;
4992 }
4993 if (Data.first) {
4994 DepDecl = VD;
4995 BaseLoopId = Data.first;
4996 }
4997 return Data.first;
4998 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004999
5000public:
5001 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5002 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005003 if (isa<VarDecl>(VD))
5004 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005005 return false;
5006 }
5007 bool VisitMemberExpr(const MemberExpr *E) {
5008 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5009 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005010 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5011 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005012 }
5013 return false;
5014 }
5015 bool VisitStmt(const Stmt *S) {
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005016 bool Res = true;
5017 for (const Stmt *Child : S->children())
5018 Res = Child && Visit(Child) && Res;
5019 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005020 }
5021 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005022 const ValueDecl *CurLCDecl, bool IsInitializer,
5023 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005024 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005025 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5026 unsigned getBaseLoopId() const {
5027 assert(CurLCDecl && "Expected loop dependency.");
5028 return BaseLoopId;
5029 }
5030 const ValueDecl *getDepDecl() const {
5031 assert(CurLCDecl && "Expected loop dependency.");
5032 return DepDecl;
5033 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005034};
5035} // namespace
5036
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005037Optional<unsigned>
5038OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5039 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005040 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005041 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5042 DepDecl);
5043 if (LoopStmtChecker.Visit(S)) {
5044 DepDecl = LoopStmtChecker.getDepDecl();
5045 return LoopStmtChecker.getBaseLoopId();
5046 }
5047 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005048}
5049
Alexey Bataeve3727102018-04-18 15:57:46 +00005050bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005051 // Check init-expr for canonical loop form and save loop counter
5052 // variable - #Var and its initialization value - #LB.
5053 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5054 // var = lb
5055 // integer-type var = lb
5056 // random-access-iterator-type var = lb
5057 // pointer-type var = lb
5058 //
5059 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005060 if (EmitDiags) {
5061 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5062 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005063 return true;
5064 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005065 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5066 if (!ExprTemp->cleanupsHaveSideEffects())
5067 S = ExprTemp->getSubExpr();
5068
Alexander Musmana5f070a2014-10-01 06:03:56 +00005069 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005070 if (Expr *E = dyn_cast<Expr>(S))
5071 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005072 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005073 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005074 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005075 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5076 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5077 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005078 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5079 EmitDiags);
5080 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005081 }
5082 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5083 if (ME->isArrow() &&
5084 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005085 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5086 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005087 }
5088 }
David Majnemer9d168222016-08-05 17:44:54 +00005089 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005090 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005091 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005092 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005093 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005094 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005095 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005096 diag::ext_omp_loop_not_canonical_init)
5097 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005098 return setLCDeclAndLB(
5099 Var,
5100 buildDeclRefExpr(SemaRef, Var,
5101 Var->getType().getNonReferenceType(),
5102 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005103 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005104 }
5105 }
5106 }
David Majnemer9d168222016-08-05 17:44:54 +00005107 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005108 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005109 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005110 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005111 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5112 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005113 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5114 EmitDiags);
5115 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005116 }
5117 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5118 if (ME->isArrow() &&
5119 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005120 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5121 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005122 }
5123 }
5124 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005125
Alexey Bataeve3727102018-04-18 15:57:46 +00005126 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005127 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005128 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005129 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005130 << S->getSourceRange();
5131 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005132 return true;
5133}
5134
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005135/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005136/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005137static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005138 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005139 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005140 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005141 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005142 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005143 if ((Ctor->isCopyOrMoveConstructor() ||
5144 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5145 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005146 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005147 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5148 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005149 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005150 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005151 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005152 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5153 return getCanonicalDecl(ME->getMemberDecl());
5154 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005155}
5156
Alexey Bataeve3727102018-04-18 15:57:46 +00005157bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005158 // Check test-expr for canonical form, save upper-bound UB, flags for
5159 // less/greater and for strict/non-strict comparison.
5160 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5161 // var relational-op b
5162 // b relational-op var
5163 //
5164 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005165 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005166 return true;
5167 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005168 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005169 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005170 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005171 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005172 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5173 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005174 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5175 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5176 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005177 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5178 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005179 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5180 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5181 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005182 } else if (BO->getOpcode() == BO_NE)
5183 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
5184 BO->getRHS() : BO->getLHS(),
5185 /*LessOp=*/llvm::None,
5186 /*StrictOp=*/true,
5187 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005188 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005189 if (CE->getNumArgs() == 2) {
5190 auto Op = CE->getOperator();
5191 switch (Op) {
5192 case OO_Greater:
5193 case OO_GreaterEqual:
5194 case OO_Less:
5195 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005196 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5197 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005198 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5199 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005200 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5201 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005202 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5203 CE->getOperatorLoc());
5204 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005205 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00005206 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
5207 CE->getArg(1) : CE->getArg(0),
5208 /*LessOp=*/llvm::None,
5209 /*StrictOp=*/true,
5210 CE->getSourceRange(),
5211 CE->getOperatorLoc());
5212 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005213 default:
5214 break;
5215 }
5216 }
5217 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005218 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005219 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005220 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005221 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005222 return true;
5223}
5224
Alexey Bataeve3727102018-04-18 15:57:46 +00005225bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005226 // RHS of canonical loop form increment can be:
5227 // var + incr
5228 // incr + var
5229 // var - incr
5230 //
5231 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005232 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005233 if (BO->isAdditiveOp()) {
5234 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005235 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5236 return setStep(BO->getRHS(), !IsAdd);
5237 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5238 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005239 }
David Majnemer9d168222016-08-05 17:44:54 +00005240 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005241 bool IsAdd = CE->getOperator() == OO_Plus;
5242 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005243 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5244 return setStep(CE->getArg(1), !IsAdd);
5245 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5246 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005247 }
5248 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005249 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005250 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005251 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005252 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005253 return true;
5254}
5255
Alexey Bataeve3727102018-04-18 15:57:46 +00005256bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005257 // Check incr-expr for canonical loop form and return true if it
5258 // does not conform.
5259 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5260 // ++var
5261 // var++
5262 // --var
5263 // var--
5264 // var += incr
5265 // var -= incr
5266 // var = var + incr
5267 // var = incr + var
5268 // var = var - incr
5269 //
5270 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005271 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005272 return true;
5273 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005274 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5275 if (!ExprTemp->cleanupsHaveSideEffects())
5276 S = ExprTemp->getSubExpr();
5277
Alexander Musmana5f070a2014-10-01 06:03:56 +00005278 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005279 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005280 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005281 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005282 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5283 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005284 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005285 (UO->isDecrementOp() ? -1 : 1))
5286 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005287 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005288 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005289 switch (BO->getOpcode()) {
5290 case BO_AddAssign:
5291 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005292 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5293 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005294 break;
5295 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005296 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5297 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005298 break;
5299 default:
5300 break;
5301 }
David Majnemer9d168222016-08-05 17:44:54 +00005302 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005303 switch (CE->getOperator()) {
5304 case OO_PlusPlus:
5305 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005306 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5307 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005308 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005309 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005310 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5311 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005312 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005313 break;
5314 case OO_PlusEqual:
5315 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005316 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5317 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005318 break;
5319 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005320 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5321 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005322 break;
5323 default:
5324 break;
5325 }
5326 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005327 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005328 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005329 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005330 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005331 return true;
5332}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005333
Alexey Bataev5a3af132016-03-29 08:58:54 +00005334static ExprResult
5335tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005336 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005337 if (SemaRef.CurContext->isDependentContext())
5338 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005339 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5340 return SemaRef.PerformImplicitConversion(
5341 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5342 /*AllowExplicit=*/true);
5343 auto I = Captures.find(Capture);
5344 if (I != Captures.end())
5345 return buildCapture(SemaRef, Capture, I->second);
5346 DeclRefExpr *Ref = nullptr;
5347 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5348 Captures[Capture] = Ref;
5349 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005350}
5351
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005352/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005353Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005354 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005355 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005356 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005357 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005358 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005359 SemaRef.getLangOpts().CPlusPlus) {
5360 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00005361 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
5362 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00005363 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
5364 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005365 if (!Upper || !Lower)
5366 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005367
5368 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5369
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005370 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005371 // BuildBinOp already emitted error, this one is to point user to upper
5372 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005373 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005374 << Upper->getSourceRange() << Lower->getSourceRange();
5375 return nullptr;
5376 }
5377 }
5378
5379 if (!Diff.isUsable())
5380 return nullptr;
5381
5382 // Upper - Lower [- 1]
5383 if (TestIsStrictOp)
5384 Diff = SemaRef.BuildBinOp(
5385 S, DefaultLoc, BO_Sub, Diff.get(),
5386 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5387 if (!Diff.isUsable())
5388 return nullptr;
5389
5390 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005391 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005392 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005393 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005394 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005395 if (!Diff.isUsable())
5396 return nullptr;
5397
5398 // Parentheses (for dumping/debugging purposes only).
5399 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5400 if (!Diff.isUsable())
5401 return nullptr;
5402
5403 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005404 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005405 if (!Diff.isUsable())
5406 return nullptr;
5407
Alexander Musman174b3ca2014-10-06 11:16:29 +00005408 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005409 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00005410 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005411 bool UseVarType = VarType->hasIntegerRepresentation() &&
5412 C.getTypeSize(Type) > C.getTypeSize(VarType);
5413 if (!Type->isIntegerType() || UseVarType) {
5414 unsigned NewSize =
5415 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
5416 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
5417 : Type->hasSignedIntegerRepresentation();
5418 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00005419 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
5420 Diff = SemaRef.PerformImplicitConversion(
5421 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
5422 if (!Diff.isUsable())
5423 return nullptr;
5424 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005425 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005426 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00005427 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
5428 if (NewSize != C.getTypeSize(Type)) {
5429 if (NewSize < C.getTypeSize(Type)) {
5430 assert(NewSize == 64 && "incorrect loop var size");
5431 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
5432 << InitSrcRange << ConditionSrcRange;
5433 }
5434 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005435 NewSize, Type->hasSignedIntegerRepresentation() ||
5436 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00005437 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
5438 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
5439 Sema::AA_Converting, true);
5440 if (!Diff.isUsable())
5441 return nullptr;
5442 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005443 }
5444 }
5445
Alexander Musmana5f070a2014-10-01 06:03:56 +00005446 return Diff.get();
5447}
5448
Alexey Bataeve3727102018-04-18 15:57:46 +00005449Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005450 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00005451 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005452 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
5453 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5454 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005455
Alexey Bataeve3727102018-04-18 15:57:46 +00005456 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
5457 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005458 if (!NewLB.isUsable() || !NewUB.isUsable())
5459 return nullptr;
5460
Alexey Bataeve3727102018-04-18 15:57:46 +00005461 ExprResult CondExpr =
5462 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005463 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005464 (TestIsStrictOp ? BO_LT : BO_LE) :
5465 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00005466 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005467 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005468 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
5469 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00005470 CondExpr = SemaRef.PerformImplicitConversion(
5471 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
5472 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005473 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00005474 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00005475 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005476 return CondExpr.isUsable() ? CondExpr.get() : Cond;
5477}
5478
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005479/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005480DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00005481 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5482 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005483 auto *VD = dyn_cast<VarDecl>(LCDecl);
5484 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005485 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
5486 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005487 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005488 const DSAStackTy::DSAVarData Data =
5489 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005490 // If the loop control decl is explicitly marked as private, do not mark it
5491 // as captured again.
5492 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
5493 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005494 return Ref;
5495 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00005496 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00005497}
5498
Alexey Bataeve3727102018-04-18 15:57:46 +00005499Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005500 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005501 QualType Type = LCDecl->getType().getNonReferenceType();
5502 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00005503 SemaRef, DefaultLoc, Type, LCDecl->getName(),
5504 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
5505 isa<VarDecl>(LCDecl)
5506 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
5507 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00005508 if (PrivateVar->isInvalidDecl())
5509 return nullptr;
5510 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
5511 }
5512 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005513}
5514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005515/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005516Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005517
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005518/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005519Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005520
Alexey Bataevf138fda2018-08-13 19:04:24 +00005521Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
5522 Scope *S, Expr *Counter,
5523 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
5524 Expr *Inc, OverloadedOperatorKind OOK) {
5525 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
5526 if (!Cnt)
5527 return nullptr;
5528 if (Inc) {
5529 assert((OOK == OO_Plus || OOK == OO_Minus) &&
5530 "Expected only + or - operations for depend clauses.");
5531 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
5532 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
5533 if (!Cnt)
5534 return nullptr;
5535 }
5536 ExprResult Diff;
5537 QualType VarType = LCDecl->getType().getNonReferenceType();
5538 if (VarType->isIntegerType() || VarType->isPointerType() ||
5539 SemaRef.getLangOpts().CPlusPlus) {
5540 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00005541 Expr *Upper = TestIsLessOp.getValue()
5542 ? Cnt
5543 : tryBuildCapture(SemaRef, UB, Captures).get();
5544 Expr *Lower = TestIsLessOp.getValue()
5545 ? tryBuildCapture(SemaRef, LB, Captures).get()
5546 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005547 if (!Upper || !Lower)
5548 return nullptr;
5549
5550 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5551
5552 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5553 // BuildBinOp already emitted error, this one is to point user to upper
5554 // and lower bound, and to tell what is passed to 'operator-'.
5555 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5556 << Upper->getSourceRange() << Lower->getSourceRange();
5557 return nullptr;
5558 }
5559 }
5560
5561 if (!Diff.isUsable())
5562 return nullptr;
5563
5564 // Parentheses (for dumping/debugging purposes only).
5565 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5566 if (!Diff.isUsable())
5567 return nullptr;
5568
5569 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5570 if (!NewStep.isUsable())
5571 return nullptr;
5572 // (Upper - Lower) / Step
5573 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5574 if (!Diff.isUsable())
5575 return nullptr;
5576
5577 return Diff.get();
5578}
5579
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005580/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005581struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005582 /// True if the condition operator is the strict compare operator (<, > or
5583 /// !=).
5584 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005585 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005586 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005587 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005588 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005589 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005590 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005591 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005592 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005593 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005594 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00005595 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005596 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005597 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005598 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005599 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005600 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005601 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005602 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005603 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005604 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005605 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005606 SourceRange IncSrcRange;
5607};
5608
Alexey Bataev23b69422014-06-18 07:08:49 +00005609} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005610
Alexey Bataev9c821032015-04-30 04:23:23 +00005611void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5612 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5613 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005614 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5615 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005616 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005617 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00005618 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005619 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5620 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005621 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00005622 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005623 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005624 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005625 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005626 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00005627 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5628 /*WithInit=*/false);
5629 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005630 }
5631 }
5632 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005633 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5634 if (LD != D->getCanonicalDecl()) {
5635 DSAStack->resetPossibleLoopCounter();
5636 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5637 MarkDeclarationsReferencedInExpr(
5638 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5639 Var->getType().getNonLValueExprType(Context),
5640 ForLoc, /*RefersToCapture=*/true));
5641 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00005642 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
5643 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
5644 // Referenced in a Construct, C/C++]. The loop iteration variable in the
5645 // associated for-loop of a simd construct with just one associated
5646 // for-loop may be listed in a linear clause with a constant-linear-step
5647 // that is the increment of the associated for-loop. The loop iteration
5648 // variable(s) in the associated for-loop(s) of a for or parallel for
5649 // construct may be listed in a private or lastprivate clause.
5650 DSAStackTy::DSAVarData DVar =
5651 DSAStack->getTopDSA(D, /*FromParent=*/false);
5652 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
5653 // is declared in the loop and it is predetermined as a private.
5654 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
5655 OpenMPClauseKind PredeterminedCKind =
5656 isOpenMPSimdDirective(DKind)
5657 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
5658 : OMPC_private;
5659 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5660 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
5661 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
5662 DVar.CKind != OMPC_private))) ||
5663 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5664 isOpenMPDistributeDirective(DKind)) &&
5665 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5666 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5667 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
5668 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
5669 << getOpenMPClauseName(DVar.CKind)
5670 << getOpenMPDirectiveName(DKind)
5671 << getOpenMPClauseName(PredeterminedCKind);
5672 if (DVar.RefExpr == nullptr)
5673 DVar.CKind = PredeterminedCKind;
5674 reportOriginalDsa(*this, DSAStack, D, DVar,
5675 /*IsLoopIterVar=*/true);
5676 } else if (LoopDeclRefExpr) {
5677 // Make the loop iteration variable private (for worksharing
5678 // constructs), linear (for simd directives with the only one
5679 // associated loop) or lastprivate (for simd directives with several
5680 // collapsed or ordered loops).
5681 if (DVar.CKind == OMPC_unknown)
5682 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
5683 PrivateRef);
5684 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005685 }
5686 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005687 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005688 }
5689}
5690
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005691/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005692/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005693static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005694 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5695 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005696 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5697 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005698 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005699 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005700 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005701 // OpenMP [2.6, Canonical Loop Form]
5702 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005703 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005704 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005705 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005706 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005707 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005708 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005709 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005710 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5711 SemaRef.Diag(DSA.getConstructLoc(),
5712 diag::note_omp_collapse_ordered_expr)
5713 << 2 << CollapseLoopCountExpr->getSourceRange()
5714 << OrderedLoopCountExpr->getSourceRange();
5715 else if (CollapseLoopCountExpr)
5716 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5717 diag::note_omp_collapse_ordered_expr)
5718 << 0 << CollapseLoopCountExpr->getSourceRange();
5719 else
5720 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5721 diag::note_omp_collapse_ordered_expr)
5722 << 1 << OrderedLoopCountExpr->getSourceRange();
5723 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005724 return true;
5725 }
5726 assert(For->getBody());
5727
Alexey Bataev622af1d2019-04-24 19:58:30 +00005728 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005729
5730 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005731 Stmt *Init = For->getInit();
5732 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005733 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005734
5735 bool HasErrors = false;
5736
5737 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005738 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005739 // OpenMP [2.6, Canonical Loop Form]
5740 // Var is one of the following:
5741 // A variable of signed or unsigned integer type.
5742 // For C++, a variable of a random access iterator type.
5743 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005744 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005745 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5746 !VarType->isPointerType() &&
5747 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005748 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005749 << SemaRef.getLangOpts().CPlusPlus;
5750 HasErrors = true;
5751 }
5752
5753 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5754 // a Construct
5755 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5756 // parallel for construct is (are) private.
5757 // The loop iteration variable in the associated for-loop of a simd
5758 // construct with just one associated for-loop is linear with a
5759 // constant-linear-step that is the increment of the associated for-loop.
5760 // Exclude loop var from the list of variables with implicitly defined data
5761 // sharing attributes.
5762 VarsWithImplicitDSA.erase(LCDecl);
5763
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005764 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5765
5766 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005767 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005768
5769 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005770 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005771 }
5772
Alexey Bataeve3727102018-04-18 15:57:46 +00005773 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005774 return HasErrors;
5775
Alexander Musmana5f070a2014-10-01 06:03:56 +00005776 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005777 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005778 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5779 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005780 DSA.getCurScope(),
5781 (isOpenMPWorksharingDirective(DKind) ||
5782 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5783 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005784 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5785 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5786 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5787 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5788 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5789 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5790 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5791 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005792 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005793
Alexey Bataev62dbb972015-04-22 11:59:37 +00005794 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5795 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005796 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005797 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005798 ResultIterSpace.CounterInit == nullptr ||
5799 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005800 if (!HasErrors && DSA.isOrderedRegion()) {
5801 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5802 if (CurrentNestedLoopCount <
5803 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5804 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5805 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5806 DSA.getOrderedRegionParam().second->setLoopCounter(
5807 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5808 }
5809 }
5810 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5811 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5812 // Erroneous case - clause has some problems.
5813 continue;
5814 }
5815 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5816 Pair.second.size() <= CurrentNestedLoopCount) {
5817 // Erroneous case - clause has some problems.
5818 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5819 continue;
5820 }
5821 Expr *CntValue;
5822 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5823 CntValue = ISC.buildOrderedLoopData(
5824 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5825 Pair.first->getDependencyLoc());
5826 else
5827 CntValue = ISC.buildOrderedLoopData(
5828 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5829 Pair.first->getDependencyLoc(),
5830 Pair.second[CurrentNestedLoopCount].first,
5831 Pair.second[CurrentNestedLoopCount].second);
5832 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5833 }
5834 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005835
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005836 return HasErrors;
5837}
5838
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005839/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005840static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005841buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005842 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005843 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005844 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005845 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005846 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005847 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005848 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005849 VarRef.get()->getType())) {
5850 NewStart = SemaRef.PerformImplicitConversion(
5851 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5852 /*AllowExplicit=*/true);
5853 if (!NewStart.isUsable())
5854 return ExprError();
5855 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005856
Alexey Bataeve3727102018-04-18 15:57:46 +00005857 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005858 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5859 return Init;
5860}
5861
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005862/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005863static ExprResult buildCounterUpdate(
5864 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5865 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5866 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005867 // Add parentheses (for debugging purposes only).
5868 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5869 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5870 !Step.isUsable())
5871 return ExprError();
5872
Alexey Bataev5a3af132016-03-29 08:58:54 +00005873 ExprResult NewStep = Step;
5874 if (Captures)
5875 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005876 if (NewStep.isInvalid())
5877 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005878 ExprResult Update =
5879 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005880 if (!Update.isUsable())
5881 return ExprError();
5882
Alexey Bataevc0214e02016-02-16 12:13:49 +00005883 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5884 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005885 ExprResult NewStart = Start;
5886 if (Captures)
5887 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005888 if (NewStart.isInvalid())
5889 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005890
Alexey Bataevc0214e02016-02-16 12:13:49 +00005891 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5892 ExprResult SavedUpdate = Update;
5893 ExprResult UpdateVal;
5894 if (VarRef.get()->getType()->isOverloadableType() ||
5895 NewStart.get()->getType()->isOverloadableType() ||
5896 Update.get()->getType()->isOverloadableType()) {
5897 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5898 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5899 Update =
5900 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5901 if (Update.isUsable()) {
5902 UpdateVal =
5903 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5904 VarRef.get(), SavedUpdate.get());
5905 if (UpdateVal.isUsable()) {
5906 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5907 UpdateVal.get());
5908 }
5909 }
5910 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5911 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005912
Alexey Bataevc0214e02016-02-16 12:13:49 +00005913 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5914 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5915 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5916 NewStart.get(), SavedUpdate.get());
5917 if (!Update.isUsable())
5918 return ExprError();
5919
Alexey Bataev11481f52016-02-17 10:29:05 +00005920 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5921 VarRef.get()->getType())) {
5922 Update = SemaRef.PerformImplicitConversion(
5923 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5924 if (!Update.isUsable())
5925 return ExprError();
5926 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005927
5928 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5929 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005930 return Update;
5931}
5932
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005933/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005934/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005935static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005936 if (E == nullptr)
5937 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005938 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005939 QualType OldType = E->getType();
5940 unsigned HasBits = C.getTypeSize(OldType);
5941 if (HasBits >= Bits)
5942 return ExprResult(E);
5943 // OK to convert to signed, because new type has more bits than old.
5944 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5945 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5946 true);
5947}
5948
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005949/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005950/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005951static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005952 if (E == nullptr)
5953 return false;
5954 llvm::APSInt Result;
5955 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5956 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5957 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005958}
5959
Alexey Bataev5a3af132016-03-29 08:58:54 +00005960/// Build preinits statement for the given declarations.
5961static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005962 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005963 if (!PreInits.empty()) {
5964 return new (Context) DeclStmt(
5965 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5966 SourceLocation(), SourceLocation());
5967 }
5968 return nullptr;
5969}
5970
5971/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005972static Stmt *
5973buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005974 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005975 if (!Captures.empty()) {
5976 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005977 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005978 PreInits.push_back(Pair.second->getDecl());
5979 return buildPreInits(Context, PreInits);
5980 }
5981 return nullptr;
5982}
5983
5984/// Build postupdate expression for the given list of postupdates expressions.
5985static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5986 Expr *PostUpdate = nullptr;
5987 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005988 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005989 Expr *ConvE = S.BuildCStyleCastExpr(
5990 E->getExprLoc(),
5991 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5992 E->getExprLoc(), E)
5993 .get();
5994 PostUpdate = PostUpdate
5995 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5996 PostUpdate, ConvE)
5997 .get()
5998 : ConvE;
5999 }
6000 }
6001 return PostUpdate;
6002}
6003
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006004/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00006005/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6006/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006007static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00006008checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00006009 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6010 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00006011 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00006012 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006013 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006014 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006015 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006016 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006017 if (!CollapseLoopCountExpr->isValueDependent() &&
6018 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006019 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006020 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006021 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006022 return 1;
6023 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00006024 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006025 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006026 if (OrderedLoopCountExpr) {
6027 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006028 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006029 if (!OrderedLoopCountExpr->isValueDependent() &&
6030 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6031 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006032 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006033 if (Result.getLimitedValue() < NestedLoopCount) {
6034 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6035 diag::err_omp_wrong_ordered_loop_count)
6036 << OrderedLoopCountExpr->getSourceRange();
6037 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6038 diag::note_collapse_loop_count)
6039 << CollapseLoopCountExpr->getSourceRange();
6040 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006041 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006042 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006043 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006044 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006045 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006046 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006047 // This is helper routine for loop directives (e.g., 'for', 'simd',
6048 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006049 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006050 SmallVector<LoopIterationSpace, 4> IterSpaces(
6051 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006052 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006053 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006054 if (checkOpenMPIterationSpace(
6055 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6056 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6057 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
6058 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006059 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006060 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006061 // OpenMP [2.8.1, simd construct, Restrictions]
6062 // All loops associated with the construct must be perfectly nested; that
6063 // is, there must be no intervening code nor any OpenMP directive between
6064 // any two loops.
6065 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006066 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006067 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6068 if (checkOpenMPIterationSpace(
6069 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6070 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
6071 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
6072 Captures))
6073 return 0;
6074 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6075 // Handle initialization of captured loop iterator variables.
6076 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6077 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6078 Captures[DRE] = DRE;
6079 }
6080 }
6081 // Move on to the next nested for loop, or to the loop body.
6082 // OpenMP [2.8.1, simd construct, Restrictions]
6083 // All loops associated with the construct must be perfectly nested; that
6084 // is, there must be no intervening code nor any OpenMP directive between
6085 // any two loops.
6086 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
6087 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006088
Alexander Musmana5f070a2014-10-01 06:03:56 +00006089 Built.clear(/* size */ NestedLoopCount);
6090
6091 if (SemaRef.CurContext->isDependentContext())
6092 return NestedLoopCount;
6093
6094 // An example of what is generated for the following code:
6095 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006096 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006097 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006098 // for (k = 0; k < NK; ++k)
6099 // for (j = J0; j < NJ; j+=2) {
6100 // <loop body>
6101 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006102 //
6103 // We generate the code below.
6104 // Note: the loop body may be outlined in CodeGen.
6105 // Note: some counters may be C++ classes, operator- is used to find number of
6106 // iterations and operator+= to calculate counter value.
6107 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
6108 // or i64 is currently supported).
6109 //
6110 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
6111 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
6112 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
6113 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
6114 // // similar updates for vars in clauses (e.g. 'linear')
6115 // <loop body (using local i and j)>
6116 // }
6117 // i = NI; // assign final values of counters
6118 // j = NJ;
6119 //
6120
6121 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
6122 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006123 // Precondition tests if there is at least one iteration (all conditions are
6124 // true).
6125 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00006126 Expr *N0 = IterSpaces[0].NumIterations;
6127 ExprResult LastIteration32 =
6128 widenIterationCount(/*Bits=*/32,
6129 SemaRef
6130 .PerformImplicitConversion(
6131 N0->IgnoreImpCasts(), N0->getType(),
6132 Sema::AA_Converting, /*AllowExplicit=*/true)
6133 .get(),
6134 SemaRef);
6135 ExprResult LastIteration64 = widenIterationCount(
6136 /*Bits=*/64,
6137 SemaRef
6138 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
6139 Sema::AA_Converting,
6140 /*AllowExplicit=*/true)
6141 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006142 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006143
6144 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
6145 return NestedLoopCount;
6146
Alexey Bataeve3727102018-04-18 15:57:46 +00006147 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006148 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
6149
6150 Scope *CurScope = DSA.getCurScope();
6151 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006152 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00006153 PreCond =
6154 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
6155 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00006156 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006157 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00006158 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006159 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
6160 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006161 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006162 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006163 SemaRef
6164 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6165 Sema::AA_Converting,
6166 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006167 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006168 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006169 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006170 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006171 SemaRef
6172 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6173 Sema::AA_Converting,
6174 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006175 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006176 }
6177
6178 // Choose either the 32-bit or 64-bit version.
6179 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006180 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
6181 (LastIteration32.isUsable() &&
6182 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
6183 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
6184 fitsInto(
6185 /*Bits=*/32,
6186 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
6187 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00006188 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00006189 QualType VType = LastIteration.get()->getType();
6190 QualType RealVType = VType;
6191 QualType StrideVType = VType;
6192 if (isOpenMPTaskLoopDirective(DKind)) {
6193 VType =
6194 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
6195 StrideVType =
6196 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6197 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006198
6199 if (!LastIteration.isUsable())
6200 return 0;
6201
6202 // Save the number of iterations.
6203 ExprResult NumIterations = LastIteration;
6204 {
6205 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006206 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
6207 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006208 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6209 if (!LastIteration.isUsable())
6210 return 0;
6211 }
6212
6213 // Calculate the last iteration number beforehand instead of doing this on
6214 // each iteration. Do not do this if the number of iterations may be kfold-ed.
6215 llvm::APSInt Result;
6216 bool IsConstant =
6217 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
6218 ExprResult CalcLastIteration;
6219 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006220 ExprResult SaveRef =
6221 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006222 LastIteration = SaveRef;
6223
6224 // Prepare SaveRef + 1.
6225 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006226 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00006227 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6228 if (!NumIterations.isUsable())
6229 return 0;
6230 }
6231
6232 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
6233
David Majnemer9d168222016-08-05 17:44:54 +00006234 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006235 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006236 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6237 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006238 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006239 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
6240 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006241 SemaRef.AddInitializerToDecl(LBDecl,
6242 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6243 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006244
6245 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006246 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
6247 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00006248 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00006249 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006250
6251 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
6252 // This will be used to implement clause 'lastprivate'.
6253 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006254 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
6255 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006256 SemaRef.AddInitializerToDecl(ILDecl,
6257 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6258 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006259
6260 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00006261 VarDecl *STDecl =
6262 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
6263 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006264 SemaRef.AddInitializerToDecl(STDecl,
6265 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
6266 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006267
6268 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00006269 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00006270 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
6271 UB.get(), LastIteration.get());
6272 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00006273 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
6274 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00006275 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
6276 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006277 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006278
6279 // If we have a combined directive that combines 'distribute', 'for' or
6280 // 'simd' we need to be able to access the bounds of the schedule of the
6281 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
6282 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
6283 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00006284 // Lower bound variable, initialized with zero.
6285 VarDecl *CombLBDecl =
6286 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
6287 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
6288 SemaRef.AddInitializerToDecl(
6289 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6290 /*DirectInit*/ false);
6291
6292 // Upper bound variable, initialized with last iteration number.
6293 VarDecl *CombUBDecl =
6294 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
6295 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
6296 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
6297 /*DirectInit*/ false);
6298
6299 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
6300 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
6301 ExprResult CombCondOp =
6302 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
6303 LastIteration.get(), CombUB.get());
6304 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
6305 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006306 CombEUB =
6307 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006308
Alexey Bataeve3727102018-04-18 15:57:46 +00006309 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006310 // We expect to have at least 2 more parameters than the 'parallel'
6311 // directive does - the lower and upper bounds of the previous schedule.
6312 assert(CD->getNumParams() >= 4 &&
6313 "Unexpected number of parameters in loop combined directive");
6314
6315 // Set the proper type for the bounds given what we learned from the
6316 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00006317 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
6318 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006319
6320 // Previous lower and upper bounds are obtained from the region
6321 // parameters.
6322 PrevLB =
6323 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
6324 PrevUB =
6325 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
6326 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006327 }
6328
6329 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006330 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006331 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006332 {
Alexey Bataev7292c292016-04-25 12:22:29 +00006333 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
6334 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00006335 Expr *RHS =
6336 (isOpenMPWorksharingDirective(DKind) ||
6337 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
6338 ? LB.get()
6339 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006340 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006341 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006342
6343 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6344 Expr *CombRHS =
6345 (isOpenMPWorksharingDirective(DKind) ||
6346 isOpenMPTaskLoopDirective(DKind) ||
6347 isOpenMPDistributeDirective(DKind))
6348 ? CombLB.get()
6349 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
6350 CombInit =
6351 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006352 CombInit =
6353 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006354 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006355 }
6356
Alexey Bataev316ccf62019-01-29 18:51:58 +00006357 bool UseStrictCompare =
6358 RealVType->hasUnsignedIntegerRepresentation() &&
6359 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
6360 return LIS.IsStrictCompare;
6361 });
6362 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
6363 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006364 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00006365 Expr *BoundUB = UB.get();
6366 if (UseStrictCompare) {
6367 BoundUB =
6368 SemaRef
6369 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
6370 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6371 .get();
6372 BoundUB =
6373 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
6374 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006375 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006376 (isOpenMPWorksharingDirective(DKind) ||
6377 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00006378 ? SemaRef.BuildBinOp(CurScope, CondLoc,
6379 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
6380 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00006381 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6382 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006383 ExprResult CombDistCond;
6384 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006385 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6386 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006387 }
6388
Carlo Bertolliffafe102017-04-20 00:39:39 +00006389 ExprResult CombCond;
6390 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006391 Expr *BoundCombUB = CombUB.get();
6392 if (UseStrictCompare) {
6393 BoundCombUB =
6394 SemaRef
6395 .BuildBinOp(
6396 CurScope, CondLoc, BO_Add, BoundCombUB,
6397 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6398 .get();
6399 BoundCombUB =
6400 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
6401 .get();
6402 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00006403 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006404 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6405 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006406 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006407 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006408 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006409 ExprResult Inc =
6410 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
6411 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
6412 if (!Inc.isUsable())
6413 return 0;
6414 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006415 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006416 if (!Inc.isUsable())
6417 return 0;
6418
6419 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
6420 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006421 // In combined construct, add combined version that use CombLB and CombUB
6422 // base variables for the update
6423 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006424 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6425 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006426 // LB + ST
6427 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
6428 if (!NextLB.isUsable())
6429 return 0;
6430 // LB = LB + ST
6431 NextLB =
6432 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006433 NextLB =
6434 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006435 if (!NextLB.isUsable())
6436 return 0;
6437 // UB + ST
6438 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
6439 if (!NextUB.isUsable())
6440 return 0;
6441 // UB = UB + ST
6442 NextUB =
6443 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006444 NextUB =
6445 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006446 if (!NextUB.isUsable())
6447 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006448 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6449 CombNextLB =
6450 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
6451 if (!NextLB.isUsable())
6452 return 0;
6453 // LB = LB + ST
6454 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
6455 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006456 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
6457 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006458 if (!CombNextLB.isUsable())
6459 return 0;
6460 // UB + ST
6461 CombNextUB =
6462 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
6463 if (!CombNextUB.isUsable())
6464 return 0;
6465 // UB = UB + ST
6466 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
6467 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006468 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
6469 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006470 if (!CombNextUB.isUsable())
6471 return 0;
6472 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006473 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006474
Carlo Bertolliffafe102017-04-20 00:39:39 +00006475 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00006476 // directive with for as IV = IV + ST; ensure upper bound expression based
6477 // on PrevUB instead of NumIterations - used to implement 'for' when found
6478 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006479 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006480 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00006481 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006482 DistCond = SemaRef.BuildBinOp(
6483 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006484 assert(DistCond.isUsable() && "distribute cond expr was not built");
6485
6486 DistInc =
6487 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
6488 assert(DistInc.isUsable() && "distribute inc expr was not built");
6489 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
6490 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006491 DistInc =
6492 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006493 assert(DistInc.isUsable() && "distribute inc expr was not built");
6494
6495 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
6496 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006497 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006498 ExprResult IsUBGreater =
6499 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
6500 ExprResult CondOp = SemaRef.ActOnConditionalOp(
6501 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
6502 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
6503 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006504 PrevEUB =
6505 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006506
Alexey Bataev316ccf62019-01-29 18:51:58 +00006507 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
6508 // parallel for is in combination with a distribute directive with
6509 // schedule(static, 1)
6510 Expr *BoundPrevUB = PrevUB.get();
6511 if (UseStrictCompare) {
6512 BoundPrevUB =
6513 SemaRef
6514 .BuildBinOp(
6515 CurScope, CondLoc, BO_Add, BoundPrevUB,
6516 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6517 .get();
6518 BoundPrevUB =
6519 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
6520 .get();
6521 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006522 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006523 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6524 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006525 }
6526
Alexander Musmana5f070a2014-10-01 06:03:56 +00006527 // Build updates and final values of the loop counters.
6528 bool HasErrors = false;
6529 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006530 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006531 Built.Updates.resize(NestedLoopCount);
6532 Built.Finals.resize(NestedLoopCount);
6533 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006534 // We implement the following algorithm for obtaining the
6535 // original loop iteration variable values based on the
6536 // value of the collapsed loop iteration variable IV.
6537 //
6538 // Let n+1 be the number of collapsed loops in the nest.
6539 // Iteration variables (I0, I1, .... In)
6540 // Iteration counts (N0, N1, ... Nn)
6541 //
6542 // Acc = IV;
6543 //
6544 // To compute Ik for loop k, 0 <= k <= n, generate:
6545 // Prod = N(k+1) * N(k+2) * ... * Nn;
6546 // Ik = Acc / Prod;
6547 // Acc -= Ik * Prod;
6548 //
6549 ExprResult Acc = IV;
6550 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006551 LoopIterationSpace &IS = IterSpaces[Cnt];
6552 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006553 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006554
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006555 // Compute prod
6556 ExprResult Prod =
6557 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6558 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
6559 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
6560 IterSpaces[K].NumIterations);
6561
6562 // Iter = Acc / Prod
6563 // If there is at least one more inner loop to avoid
6564 // multiplication by 1.
6565 if (Cnt + 1 < NestedLoopCount)
6566 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
6567 Acc.get(), Prod.get());
6568 else
6569 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006570 if (!Iter.isUsable()) {
6571 HasErrors = true;
6572 break;
6573 }
6574
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006575 // Update Acc:
6576 // Acc -= Iter * Prod
6577 // Check if there is at least one more inner loop to avoid
6578 // multiplication by 1.
6579 if (Cnt + 1 < NestedLoopCount)
6580 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
6581 Iter.get(), Prod.get());
6582 else
6583 Prod = Iter;
6584 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
6585 Acc.get(), Prod.get());
6586
Alexey Bataev39f915b82015-05-08 10:41:21 +00006587 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006588 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00006589 DeclRefExpr *CounterVar = buildDeclRefExpr(
6590 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
6591 /*RefersToCapture=*/true);
6592 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006593 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006594 if (!Init.isUsable()) {
6595 HasErrors = true;
6596 break;
6597 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006598 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006599 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6600 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006601 if (!Update.isUsable()) {
6602 HasErrors = true;
6603 break;
6604 }
6605
6606 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006607 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00006608 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006609 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006610 if (!Final.isUsable()) {
6611 HasErrors = true;
6612 break;
6613 }
6614
Alexander Musmana5f070a2014-10-01 06:03:56 +00006615 if (!Update.isUsable() || !Final.isUsable()) {
6616 HasErrors = true;
6617 break;
6618 }
6619 // Save results
6620 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006621 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006622 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006623 Built.Updates[Cnt] = Update.get();
6624 Built.Finals[Cnt] = Final.get();
6625 }
6626 }
6627
6628 if (HasErrors)
6629 return 0;
6630
6631 // Save results
6632 Built.IterationVarRef = IV.get();
6633 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006634 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006635 Built.CalcLastIteration = SemaRef
6636 .ActOnFinishFullExpr(CalcLastIteration.get(),
6637 /*DiscardedValue*/ false)
6638 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006639 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006640 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006641 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006642 Built.Init = Init.get();
6643 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006644 Built.LB = LB.get();
6645 Built.UB = UB.get();
6646 Built.IL = IL.get();
6647 Built.ST = ST.get();
6648 Built.EUB = EUB.get();
6649 Built.NLB = NextLB.get();
6650 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006651 Built.PrevLB = PrevLB.get();
6652 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006653 Built.DistInc = DistInc.get();
6654 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006655 Built.DistCombinedFields.LB = CombLB.get();
6656 Built.DistCombinedFields.UB = CombUB.get();
6657 Built.DistCombinedFields.EUB = CombEUB.get();
6658 Built.DistCombinedFields.Init = CombInit.get();
6659 Built.DistCombinedFields.Cond = CombCond.get();
6660 Built.DistCombinedFields.NLB = CombNextLB.get();
6661 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006662 Built.DistCombinedFields.DistCond = CombDistCond.get();
6663 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006664
Alexey Bataevabfc0692014-06-25 06:52:00 +00006665 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006666}
6667
Alexey Bataev10e775f2015-07-30 11:36:16 +00006668static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006669 auto CollapseClauses =
6670 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6671 if (CollapseClauses.begin() != CollapseClauses.end())
6672 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006673 return nullptr;
6674}
6675
Alexey Bataev10e775f2015-07-30 11:36:16 +00006676static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006677 auto OrderedClauses =
6678 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6679 if (OrderedClauses.begin() != OrderedClauses.end())
6680 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006681 return nullptr;
6682}
6683
Kelvin Lic5609492016-07-15 04:39:07 +00006684static bool checkSimdlenSafelenSpecified(Sema &S,
6685 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006686 const OMPSafelenClause *Safelen = nullptr;
6687 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006688
Alexey Bataeve3727102018-04-18 15:57:46 +00006689 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006690 if (Clause->getClauseKind() == OMPC_safelen)
6691 Safelen = cast<OMPSafelenClause>(Clause);
6692 else if (Clause->getClauseKind() == OMPC_simdlen)
6693 Simdlen = cast<OMPSimdlenClause>(Clause);
6694 if (Safelen && Simdlen)
6695 break;
6696 }
6697
6698 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006699 const Expr *SimdlenLength = Simdlen->getSimdlen();
6700 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006701 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6702 SimdlenLength->isInstantiationDependent() ||
6703 SimdlenLength->containsUnexpandedParameterPack())
6704 return false;
6705 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6706 SafelenLength->isInstantiationDependent() ||
6707 SafelenLength->containsUnexpandedParameterPack())
6708 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006709 Expr::EvalResult SimdlenResult, SafelenResult;
6710 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6711 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6712 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6713 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006714 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6715 // If both simdlen and safelen clauses are specified, the value of the
6716 // simdlen parameter must be less than or equal to the value of the safelen
6717 // parameter.
6718 if (SimdlenRes > SafelenRes) {
6719 S.Diag(SimdlenLength->getExprLoc(),
6720 diag::err_omp_wrong_simdlen_safelen_values)
6721 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6722 return true;
6723 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006724 }
6725 return false;
6726}
6727
Alexey Bataeve3727102018-04-18 15:57:46 +00006728StmtResult
6729Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6730 SourceLocation StartLoc, SourceLocation EndLoc,
6731 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006732 if (!AStmt)
6733 return StmtError();
6734
6735 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006736 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006737 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6738 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006739 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006740 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6741 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006742 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006743 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006744
Alexander Musmana5f070a2014-10-01 06:03:56 +00006745 assert((CurContext->isDependentContext() || B.builtAll()) &&
6746 "omp simd loop exprs were not built");
6747
Alexander Musman3276a272015-03-21 10:12:56 +00006748 if (!CurContext->isDependentContext()) {
6749 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006750 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006751 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006752 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006753 B.NumIterations, *this, CurScope,
6754 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006755 return StmtError();
6756 }
6757 }
6758
Kelvin Lic5609492016-07-15 04:39:07 +00006759 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006760 return StmtError();
6761
Reid Kleckner87a31802018-03-12 21:43:02 +00006762 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006763 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6764 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006765}
6766
Alexey Bataeve3727102018-04-18 15:57:46 +00006767StmtResult
6768Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6769 SourceLocation StartLoc, SourceLocation EndLoc,
6770 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006771 if (!AStmt)
6772 return StmtError();
6773
6774 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006775 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006776 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6777 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006778 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006779 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6780 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006781 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006782 return StmtError();
6783
Alexander Musmana5f070a2014-10-01 06:03:56 +00006784 assert((CurContext->isDependentContext() || B.builtAll()) &&
6785 "omp for loop exprs were not built");
6786
Alexey Bataev54acd402015-08-04 11:18:19 +00006787 if (!CurContext->isDependentContext()) {
6788 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006789 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006790 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006791 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006792 B.NumIterations, *this, CurScope,
6793 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006794 return StmtError();
6795 }
6796 }
6797
Reid Kleckner87a31802018-03-12 21:43:02 +00006798 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006799 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006800 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006801}
6802
Alexander Musmanf82886e2014-09-18 05:12:34 +00006803StmtResult Sema::ActOnOpenMPForSimdDirective(
6804 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006805 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006806 if (!AStmt)
6807 return StmtError();
6808
6809 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006810 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006811 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6812 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006813 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006814 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006815 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6816 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006817 if (NestedLoopCount == 0)
6818 return StmtError();
6819
Alexander Musmanc6388682014-12-15 07:07:06 +00006820 assert((CurContext->isDependentContext() || B.builtAll()) &&
6821 "omp for simd loop exprs were not built");
6822
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006823 if (!CurContext->isDependentContext()) {
6824 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006825 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006826 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006827 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006828 B.NumIterations, *this, CurScope,
6829 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006830 return StmtError();
6831 }
6832 }
6833
Kelvin Lic5609492016-07-15 04:39:07 +00006834 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006835 return StmtError();
6836
Reid Kleckner87a31802018-03-12 21:43:02 +00006837 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006838 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6839 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006840}
6841
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006842StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6843 Stmt *AStmt,
6844 SourceLocation StartLoc,
6845 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006846 if (!AStmt)
6847 return StmtError();
6848
6849 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006850 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006851 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006852 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006853 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006854 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006855 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006856 return StmtError();
6857 // All associated statements must be '#pragma omp section' except for
6858 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006859 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006860 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6861 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006862 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006863 diag::err_omp_sections_substmt_not_section);
6864 return StmtError();
6865 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006866 cast<OMPSectionDirective>(SectionStmt)
6867 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006868 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006869 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006870 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006871 return StmtError();
6872 }
6873
Reid Kleckner87a31802018-03-12 21:43:02 +00006874 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006875
Alexey Bataev25e5b442015-09-15 12:52:43 +00006876 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6877 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006878}
6879
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006880StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6881 SourceLocation StartLoc,
6882 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006883 if (!AStmt)
6884 return StmtError();
6885
6886 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006887
Reid Kleckner87a31802018-03-12 21:43:02 +00006888 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006889 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006890
Alexey Bataev25e5b442015-09-15 12:52:43 +00006891 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6892 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006893}
6894
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006895StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6896 Stmt *AStmt,
6897 SourceLocation StartLoc,
6898 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006899 if (!AStmt)
6900 return StmtError();
6901
6902 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006903
Reid Kleckner87a31802018-03-12 21:43:02 +00006904 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006905
Alexey Bataev3255bf32015-01-19 05:20:46 +00006906 // OpenMP [2.7.3, single Construct, Restrictions]
6907 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006908 const OMPClause *Nowait = nullptr;
6909 const OMPClause *Copyprivate = nullptr;
6910 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006911 if (Clause->getClauseKind() == OMPC_nowait)
6912 Nowait = Clause;
6913 else if (Clause->getClauseKind() == OMPC_copyprivate)
6914 Copyprivate = Clause;
6915 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006916 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006917 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006918 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006919 return StmtError();
6920 }
6921 }
6922
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006923 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6924}
6925
Alexander Musman80c22892014-07-17 08:54:58 +00006926StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6927 SourceLocation StartLoc,
6928 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006929 if (!AStmt)
6930 return StmtError();
6931
6932 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006933
Reid Kleckner87a31802018-03-12 21:43:02 +00006934 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006935
6936 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6937}
6938
Alexey Bataev28c75412015-12-15 08:19:24 +00006939StmtResult Sema::ActOnOpenMPCriticalDirective(
6940 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6941 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006942 if (!AStmt)
6943 return StmtError();
6944
6945 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006946
Alexey Bataev28c75412015-12-15 08:19:24 +00006947 bool ErrorFound = false;
6948 llvm::APSInt Hint;
6949 SourceLocation HintLoc;
6950 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006951 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006952 if (C->getClauseKind() == OMPC_hint) {
6953 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006954 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006955 ErrorFound = true;
6956 }
6957 Expr *E = cast<OMPHintClause>(C)->getHint();
6958 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006959 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006960 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006961 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006962 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006963 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006964 }
6965 }
6966 }
6967 if (ErrorFound)
6968 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006969 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006970 if (Pair.first && DirName.getName() && !DependentHint) {
6971 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6972 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006973 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006974 Diag(HintLoc, diag::note_omp_critical_hint_here)
6975 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006976 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006977 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006978 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006979 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006980 << 1
6981 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6982 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006983 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006984 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006985 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006986 }
6987 }
6988
Reid Kleckner87a31802018-03-12 21:43:02 +00006989 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006990
Alexey Bataev28c75412015-12-15 08:19:24 +00006991 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6992 Clauses, AStmt);
6993 if (!Pair.first && DirName.getName() && !DependentHint)
6994 DSAStack->addCriticalWithHint(Dir, Hint);
6995 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006996}
6997
Alexey Bataev4acb8592014-07-07 13:01:15 +00006998StmtResult Sema::ActOnOpenMPParallelForDirective(
6999 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007000 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007001 if (!AStmt)
7002 return StmtError();
7003
Alexey Bataeve3727102018-04-18 15:57:46 +00007004 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007005 // 1.2.2 OpenMP Language Terminology
7006 // Structured block - An executable statement with a single entry at the
7007 // top and a single exit at the bottom.
7008 // The point of exit cannot be a branch out of the structured block.
7009 // longjmp() and throw() must not violate the entry/exit criteria.
7010 CS->getCapturedDecl()->setNothrow();
7011
Alexander Musmanc6388682014-12-15 07:07:06 +00007012 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007013 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7014 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007015 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007016 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007017 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7018 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007019 if (NestedLoopCount == 0)
7020 return StmtError();
7021
Alexander Musmana5f070a2014-10-01 06:03:56 +00007022 assert((CurContext->isDependentContext() || B.builtAll()) &&
7023 "omp parallel for loop exprs were not built");
7024
Alexey Bataev54acd402015-08-04 11:18:19 +00007025 if (!CurContext->isDependentContext()) {
7026 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007027 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007028 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007029 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007030 B.NumIterations, *this, CurScope,
7031 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007032 return StmtError();
7033 }
7034 }
7035
Reid Kleckner87a31802018-03-12 21:43:02 +00007036 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007037 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007038 NestedLoopCount, Clauses, AStmt, B,
7039 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00007040}
7041
Alexander Musmane4e893b2014-09-23 09:33:00 +00007042StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
7043 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007044 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007045 if (!AStmt)
7046 return StmtError();
7047
Alexey Bataeve3727102018-04-18 15:57:46 +00007048 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007049 // 1.2.2 OpenMP Language Terminology
7050 // Structured block - An executable statement with a single entry at the
7051 // top and a single exit at the bottom.
7052 // The point of exit cannot be a branch out of the structured block.
7053 // longjmp() and throw() must not violate the entry/exit criteria.
7054 CS->getCapturedDecl()->setNothrow();
7055
Alexander Musmanc6388682014-12-15 07:07:06 +00007056 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007057 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7058 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007059 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007060 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007061 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7062 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007063 if (NestedLoopCount == 0)
7064 return StmtError();
7065
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007066 if (!CurContext->isDependentContext()) {
7067 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007068 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007069 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007070 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007071 B.NumIterations, *this, CurScope,
7072 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007073 return StmtError();
7074 }
7075 }
7076
Kelvin Lic5609492016-07-15 04:39:07 +00007077 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007078 return StmtError();
7079
Reid Kleckner87a31802018-03-12 21:43:02 +00007080 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007081 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007082 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007083}
7084
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007085StmtResult
7086Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7087 Stmt *AStmt, SourceLocation StartLoc,
7088 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007089 if (!AStmt)
7090 return StmtError();
7091
7092 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007093 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007094 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007095 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007096 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007097 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007098 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007099 return StmtError();
7100 // All associated statements must be '#pragma omp section' except for
7101 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007102 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007103 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7104 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007105 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007106 diag::err_omp_parallel_sections_substmt_not_section);
7107 return StmtError();
7108 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007109 cast<OMPSectionDirective>(SectionStmt)
7110 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007111 }
7112 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007113 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007114 diag::err_omp_parallel_sections_not_compound_stmt);
7115 return StmtError();
7116 }
7117
Reid Kleckner87a31802018-03-12 21:43:02 +00007118 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007119
Alexey Bataev25e5b442015-09-15 12:52:43 +00007120 return OMPParallelSectionsDirective::Create(
7121 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007122}
7123
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007124StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7125 Stmt *AStmt, SourceLocation StartLoc,
7126 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007127 if (!AStmt)
7128 return StmtError();
7129
David Majnemer9d168222016-08-05 17:44:54 +00007130 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007131 // 1.2.2 OpenMP Language Terminology
7132 // Structured block - An executable statement with a single entry at the
7133 // top and a single exit at the bottom.
7134 // The point of exit cannot be a branch out of the structured block.
7135 // longjmp() and throw() must not violate the entry/exit criteria.
7136 CS->getCapturedDecl()->setNothrow();
7137
Reid Kleckner87a31802018-03-12 21:43:02 +00007138 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007139
Alexey Bataev25e5b442015-09-15 12:52:43 +00007140 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7141 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007142}
7143
Alexey Bataev68446b72014-07-18 07:47:19 +00007144StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7145 SourceLocation EndLoc) {
7146 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
7147}
7148
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00007149StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7150 SourceLocation EndLoc) {
7151 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
7152}
7153
Alexey Bataev2df347a2014-07-18 10:17:07 +00007154StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7155 SourceLocation EndLoc) {
7156 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
7157}
7158
Alexey Bataev169d96a2017-07-18 20:17:46 +00007159StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
7160 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007161 SourceLocation StartLoc,
7162 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007163 if (!AStmt)
7164 return StmtError();
7165
7166 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007167
Reid Kleckner87a31802018-03-12 21:43:02 +00007168 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007169
Alexey Bataev169d96a2017-07-18 20:17:46 +00007170 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00007171 AStmt,
7172 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007173}
7174
Alexey Bataev6125da92014-07-21 11:26:11 +00007175StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7176 SourceLocation StartLoc,
7177 SourceLocation EndLoc) {
7178 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
7179 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
7180}
7181
Alexey Bataev346265e2015-09-25 10:37:12 +00007182StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7183 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007184 SourceLocation StartLoc,
7185 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007186 const OMPClause *DependFound = nullptr;
7187 const OMPClause *DependSourceClause = nullptr;
7188 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00007189 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007190 const OMPThreadsClause *TC = nullptr;
7191 const OMPSIMDClause *SC = nullptr;
7192 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00007193 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
7194 DependFound = C;
7195 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
7196 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007197 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00007198 << getOpenMPDirectiveName(OMPD_ordered)
7199 << getOpenMPClauseName(OMPC_depend) << 2;
7200 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007201 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00007202 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00007203 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007204 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007205 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007206 << 0;
7207 ErrorFound = true;
7208 }
7209 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
7210 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007211 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00007212 << 1;
7213 ErrorFound = true;
7214 }
7215 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00007216 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007217 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00007218 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007219 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007220 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00007221 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007222 }
Alexey Bataeveb482352015-12-18 05:05:56 +00007223 if (!ErrorFound && !SC &&
7224 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007225 // OpenMP [2.8.1,simd Construct, Restrictions]
7226 // An ordered construct with the simd clause is the only OpenMP construct
7227 // that can appear in the simd region.
7228 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00007229 ErrorFound = true;
7230 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007231 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00007232 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
7233 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007234 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007235 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00007236 diag::err_omp_ordered_directive_without_param);
7237 ErrorFound = true;
7238 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007239 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007240 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00007241 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
7242 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007243 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00007244 ErrorFound = true;
7245 }
7246 }
7247 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007248 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00007249
7250 if (AStmt) {
7251 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7252
Reid Kleckner87a31802018-03-12 21:43:02 +00007253 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007254 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007255
7256 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007257}
7258
Alexey Bataev1d160b12015-03-13 12:27:31 +00007259namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007260/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007261/// construct.
7262class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007263 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007264 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007265 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007266 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007267 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007268 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007269 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007270 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007271 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007272 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007273 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007274 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007275 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007276 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007277 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00007278 /// expression.
7279 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007280 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00007281 /// part.
7282 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007283 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007284 NoError
7285 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007286 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007287 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007288 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00007289 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007290 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007291 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007292 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007293 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007294 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00007295 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7296 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7297 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007298 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00007299 /// important for non-associative operations.
7300 bool IsXLHSInRHSPart;
7301 BinaryOperatorKind Op;
7302 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007303 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007304 /// if it is a prefix unary operation.
7305 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007306
7307public:
7308 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00007309 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00007310 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007311 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007312 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00007313 /// expression. If DiagId and NoteId == 0, then only check is performed
7314 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007315 /// \param DiagId Diagnostic which should be emitted if error is found.
7316 /// \param NoteId Diagnostic note for the main error message.
7317 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00007318 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007319 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007320 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007321 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007322 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007323 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00007324 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7325 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7326 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007327 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00007328 /// false otherwise.
7329 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
7330
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007331 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007332 /// if it is a prefix unary operation.
7333 bool isPostfixUpdate() const { return IsPostfixUpdate; }
7334
Alexey Bataev1d160b12015-03-13 12:27:31 +00007335private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00007336 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
7337 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00007338};
7339} // namespace
7340
7341bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
7342 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
7343 ExprAnalysisErrorCode ErrorFound = NoError;
7344 SourceLocation ErrorLoc, NoteLoc;
7345 SourceRange ErrorRange, NoteRange;
7346 // Allowed constructs are:
7347 // x = x binop expr;
7348 // x = expr binop x;
7349 if (AtomicBinOp->getOpcode() == BO_Assign) {
7350 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00007351 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007352 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
7353 if (AtomicInnerBinOp->isMultiplicativeOp() ||
7354 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
7355 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007356 Op = AtomicInnerBinOp->getOpcode();
7357 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00007358 Expr *LHS = AtomicInnerBinOp->getLHS();
7359 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007360 llvm::FoldingSetNodeID XId, LHSId, RHSId;
7361 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
7362 /*Canonical=*/true);
7363 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
7364 /*Canonical=*/true);
7365 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
7366 /*Canonical=*/true);
7367 if (XId == LHSId) {
7368 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007369 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007370 } else if (XId == RHSId) {
7371 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007372 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007373 } else {
7374 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7375 ErrorRange = AtomicInnerBinOp->getSourceRange();
7376 NoteLoc = X->getExprLoc();
7377 NoteRange = X->getSourceRange();
7378 ErrorFound = NotAnUpdateExpression;
7379 }
7380 } else {
7381 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7382 ErrorRange = AtomicInnerBinOp->getSourceRange();
7383 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
7384 NoteRange = SourceRange(NoteLoc, NoteLoc);
7385 ErrorFound = NotABinaryOperator;
7386 }
7387 } else {
7388 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
7389 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
7390 ErrorFound = NotABinaryExpression;
7391 }
7392 } else {
7393 ErrorLoc = AtomicBinOp->getExprLoc();
7394 ErrorRange = AtomicBinOp->getSourceRange();
7395 NoteLoc = AtomicBinOp->getOperatorLoc();
7396 NoteRange = SourceRange(NoteLoc, NoteLoc);
7397 ErrorFound = NotAnAssignmentOp;
7398 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007399 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007400 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7401 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7402 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007403 }
7404 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007405 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007406 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007407}
7408
7409bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
7410 unsigned NoteId) {
7411 ExprAnalysisErrorCode ErrorFound = NoError;
7412 SourceLocation ErrorLoc, NoteLoc;
7413 SourceRange ErrorRange, NoteRange;
7414 // Allowed constructs are:
7415 // x++;
7416 // x--;
7417 // ++x;
7418 // --x;
7419 // x binop= expr;
7420 // x = x binop expr;
7421 // x = expr binop x;
7422 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
7423 AtomicBody = AtomicBody->IgnoreParenImpCasts();
7424 if (AtomicBody->getType()->isScalarType() ||
7425 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007426 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007427 AtomicBody->IgnoreParenImpCasts())) {
7428 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00007429 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007430 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00007431 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007432 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007433 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007434 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007435 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
7436 AtomicBody->IgnoreParenImpCasts())) {
7437 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00007438 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00007439 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007440 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00007441 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007442 // Check for Unary Operation
7443 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007444 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007445 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
7446 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007447 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007448 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
7449 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007450 } else {
7451 ErrorFound = NotAnUnaryIncDecExpression;
7452 ErrorLoc = AtomicUnaryOp->getExprLoc();
7453 ErrorRange = AtomicUnaryOp->getSourceRange();
7454 NoteLoc = AtomicUnaryOp->getOperatorLoc();
7455 NoteRange = SourceRange(NoteLoc, NoteLoc);
7456 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007457 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007458 ErrorFound = NotABinaryOrUnaryExpression;
7459 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
7460 NoteRange = ErrorRange = AtomicBody->getSourceRange();
7461 }
7462 } else {
7463 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007464 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007465 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7466 }
7467 } else {
7468 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007469 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007470 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7471 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007472 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007473 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7474 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7475 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007476 }
7477 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007478 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007479 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007480 // Build an update expression of form 'OpaqueValueExpr(x) binop
7481 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
7482 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
7483 auto *OVEX = new (SemaRef.getASTContext())
7484 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
7485 auto *OVEExpr = new (SemaRef.getASTContext())
7486 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00007487 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00007488 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
7489 IsXLHSInRHSPart ? OVEExpr : OVEX);
7490 if (Update.isInvalid())
7491 return true;
7492 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
7493 Sema::AA_Casting);
7494 if (Update.isInvalid())
7495 return true;
7496 UpdateExpr = Update.get();
7497 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00007498 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007499}
7500
Alexey Bataev0162e452014-07-22 10:10:35 +00007501StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7502 Stmt *AStmt,
7503 SourceLocation StartLoc,
7504 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007505 if (!AStmt)
7506 return StmtError();
7507
David Majnemer9d168222016-08-05 17:44:54 +00007508 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00007509 // 1.2.2 OpenMP Language Terminology
7510 // Structured block - An executable statement with a single entry at the
7511 // top and a single exit at the bottom.
7512 // The point of exit cannot be a branch out of the structured block.
7513 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00007514 OpenMPClauseKind AtomicKind = OMPC_unknown;
7515 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00007516 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00007517 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00007518 C->getClauseKind() == OMPC_update ||
7519 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00007520 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007521 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007522 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00007523 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
7524 << getOpenMPClauseName(AtomicKind);
7525 } else {
7526 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007527 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007528 }
7529 }
7530 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007531
Alexey Bataeve3727102018-04-18 15:57:46 +00007532 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00007533 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
7534 Body = EWC->getSubExpr();
7535
Alexey Bataev62cec442014-11-18 10:14:22 +00007536 Expr *X = nullptr;
7537 Expr *V = nullptr;
7538 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007539 Expr *UE = nullptr;
7540 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007541 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00007542 // OpenMP [2.12.6, atomic Construct]
7543 // In the next expressions:
7544 // * x and v (as applicable) are both l-value expressions with scalar type.
7545 // * During the execution of an atomic region, multiple syntactic
7546 // occurrences of x must designate the same storage location.
7547 // * Neither of v and expr (as applicable) may access the storage location
7548 // designated by x.
7549 // * Neither of x and expr (as applicable) may access the storage location
7550 // designated by v.
7551 // * expr is an expression with scalar type.
7552 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
7553 // * binop, binop=, ++, and -- are not overloaded operators.
7554 // * The expression x binop expr must be numerically equivalent to x binop
7555 // (expr). This requirement is satisfied if the operators in expr have
7556 // precedence greater than binop, or by using parentheses around expr or
7557 // subexpressions of expr.
7558 // * The expression expr binop x must be numerically equivalent to (expr)
7559 // binop x. This requirement is satisfied if the operators in expr have
7560 // precedence equal to or greater than binop, or by using parentheses around
7561 // expr or subexpressions of expr.
7562 // * For forms that allow multiple occurrences of x, the number of times
7563 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00007564 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007565 enum {
7566 NotAnExpression,
7567 NotAnAssignmentOp,
7568 NotAScalarType,
7569 NotAnLValue,
7570 NoError
7571 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00007572 SourceLocation ErrorLoc, NoteLoc;
7573 SourceRange ErrorRange, NoteRange;
7574 // If clause is read:
7575 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007576 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7577 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00007578 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7579 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7580 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7581 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
7582 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7583 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
7584 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007585 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00007586 ErrorFound = NotAnLValue;
7587 ErrorLoc = AtomicBinOp->getExprLoc();
7588 ErrorRange = AtomicBinOp->getSourceRange();
7589 NoteLoc = NotLValueExpr->getExprLoc();
7590 NoteRange = NotLValueExpr->getSourceRange();
7591 }
7592 } else if (!X->isInstantiationDependent() ||
7593 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007594 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00007595 (X->isInstantiationDependent() || X->getType()->isScalarType())
7596 ? V
7597 : X;
7598 ErrorFound = NotAScalarType;
7599 ErrorLoc = AtomicBinOp->getExprLoc();
7600 ErrorRange = AtomicBinOp->getSourceRange();
7601 NoteLoc = NotScalarExpr->getExprLoc();
7602 NoteRange = NotScalarExpr->getSourceRange();
7603 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007604 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00007605 ErrorFound = NotAnAssignmentOp;
7606 ErrorLoc = AtomicBody->getExprLoc();
7607 ErrorRange = AtomicBody->getSourceRange();
7608 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7609 : AtomicBody->getExprLoc();
7610 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7611 : AtomicBody->getSourceRange();
7612 }
7613 } else {
7614 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007615 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007616 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007617 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007618 if (ErrorFound != NoError) {
7619 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7620 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007621 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7622 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007623 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007624 }
7625 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007626 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007627 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007628 enum {
7629 NotAnExpression,
7630 NotAnAssignmentOp,
7631 NotAScalarType,
7632 NotAnLValue,
7633 NoError
7634 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007635 SourceLocation ErrorLoc, NoteLoc;
7636 SourceRange ErrorRange, NoteRange;
7637 // If clause is write:
7638 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007639 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7640 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007641 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7642 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007643 X = AtomicBinOp->getLHS();
7644 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007645 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7646 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7647 if (!X->isLValue()) {
7648 ErrorFound = NotAnLValue;
7649 ErrorLoc = AtomicBinOp->getExprLoc();
7650 ErrorRange = AtomicBinOp->getSourceRange();
7651 NoteLoc = X->getExprLoc();
7652 NoteRange = X->getSourceRange();
7653 }
7654 } else if (!X->isInstantiationDependent() ||
7655 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007656 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007657 (X->isInstantiationDependent() || X->getType()->isScalarType())
7658 ? E
7659 : X;
7660 ErrorFound = NotAScalarType;
7661 ErrorLoc = AtomicBinOp->getExprLoc();
7662 ErrorRange = AtomicBinOp->getSourceRange();
7663 NoteLoc = NotScalarExpr->getExprLoc();
7664 NoteRange = NotScalarExpr->getSourceRange();
7665 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007666 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007667 ErrorFound = NotAnAssignmentOp;
7668 ErrorLoc = AtomicBody->getExprLoc();
7669 ErrorRange = AtomicBody->getSourceRange();
7670 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7671 : AtomicBody->getExprLoc();
7672 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7673 : AtomicBody->getSourceRange();
7674 }
7675 } else {
7676 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007677 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007678 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007679 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007680 if (ErrorFound != NoError) {
7681 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7682 << ErrorRange;
7683 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7684 << NoteRange;
7685 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007686 }
7687 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007688 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007689 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007690 // If clause is update:
7691 // x++;
7692 // x--;
7693 // ++x;
7694 // --x;
7695 // x binop= expr;
7696 // x = x binop expr;
7697 // x = expr binop x;
7698 OpenMPAtomicUpdateChecker Checker(*this);
7699 if (Checker.checkStatement(
7700 Body, (AtomicKind == OMPC_update)
7701 ? diag::err_omp_atomic_update_not_expression_statement
7702 : diag::err_omp_atomic_not_expression_statement,
7703 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007704 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007705 if (!CurContext->isDependentContext()) {
7706 E = Checker.getExpr();
7707 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007708 UE = Checker.getUpdateExpr();
7709 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007710 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007711 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007712 enum {
7713 NotAnAssignmentOp,
7714 NotACompoundStatement,
7715 NotTwoSubstatements,
7716 NotASpecificExpression,
7717 NoError
7718 } ErrorFound = NoError;
7719 SourceLocation ErrorLoc, NoteLoc;
7720 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007721 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007722 // If clause is a capture:
7723 // v = x++;
7724 // v = x--;
7725 // v = ++x;
7726 // v = --x;
7727 // v = x binop= expr;
7728 // v = x = x binop expr;
7729 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007730 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007731 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7732 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7733 V = AtomicBinOp->getLHS();
7734 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7735 OpenMPAtomicUpdateChecker Checker(*this);
7736 if (Checker.checkStatement(
7737 Body, diag::err_omp_atomic_capture_not_expression_statement,
7738 diag::note_omp_atomic_update))
7739 return StmtError();
7740 E = Checker.getExpr();
7741 X = Checker.getX();
7742 UE = Checker.getUpdateExpr();
7743 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7744 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007745 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007746 ErrorLoc = AtomicBody->getExprLoc();
7747 ErrorRange = AtomicBody->getSourceRange();
7748 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7749 : AtomicBody->getExprLoc();
7750 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7751 : AtomicBody->getSourceRange();
7752 ErrorFound = NotAnAssignmentOp;
7753 }
7754 if (ErrorFound != NoError) {
7755 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7756 << ErrorRange;
7757 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7758 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007759 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007760 if (CurContext->isDependentContext())
7761 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007762 } else {
7763 // If clause is a capture:
7764 // { v = x; x = expr; }
7765 // { v = x; x++; }
7766 // { v = x; x--; }
7767 // { v = x; ++x; }
7768 // { v = x; --x; }
7769 // { v = x; x binop= expr; }
7770 // { v = x; x = x binop expr; }
7771 // { v = x; x = expr binop x; }
7772 // { x++; v = x; }
7773 // { x--; v = x; }
7774 // { ++x; v = x; }
7775 // { --x; v = x; }
7776 // { x binop= expr; v = x; }
7777 // { x = x binop expr; v = x; }
7778 // { x = expr binop x; v = x; }
7779 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7780 // Check that this is { expr1; expr2; }
7781 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007782 Stmt *First = CS->body_front();
7783 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007784 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7785 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7786 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7787 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7788 // Need to find what subexpression is 'v' and what is 'x'.
7789 OpenMPAtomicUpdateChecker Checker(*this);
7790 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7791 BinaryOperator *BinOp = nullptr;
7792 if (IsUpdateExprFound) {
7793 BinOp = dyn_cast<BinaryOperator>(First);
7794 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7795 }
7796 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7797 // { v = x; x++; }
7798 // { v = x; x--; }
7799 // { v = x; ++x; }
7800 // { v = x; --x; }
7801 // { v = x; x binop= expr; }
7802 // { v = x; x = x binop expr; }
7803 // { v = x; x = expr binop x; }
7804 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007805 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007806 llvm::FoldingSetNodeID XId, PossibleXId;
7807 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7808 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7809 IsUpdateExprFound = XId == PossibleXId;
7810 if (IsUpdateExprFound) {
7811 V = BinOp->getLHS();
7812 X = Checker.getX();
7813 E = Checker.getExpr();
7814 UE = Checker.getUpdateExpr();
7815 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007816 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007817 }
7818 }
7819 if (!IsUpdateExprFound) {
7820 IsUpdateExprFound = !Checker.checkStatement(First);
7821 BinOp = nullptr;
7822 if (IsUpdateExprFound) {
7823 BinOp = dyn_cast<BinaryOperator>(Second);
7824 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7825 }
7826 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7827 // { x++; v = x; }
7828 // { x--; v = x; }
7829 // { ++x; v = x; }
7830 // { --x; v = x; }
7831 // { x binop= expr; v = x; }
7832 // { x = x binop expr; v = x; }
7833 // { x = expr binop x; v = x; }
7834 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007835 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007836 llvm::FoldingSetNodeID XId, PossibleXId;
7837 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7838 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7839 IsUpdateExprFound = XId == PossibleXId;
7840 if (IsUpdateExprFound) {
7841 V = BinOp->getLHS();
7842 X = Checker.getX();
7843 E = Checker.getExpr();
7844 UE = Checker.getUpdateExpr();
7845 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007846 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007847 }
7848 }
7849 }
7850 if (!IsUpdateExprFound) {
7851 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007852 auto *FirstExpr = dyn_cast<Expr>(First);
7853 auto *SecondExpr = dyn_cast<Expr>(Second);
7854 if (!FirstExpr || !SecondExpr ||
7855 !(FirstExpr->isInstantiationDependent() ||
7856 SecondExpr->isInstantiationDependent())) {
7857 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7858 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007859 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007860 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007861 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007862 NoteRange = ErrorRange = FirstBinOp
7863 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007864 : SourceRange(ErrorLoc, ErrorLoc);
7865 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007866 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7867 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7868 ErrorFound = NotAnAssignmentOp;
7869 NoteLoc = ErrorLoc = SecondBinOp
7870 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007871 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007872 NoteRange = ErrorRange =
7873 SecondBinOp ? SecondBinOp->getSourceRange()
7874 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007875 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007876 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007877 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007878 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007879 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7880 llvm::FoldingSetNodeID X1Id, X2Id;
7881 PossibleXRHSInFirst->Profile(X1Id, Context,
7882 /*Canonical=*/true);
7883 PossibleXLHSInSecond->Profile(X2Id, Context,
7884 /*Canonical=*/true);
7885 IsUpdateExprFound = X1Id == X2Id;
7886 if (IsUpdateExprFound) {
7887 V = FirstBinOp->getLHS();
7888 X = SecondBinOp->getLHS();
7889 E = SecondBinOp->getRHS();
7890 UE = nullptr;
7891 IsXLHSInRHSPart = false;
7892 IsPostfixUpdate = true;
7893 } else {
7894 ErrorFound = NotASpecificExpression;
7895 ErrorLoc = FirstBinOp->getExprLoc();
7896 ErrorRange = FirstBinOp->getSourceRange();
7897 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7898 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7899 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007900 }
7901 }
7902 }
7903 }
7904 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007905 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007906 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007907 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007908 ErrorFound = NotTwoSubstatements;
7909 }
7910 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007911 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007912 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007913 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007914 ErrorFound = NotACompoundStatement;
7915 }
7916 if (ErrorFound != NoError) {
7917 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7918 << ErrorRange;
7919 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7920 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007921 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007922 if (CurContext->isDependentContext())
7923 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007924 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007925 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007926
Reid Kleckner87a31802018-03-12 21:43:02 +00007927 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007928
Alexey Bataev62cec442014-11-18 10:14:22 +00007929 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007930 X, V, E, UE, IsXLHSInRHSPart,
7931 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007932}
7933
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007934StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7935 Stmt *AStmt,
7936 SourceLocation StartLoc,
7937 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007938 if (!AStmt)
7939 return StmtError();
7940
Alexey Bataeve3727102018-04-18 15:57:46 +00007941 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007942 // 1.2.2 OpenMP Language Terminology
7943 // Structured block - An executable statement with a single entry at the
7944 // top and a single exit at the bottom.
7945 // The point of exit cannot be a branch out of the structured block.
7946 // longjmp() and throw() must not violate the entry/exit criteria.
7947 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007948 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7949 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7950 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7951 // 1.2.2 OpenMP Language Terminology
7952 // Structured block - An executable statement with a single entry at the
7953 // top and a single exit at the bottom.
7954 // The point of exit cannot be a branch out of the structured block.
7955 // longjmp() and throw() must not violate the entry/exit criteria.
7956 CS->getCapturedDecl()->setNothrow();
7957 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007958
Alexey Bataev13314bf2014-10-09 04:18:56 +00007959 // OpenMP [2.16, Nesting of Regions]
7960 // If specified, a teams construct must be contained within a target
7961 // construct. That target construct must contain no statements or directives
7962 // outside of the teams construct.
7963 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007964 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007965 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007966 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007967 auto I = CS->body_begin();
7968 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007969 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007970 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7971 OMPTeamsFound) {
7972
Alexey Bataev13314bf2014-10-09 04:18:56 +00007973 OMPTeamsFound = false;
7974 break;
7975 }
7976 ++I;
7977 }
7978 assert(I != CS->body_end() && "Not found statement");
7979 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007980 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007982 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007983 }
7984 if (!OMPTeamsFound) {
7985 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7986 Diag(DSAStack->getInnerTeamsRegionLoc(),
7987 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007988 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007989 << isa<OMPExecutableDirective>(S);
7990 return StmtError();
7991 }
7992 }
7993
Reid Kleckner87a31802018-03-12 21:43:02 +00007994 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007995
7996 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7997}
7998
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007999StmtResult
8000Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8001 Stmt *AStmt, SourceLocation StartLoc,
8002 SourceLocation EndLoc) {
8003 if (!AStmt)
8004 return StmtError();
8005
Alexey Bataeve3727102018-04-18 15:57:46 +00008006 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008007 // 1.2.2 OpenMP Language Terminology
8008 // Structured block - An executable statement with a single entry at the
8009 // top and a single exit at the bottom.
8010 // The point of exit cannot be a branch out of the structured block.
8011 // longjmp() and throw() must not violate the entry/exit criteria.
8012 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008013 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8014 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8015 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8016 // 1.2.2 OpenMP Language Terminology
8017 // Structured block - An executable statement with a single entry at the
8018 // top and a single exit at the bottom.
8019 // The point of exit cannot be a branch out of the structured block.
8020 // longjmp() and throw() must not violate the entry/exit criteria.
8021 CS->getCapturedDecl()->setNothrow();
8022 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008023
Reid Kleckner87a31802018-03-12 21:43:02 +00008024 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008025
8026 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8027 AStmt);
8028}
8029
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008030StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
8031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008032 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008033 if (!AStmt)
8034 return StmtError();
8035
Alexey Bataeve3727102018-04-18 15:57:46 +00008036 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008037 // 1.2.2 OpenMP Language Terminology
8038 // Structured block - An executable statement with a single entry at the
8039 // top and a single exit at the bottom.
8040 // The point of exit cannot be a branch out of the structured block.
8041 // longjmp() and throw() must not violate the entry/exit criteria.
8042 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008043 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8044 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8045 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8046 // 1.2.2 OpenMP Language Terminology
8047 // Structured block - An executable statement with a single entry at the
8048 // top and a single exit at the bottom.
8049 // The point of exit cannot be a branch out of the structured block.
8050 // longjmp() and throw() must not violate the entry/exit criteria.
8051 CS->getCapturedDecl()->setNothrow();
8052 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008053
8054 OMPLoopDirective::HelperExprs B;
8055 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8056 // define the nested loops number.
8057 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008058 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008059 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008060 VarsWithImplicitDSA, B);
8061 if (NestedLoopCount == 0)
8062 return StmtError();
8063
8064 assert((CurContext->isDependentContext() || B.builtAll()) &&
8065 "omp target parallel for loop exprs were not built");
8066
8067 if (!CurContext->isDependentContext()) {
8068 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008069 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008070 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008071 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008072 B.NumIterations, *this, CurScope,
8073 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008074 return StmtError();
8075 }
8076 }
8077
Reid Kleckner87a31802018-03-12 21:43:02 +00008078 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008079 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8080 NestedLoopCount, Clauses, AStmt,
8081 B, DSAStack->isCancelRegion());
8082}
8083
Alexey Bataev95b64a92017-05-30 16:00:04 +00008084/// Check for existence of a map clause in the list of clauses.
8085static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8086 const OpenMPClauseKind K) {
8087 return llvm::any_of(
8088 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8089}
Samuel Antaodf67fc42016-01-19 19:15:56 +00008090
Alexey Bataev95b64a92017-05-30 16:00:04 +00008091template <typename... Params>
8092static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
8093 const Params... ClauseTypes) {
8094 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008095}
8096
Michael Wong65f367f2015-07-21 13:44:28 +00008097StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8098 Stmt *AStmt,
8099 SourceLocation StartLoc,
8100 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008101 if (!AStmt)
8102 return StmtError();
8103
8104 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8105
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008106 // OpenMP [2.10.1, Restrictions, p. 97]
8107 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008108 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
8109 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8110 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00008111 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008112 return StmtError();
8113 }
8114
Reid Kleckner87a31802018-03-12 21:43:02 +00008115 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00008116
8117 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8118 AStmt);
8119}
8120
Samuel Antaodf67fc42016-01-19 19:15:56 +00008121StmtResult
8122Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8123 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008124 SourceLocation EndLoc, Stmt *AStmt) {
8125 if (!AStmt)
8126 return StmtError();
8127
Alexey Bataeve3727102018-04-18 15:57:46 +00008128 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008129 // 1.2.2 OpenMP Language Terminology
8130 // Structured block - An executable statement with a single entry at the
8131 // top and a single exit at the bottom.
8132 // The point of exit cannot be a branch out of the structured block.
8133 // longjmp() and throw() must not violate the entry/exit criteria.
8134 CS->getCapturedDecl()->setNothrow();
8135 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
8136 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8137 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8138 // 1.2.2 OpenMP Language Terminology
8139 // Structured block - An executable statement with a single entry at the
8140 // top and a single exit at the bottom.
8141 // The point of exit cannot be a branch out of the structured block.
8142 // longjmp() and throw() must not violate the entry/exit criteria.
8143 CS->getCapturedDecl()->setNothrow();
8144 }
8145
Samuel Antaodf67fc42016-01-19 19:15:56 +00008146 // OpenMP [2.10.2, Restrictions, p. 99]
8147 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008148 if (!hasClauses(Clauses, OMPC_map)) {
8149 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8150 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008151 return StmtError();
8152 }
8153
Alexey Bataev7828b252017-11-21 17:08:48 +00008154 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8155 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008156}
8157
Samuel Antao72590762016-01-19 20:04:50 +00008158StmtResult
8159Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8160 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008161 SourceLocation EndLoc, Stmt *AStmt) {
8162 if (!AStmt)
8163 return StmtError();
8164
Alexey Bataeve3727102018-04-18 15:57:46 +00008165 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008166 // 1.2.2 OpenMP Language Terminology
8167 // Structured block - An executable statement with a single entry at the
8168 // top and a single exit at the bottom.
8169 // The point of exit cannot be a branch out of the structured block.
8170 // longjmp() and throw() must not violate the entry/exit criteria.
8171 CS->getCapturedDecl()->setNothrow();
8172 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
8173 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8174 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8175 // 1.2.2 OpenMP Language Terminology
8176 // Structured block - An executable statement with a single entry at the
8177 // top and a single exit at the bottom.
8178 // The point of exit cannot be a branch out of the structured block.
8179 // longjmp() and throw() must not violate the entry/exit criteria.
8180 CS->getCapturedDecl()->setNothrow();
8181 }
8182
Samuel Antao72590762016-01-19 20:04:50 +00008183 // OpenMP [2.10.3, Restrictions, p. 102]
8184 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008185 if (!hasClauses(Clauses, OMPC_map)) {
8186 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8187 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00008188 return StmtError();
8189 }
8190
Alexey Bataev7828b252017-11-21 17:08:48 +00008191 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8192 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00008193}
8194
Samuel Antao686c70c2016-05-26 17:30:50 +00008195StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
8196 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008197 SourceLocation EndLoc,
8198 Stmt *AStmt) {
8199 if (!AStmt)
8200 return StmtError();
8201
Alexey Bataeve3727102018-04-18 15:57:46 +00008202 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008203 // 1.2.2 OpenMP Language Terminology
8204 // Structured block - An executable statement with a single entry at the
8205 // top and a single exit at the bottom.
8206 // The point of exit cannot be a branch out of the structured block.
8207 // longjmp() and throw() must not violate the entry/exit criteria.
8208 CS->getCapturedDecl()->setNothrow();
8209 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
8210 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8211 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8212 // 1.2.2 OpenMP Language Terminology
8213 // Structured block - An executable statement with a single entry at the
8214 // top and a single exit at the bottom.
8215 // The point of exit cannot be a branch out of the structured block.
8216 // longjmp() and throw() must not violate the entry/exit criteria.
8217 CS->getCapturedDecl()->setNothrow();
8218 }
8219
Alexey Bataev95b64a92017-05-30 16:00:04 +00008220 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00008221 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
8222 return StmtError();
8223 }
Alexey Bataev7828b252017-11-21 17:08:48 +00008224 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
8225 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00008226}
8227
Alexey Bataev13314bf2014-10-09 04:18:56 +00008228StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
8229 Stmt *AStmt, SourceLocation StartLoc,
8230 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008231 if (!AStmt)
8232 return StmtError();
8233
Alexey Bataeve3727102018-04-18 15:57:46 +00008234 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008235 // 1.2.2 OpenMP Language Terminology
8236 // Structured block - An executable statement with a single entry at the
8237 // top and a single exit at the bottom.
8238 // The point of exit cannot be a branch out of the structured block.
8239 // longjmp() and throw() must not violate the entry/exit criteria.
8240 CS->getCapturedDecl()->setNothrow();
8241
Reid Kleckner87a31802018-03-12 21:43:02 +00008242 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00008243
Alexey Bataevceabd412017-11-30 18:01:54 +00008244 DSAStack->setParentTeamsRegionLoc(StartLoc);
8245
Alexey Bataev13314bf2014-10-09 04:18:56 +00008246 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8247}
8248
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008249StmtResult
8250Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8251 SourceLocation EndLoc,
8252 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008253 if (DSAStack->isParentNowaitRegion()) {
8254 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
8255 return StmtError();
8256 }
8257 if (DSAStack->isParentOrderedRegion()) {
8258 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
8259 return StmtError();
8260 }
8261 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
8262 CancelRegion);
8263}
8264
Alexey Bataev87933c72015-09-18 08:07:34 +00008265StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8266 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00008267 SourceLocation EndLoc,
8268 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00008269 if (DSAStack->isParentNowaitRegion()) {
8270 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
8271 return StmtError();
8272 }
8273 if (DSAStack->isParentOrderedRegion()) {
8274 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
8275 return StmtError();
8276 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008277 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00008278 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8279 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00008280}
8281
Alexey Bataev382967a2015-12-08 12:06:20 +00008282static bool checkGrainsizeNumTasksClauses(Sema &S,
8283 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008284 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00008285 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008286 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00008287 if (C->getClauseKind() == OMPC_grainsize ||
8288 C->getClauseKind() == OMPC_num_tasks) {
8289 if (!PrevClause)
8290 PrevClause = C;
8291 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008292 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008293 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
8294 << getOpenMPClauseName(C->getClauseKind())
8295 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008296 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008297 diag::note_omp_previous_grainsize_num_tasks)
8298 << getOpenMPClauseName(PrevClause->getClauseKind());
8299 ErrorFound = true;
8300 }
8301 }
8302 }
8303 return ErrorFound;
8304}
8305
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008306static bool checkReductionClauseWithNogroup(Sema &S,
8307 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008308 const OMPClause *ReductionClause = nullptr;
8309 const OMPClause *NogroupClause = nullptr;
8310 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008311 if (C->getClauseKind() == OMPC_reduction) {
8312 ReductionClause = C;
8313 if (NogroupClause)
8314 break;
8315 continue;
8316 }
8317 if (C->getClauseKind() == OMPC_nogroup) {
8318 NogroupClause = C;
8319 if (ReductionClause)
8320 break;
8321 continue;
8322 }
8323 }
8324 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008325 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
8326 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008327 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008328 return true;
8329 }
8330 return false;
8331}
8332
Alexey Bataev49f6e782015-12-01 04:18:41 +00008333StmtResult Sema::ActOnOpenMPTaskLoopDirective(
8334 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008335 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00008336 if (!AStmt)
8337 return StmtError();
8338
8339 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8340 OMPLoopDirective::HelperExprs B;
8341 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8342 // define the nested loops number.
8343 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008344 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008345 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00008346 VarsWithImplicitDSA, B);
8347 if (NestedLoopCount == 0)
8348 return StmtError();
8349
8350 assert((CurContext->isDependentContext() || B.builtAll()) &&
8351 "omp for loop exprs were not built");
8352
Alexey Bataev382967a2015-12-08 12:06:20 +00008353 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8354 // The grainsize clause and num_tasks clause are mutually exclusive and may
8355 // not appear on the same taskloop directive.
8356 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8357 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008358 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8359 // If a reduction clause is present on the taskloop directive, the nogroup
8360 // clause must not be specified.
8361 if (checkReductionClauseWithNogroup(*this, Clauses))
8362 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008363
Reid Kleckner87a31802018-03-12 21:43:02 +00008364 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00008365 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
8366 NestedLoopCount, Clauses, AStmt, B);
8367}
8368
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008369StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
8370 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008371 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008372 if (!AStmt)
8373 return StmtError();
8374
8375 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8376 OMPLoopDirective::HelperExprs B;
8377 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8378 // define the nested loops number.
8379 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008380 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008381 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
8382 VarsWithImplicitDSA, B);
8383 if (NestedLoopCount == 0)
8384 return StmtError();
8385
8386 assert((CurContext->isDependentContext() || B.builtAll()) &&
8387 "omp for loop exprs were not built");
8388
Alexey Bataev5a3af132016-03-29 08:58:54 +00008389 if (!CurContext->isDependentContext()) {
8390 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008391 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008392 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008393 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008394 B.NumIterations, *this, CurScope,
8395 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008396 return StmtError();
8397 }
8398 }
8399
Alexey Bataev382967a2015-12-08 12:06:20 +00008400 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8401 // The grainsize clause and num_tasks clause are mutually exclusive and may
8402 // not appear on the same taskloop directive.
8403 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8404 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008405 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8406 // If a reduction clause is present on the taskloop directive, the nogroup
8407 // clause must not be specified.
8408 if (checkReductionClauseWithNogroup(*this, Clauses))
8409 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00008410 if (checkSimdlenSafelenSpecified(*this, Clauses))
8411 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008412
Reid Kleckner87a31802018-03-12 21:43:02 +00008413 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008414 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
8415 NestedLoopCount, Clauses, AStmt, B);
8416}
8417
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008418StmtResult Sema::ActOnOpenMPDistributeDirective(
8419 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008420 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008421 if (!AStmt)
8422 return StmtError();
8423
8424 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8425 OMPLoopDirective::HelperExprs B;
8426 // In presence of clause 'collapse' with number of loops, it will
8427 // define the nested loops number.
8428 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008429 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008430 nullptr /*ordered not a clause on distribute*/, AStmt,
8431 *this, *DSAStack, VarsWithImplicitDSA, B);
8432 if (NestedLoopCount == 0)
8433 return StmtError();
8434
8435 assert((CurContext->isDependentContext() || B.builtAll()) &&
8436 "omp for loop exprs were not built");
8437
Reid Kleckner87a31802018-03-12 21:43:02 +00008438 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008439 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
8440 NestedLoopCount, Clauses, AStmt, B);
8441}
8442
Carlo Bertolli9925f152016-06-27 14:55:37 +00008443StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
8444 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008445 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00008446 if (!AStmt)
8447 return StmtError();
8448
Alexey Bataeve3727102018-04-18 15:57:46 +00008449 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00008450 // 1.2.2 OpenMP Language Terminology
8451 // Structured block - An executable statement with a single entry at the
8452 // top and a single exit at the bottom.
8453 // The point of exit cannot be a branch out of the structured block.
8454 // longjmp() and throw() must not violate the entry/exit criteria.
8455 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00008456 for (int ThisCaptureLevel =
8457 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
8458 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8459 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8460 // 1.2.2 OpenMP Language Terminology
8461 // Structured block - An executable statement with a single entry at the
8462 // top and a single exit at the bottom.
8463 // The point of exit cannot be a branch out of the structured block.
8464 // longjmp() and throw() must not violate the entry/exit criteria.
8465 CS->getCapturedDecl()->setNothrow();
8466 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00008467
8468 OMPLoopDirective::HelperExprs B;
8469 // In presence of clause 'collapse' with number of loops, it will
8470 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008471 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00008472 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00008473 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00008474 VarsWithImplicitDSA, B);
8475 if (NestedLoopCount == 0)
8476 return StmtError();
8477
8478 assert((CurContext->isDependentContext() || B.builtAll()) &&
8479 "omp for loop exprs were not built");
8480
Reid Kleckner87a31802018-03-12 21:43:02 +00008481 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008482 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008483 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8484 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00008485}
8486
Kelvin Li4a39add2016-07-05 05:00:15 +00008487StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
8488 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008489 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00008490 if (!AStmt)
8491 return StmtError();
8492
Alexey Bataeve3727102018-04-18 15:57:46 +00008493 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00008494 // 1.2.2 OpenMP Language Terminology
8495 // Structured block - An executable statement with a single entry at the
8496 // top and a single exit at the bottom.
8497 // The point of exit cannot be a branch out of the structured block.
8498 // longjmp() and throw() must not violate the entry/exit criteria.
8499 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00008500 for (int ThisCaptureLevel =
8501 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
8502 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8503 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8504 // 1.2.2 OpenMP Language Terminology
8505 // Structured block - An executable statement with a single entry at the
8506 // top and a single exit at the bottom.
8507 // The point of exit cannot be a branch out of the structured block.
8508 // longjmp() and throw() must not violate the entry/exit criteria.
8509 CS->getCapturedDecl()->setNothrow();
8510 }
Kelvin Li4a39add2016-07-05 05:00:15 +00008511
8512 OMPLoopDirective::HelperExprs B;
8513 // In presence of clause 'collapse' with number of loops, it will
8514 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008515 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00008516 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00008517 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00008518 VarsWithImplicitDSA, B);
8519 if (NestedLoopCount == 0)
8520 return StmtError();
8521
8522 assert((CurContext->isDependentContext() || B.builtAll()) &&
8523 "omp for loop exprs were not built");
8524
Alexey Bataev438388c2017-11-22 18:34:02 +00008525 if (!CurContext->isDependentContext()) {
8526 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008527 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008528 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8529 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8530 B.NumIterations, *this, CurScope,
8531 DSAStack))
8532 return StmtError();
8533 }
8534 }
8535
Kelvin Lic5609492016-07-15 04:39:07 +00008536 if (checkSimdlenSafelenSpecified(*this, Clauses))
8537 return StmtError();
8538
Reid Kleckner87a31802018-03-12 21:43:02 +00008539 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00008540 return OMPDistributeParallelForSimdDirective::Create(
8541 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8542}
8543
Kelvin Li787f3fc2016-07-06 04:45:38 +00008544StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
8545 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008546 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00008547 if (!AStmt)
8548 return StmtError();
8549
Alexey Bataeve3727102018-04-18 15:57:46 +00008550 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008551 // 1.2.2 OpenMP Language Terminology
8552 // Structured block - An executable statement with a single entry at the
8553 // top and a single exit at the bottom.
8554 // The point of exit cannot be a branch out of the structured block.
8555 // longjmp() and throw() must not violate the entry/exit criteria.
8556 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00008557 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
8558 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8559 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8560 // 1.2.2 OpenMP Language Terminology
8561 // Structured block - An executable statement with a single entry at the
8562 // top and a single exit at the bottom.
8563 // The point of exit cannot be a branch out of the structured block.
8564 // longjmp() and throw() must not violate the entry/exit criteria.
8565 CS->getCapturedDecl()->setNothrow();
8566 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00008567
8568 OMPLoopDirective::HelperExprs B;
8569 // In presence of clause 'collapse' with number of loops, it will
8570 // define the nested loops number.
8571 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008572 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00008573 nullptr /*ordered not a clause on distribute*/, CS, *this,
8574 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008575 if (NestedLoopCount == 0)
8576 return StmtError();
8577
8578 assert((CurContext->isDependentContext() || B.builtAll()) &&
8579 "omp for loop exprs were not built");
8580
Alexey Bataev438388c2017-11-22 18:34:02 +00008581 if (!CurContext->isDependentContext()) {
8582 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008583 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008584 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8585 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8586 B.NumIterations, *this, CurScope,
8587 DSAStack))
8588 return StmtError();
8589 }
8590 }
8591
Kelvin Lic5609492016-07-15 04:39:07 +00008592 if (checkSimdlenSafelenSpecified(*this, Clauses))
8593 return StmtError();
8594
Reid Kleckner87a31802018-03-12 21:43:02 +00008595 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00008596 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8597 NestedLoopCount, Clauses, AStmt, B);
8598}
8599
Kelvin Lia579b912016-07-14 02:54:56 +00008600StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8601 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008602 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00008603 if (!AStmt)
8604 return StmtError();
8605
Alexey Bataeve3727102018-04-18 15:57:46 +00008606 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00008607 // 1.2.2 OpenMP Language Terminology
8608 // Structured block - An executable statement with a single entry at the
8609 // top and a single exit at the bottom.
8610 // The point of exit cannot be a branch out of the structured block.
8611 // longjmp() and throw() must not violate the entry/exit criteria.
8612 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008613 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8614 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8615 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8616 // 1.2.2 OpenMP Language Terminology
8617 // Structured block - An executable statement with a single entry at the
8618 // top and a single exit at the bottom.
8619 // The point of exit cannot be a branch out of the structured block.
8620 // longjmp() and throw() must not violate the entry/exit criteria.
8621 CS->getCapturedDecl()->setNothrow();
8622 }
Kelvin Lia579b912016-07-14 02:54:56 +00008623
8624 OMPLoopDirective::HelperExprs B;
8625 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8626 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008627 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008628 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008629 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008630 VarsWithImplicitDSA, B);
8631 if (NestedLoopCount == 0)
8632 return StmtError();
8633
8634 assert((CurContext->isDependentContext() || B.builtAll()) &&
8635 "omp target parallel for simd loop exprs were not built");
8636
8637 if (!CurContext->isDependentContext()) {
8638 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008639 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008640 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008641 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8642 B.NumIterations, *this, CurScope,
8643 DSAStack))
8644 return StmtError();
8645 }
8646 }
Kelvin Lic5609492016-07-15 04:39:07 +00008647 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008648 return StmtError();
8649
Reid Kleckner87a31802018-03-12 21:43:02 +00008650 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008651 return OMPTargetParallelForSimdDirective::Create(
8652 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8653}
8654
Kelvin Li986330c2016-07-20 22:57:10 +00008655StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8656 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008657 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008658 if (!AStmt)
8659 return StmtError();
8660
Alexey Bataeve3727102018-04-18 15:57:46 +00008661 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008662 // 1.2.2 OpenMP Language Terminology
8663 // Structured block - An executable statement with a single entry at the
8664 // top and a single exit at the bottom.
8665 // The point of exit cannot be a branch out of the structured block.
8666 // longjmp() and throw() must not violate the entry/exit criteria.
8667 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008668 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8669 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8670 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8671 // 1.2.2 OpenMP Language Terminology
8672 // Structured block - An executable statement with a single entry at the
8673 // top and a single exit at the bottom.
8674 // The point of exit cannot be a branch out of the structured block.
8675 // longjmp() and throw() must not violate the entry/exit criteria.
8676 CS->getCapturedDecl()->setNothrow();
8677 }
8678
Kelvin Li986330c2016-07-20 22:57:10 +00008679 OMPLoopDirective::HelperExprs B;
8680 // In presence of clause 'collapse' with number of loops, it will define the
8681 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008682 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008683 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008684 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008685 VarsWithImplicitDSA, B);
8686 if (NestedLoopCount == 0)
8687 return StmtError();
8688
8689 assert((CurContext->isDependentContext() || B.builtAll()) &&
8690 "omp target simd loop exprs were not built");
8691
8692 if (!CurContext->isDependentContext()) {
8693 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008694 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008695 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008696 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8697 B.NumIterations, *this, CurScope,
8698 DSAStack))
8699 return StmtError();
8700 }
8701 }
8702
8703 if (checkSimdlenSafelenSpecified(*this, Clauses))
8704 return StmtError();
8705
Reid Kleckner87a31802018-03-12 21:43:02 +00008706 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008707 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8708 NestedLoopCount, Clauses, AStmt, B);
8709}
8710
Kelvin Li02532872016-08-05 14:37:37 +00008711StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008713 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008714 if (!AStmt)
8715 return StmtError();
8716
Alexey Bataeve3727102018-04-18 15:57:46 +00008717 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008718 // 1.2.2 OpenMP Language Terminology
8719 // Structured block - An executable statement with a single entry at the
8720 // top and a single exit at the bottom.
8721 // The point of exit cannot be a branch out of the structured block.
8722 // longjmp() and throw() must not violate the entry/exit criteria.
8723 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008724 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8725 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8726 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8727 // 1.2.2 OpenMP Language Terminology
8728 // Structured block - An executable statement with a single entry at the
8729 // top and a single exit at the bottom.
8730 // The point of exit cannot be a branch out of the structured block.
8731 // longjmp() and throw() must not violate the entry/exit criteria.
8732 CS->getCapturedDecl()->setNothrow();
8733 }
Kelvin Li02532872016-08-05 14:37:37 +00008734
8735 OMPLoopDirective::HelperExprs B;
8736 // In presence of clause 'collapse' with number of loops, it will
8737 // define the nested loops number.
8738 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008739 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008740 nullptr /*ordered not a clause on distribute*/, CS, *this,
8741 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008742 if (NestedLoopCount == 0)
8743 return StmtError();
8744
8745 assert((CurContext->isDependentContext() || B.builtAll()) &&
8746 "omp teams distribute loop exprs were not built");
8747
Reid Kleckner87a31802018-03-12 21:43:02 +00008748 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008749
8750 DSAStack->setParentTeamsRegionLoc(StartLoc);
8751
David Majnemer9d168222016-08-05 17:44:54 +00008752 return OMPTeamsDistributeDirective::Create(
8753 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008754}
8755
Kelvin Li4e325f72016-10-25 12:50:55 +00008756StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008758 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008759 if (!AStmt)
8760 return StmtError();
8761
Alexey Bataeve3727102018-04-18 15:57:46 +00008762 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008763 // 1.2.2 OpenMP Language Terminology
8764 // Structured block - An executable statement with a single entry at the
8765 // top and a single exit at the bottom.
8766 // The point of exit cannot be a branch out of the structured block.
8767 // longjmp() and throw() must not violate the entry/exit criteria.
8768 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008769 for (int ThisCaptureLevel =
8770 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8771 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8772 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8773 // 1.2.2 OpenMP Language Terminology
8774 // Structured block - An executable statement with a single entry at the
8775 // top and a single exit at the bottom.
8776 // The point of exit cannot be a branch out of the structured block.
8777 // longjmp() and throw() must not violate the entry/exit criteria.
8778 CS->getCapturedDecl()->setNothrow();
8779 }
8780
Kelvin Li4e325f72016-10-25 12:50:55 +00008781
8782 OMPLoopDirective::HelperExprs B;
8783 // In presence of clause 'collapse' with number of loops, it will
8784 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008785 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008786 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008787 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008788 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008789
8790 if (NestedLoopCount == 0)
8791 return StmtError();
8792
8793 assert((CurContext->isDependentContext() || B.builtAll()) &&
8794 "omp teams distribute simd loop exprs were not built");
8795
8796 if (!CurContext->isDependentContext()) {
8797 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008798 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008799 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8800 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8801 B.NumIterations, *this, CurScope,
8802 DSAStack))
8803 return StmtError();
8804 }
8805 }
8806
8807 if (checkSimdlenSafelenSpecified(*this, Clauses))
8808 return StmtError();
8809
Reid Kleckner87a31802018-03-12 21:43:02 +00008810 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008811
8812 DSAStack->setParentTeamsRegionLoc(StartLoc);
8813
Kelvin Li4e325f72016-10-25 12:50:55 +00008814 return OMPTeamsDistributeSimdDirective::Create(
8815 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8816}
8817
Kelvin Li579e41c2016-11-30 23:51:03 +00008818StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008820 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008821 if (!AStmt)
8822 return StmtError();
8823
Alexey Bataeve3727102018-04-18 15:57:46 +00008824 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008825 // 1.2.2 OpenMP Language Terminology
8826 // Structured block - An executable statement with a single entry at the
8827 // top and a single exit at the bottom.
8828 // The point of exit cannot be a branch out of the structured block.
8829 // longjmp() and throw() must not violate the entry/exit criteria.
8830 CS->getCapturedDecl()->setNothrow();
8831
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008832 for (int ThisCaptureLevel =
8833 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8834 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8835 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8836 // 1.2.2 OpenMP Language Terminology
8837 // Structured block - An executable statement with a single entry at the
8838 // top and a single exit at the bottom.
8839 // The point of exit cannot be a branch out of the structured block.
8840 // longjmp() and throw() must not violate the entry/exit criteria.
8841 CS->getCapturedDecl()->setNothrow();
8842 }
8843
Kelvin Li579e41c2016-11-30 23:51:03 +00008844 OMPLoopDirective::HelperExprs B;
8845 // In presence of clause 'collapse' with number of loops, it will
8846 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008847 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008848 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008849 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008850 VarsWithImplicitDSA, B);
8851
8852 if (NestedLoopCount == 0)
8853 return StmtError();
8854
8855 assert((CurContext->isDependentContext() || B.builtAll()) &&
8856 "omp for loop exprs were not built");
8857
8858 if (!CurContext->isDependentContext()) {
8859 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008860 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008861 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8862 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8863 B.NumIterations, *this, CurScope,
8864 DSAStack))
8865 return StmtError();
8866 }
8867 }
8868
8869 if (checkSimdlenSafelenSpecified(*this, Clauses))
8870 return StmtError();
8871
Reid Kleckner87a31802018-03-12 21:43:02 +00008872 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008873
8874 DSAStack->setParentTeamsRegionLoc(StartLoc);
8875
Kelvin Li579e41c2016-11-30 23:51:03 +00008876 return OMPTeamsDistributeParallelForSimdDirective::Create(
8877 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8878}
8879
Kelvin Li7ade93f2016-12-09 03:24:30 +00008880StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8881 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008882 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008883 if (!AStmt)
8884 return StmtError();
8885
Alexey Bataeve3727102018-04-18 15:57:46 +00008886 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008887 // 1.2.2 OpenMP Language Terminology
8888 // Structured block - An executable statement with a single entry at the
8889 // top and a single exit at the bottom.
8890 // The point of exit cannot be a branch out of the structured block.
8891 // longjmp() and throw() must not violate the entry/exit criteria.
8892 CS->getCapturedDecl()->setNothrow();
8893
Carlo Bertolli62fae152017-11-20 20:46:39 +00008894 for (int ThisCaptureLevel =
8895 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8896 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8897 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8898 // 1.2.2 OpenMP Language Terminology
8899 // Structured block - An executable statement with a single entry at the
8900 // top and a single exit at the bottom.
8901 // The point of exit cannot be a branch out of the structured block.
8902 // longjmp() and throw() must not violate the entry/exit criteria.
8903 CS->getCapturedDecl()->setNothrow();
8904 }
8905
Kelvin Li7ade93f2016-12-09 03:24:30 +00008906 OMPLoopDirective::HelperExprs B;
8907 // In presence of clause 'collapse' with number of loops, it will
8908 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008909 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008910 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008911 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008912 VarsWithImplicitDSA, B);
8913
8914 if (NestedLoopCount == 0)
8915 return StmtError();
8916
8917 assert((CurContext->isDependentContext() || B.builtAll()) &&
8918 "omp for loop exprs were not built");
8919
Reid Kleckner87a31802018-03-12 21:43:02 +00008920 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008921
8922 DSAStack->setParentTeamsRegionLoc(StartLoc);
8923
Kelvin Li7ade93f2016-12-09 03:24:30 +00008924 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008925 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8926 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008927}
8928
Kelvin Libf594a52016-12-17 05:48:59 +00008929StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8930 Stmt *AStmt,
8931 SourceLocation StartLoc,
8932 SourceLocation EndLoc) {
8933 if (!AStmt)
8934 return StmtError();
8935
Alexey Bataeve3727102018-04-18 15:57:46 +00008936 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008937 // 1.2.2 OpenMP Language Terminology
8938 // Structured block - An executable statement with a single entry at the
8939 // top and a single exit at the bottom.
8940 // The point of exit cannot be a branch out of the structured block.
8941 // longjmp() and throw() must not violate the entry/exit criteria.
8942 CS->getCapturedDecl()->setNothrow();
8943
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008944 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8945 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8946 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8947 // 1.2.2 OpenMP Language Terminology
8948 // Structured block - An executable statement with a single entry at the
8949 // top and a single exit at the bottom.
8950 // The point of exit cannot be a branch out of the structured block.
8951 // longjmp() and throw() must not violate the entry/exit criteria.
8952 CS->getCapturedDecl()->setNothrow();
8953 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008954 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008955
8956 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8957 AStmt);
8958}
8959
Kelvin Li83c451e2016-12-25 04:52:54 +00008960StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8961 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008962 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008963 if (!AStmt)
8964 return StmtError();
8965
Alexey Bataeve3727102018-04-18 15:57:46 +00008966 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008967 // 1.2.2 OpenMP Language Terminology
8968 // Structured block - An executable statement with a single entry at the
8969 // top and a single exit at the bottom.
8970 // The point of exit cannot be a branch out of the structured block.
8971 // longjmp() and throw() must not violate the entry/exit criteria.
8972 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008973 for (int ThisCaptureLevel =
8974 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8975 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8976 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8977 // 1.2.2 OpenMP Language Terminology
8978 // Structured block - An executable statement with a single entry at the
8979 // top and a single exit at the bottom.
8980 // The point of exit cannot be a branch out of the structured block.
8981 // longjmp() and throw() must not violate the entry/exit criteria.
8982 CS->getCapturedDecl()->setNothrow();
8983 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008984
8985 OMPLoopDirective::HelperExprs B;
8986 // In presence of clause 'collapse' with number of loops, it will
8987 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008988 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008989 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8990 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008991 VarsWithImplicitDSA, B);
8992 if (NestedLoopCount == 0)
8993 return StmtError();
8994
8995 assert((CurContext->isDependentContext() || B.builtAll()) &&
8996 "omp target teams distribute loop exprs were not built");
8997
Reid Kleckner87a31802018-03-12 21:43:02 +00008998 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008999 return OMPTargetTeamsDistributeDirective::Create(
9000 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9001}
9002
Kelvin Li80e8f562016-12-29 22:16:30 +00009003StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9004 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009005 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00009006 if (!AStmt)
9007 return StmtError();
9008
Alexey Bataeve3727102018-04-18 15:57:46 +00009009 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00009010 // 1.2.2 OpenMP Language Terminology
9011 // Structured block - An executable statement with a single entry at the
9012 // top and a single exit at the bottom.
9013 // The point of exit cannot be a branch out of the structured block.
9014 // longjmp() and throw() must not violate the entry/exit criteria.
9015 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00009016 for (int ThisCaptureLevel =
9017 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
9018 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9019 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9020 // 1.2.2 OpenMP Language Terminology
9021 // Structured block - An executable statement with a single entry at the
9022 // top and a single exit at the bottom.
9023 // The point of exit cannot be a branch out of the structured block.
9024 // longjmp() and throw() must not violate the entry/exit criteria.
9025 CS->getCapturedDecl()->setNothrow();
9026 }
9027
Kelvin Li80e8f562016-12-29 22:16:30 +00009028 OMPLoopDirective::HelperExprs B;
9029 // In presence of clause 'collapse' with number of loops, it will
9030 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009031 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00009032 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
9033 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00009034 VarsWithImplicitDSA, B);
9035 if (NestedLoopCount == 0)
9036 return StmtError();
9037
9038 assert((CurContext->isDependentContext() || B.builtAll()) &&
9039 "omp target teams distribute parallel for loop exprs were not built");
9040
Alexey Bataev647dd842018-01-15 20:59:40 +00009041 if (!CurContext->isDependentContext()) {
9042 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009043 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00009044 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9045 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9046 B.NumIterations, *this, CurScope,
9047 DSAStack))
9048 return StmtError();
9049 }
9050 }
9051
Reid Kleckner87a31802018-03-12 21:43:02 +00009052 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00009053 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00009054 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9055 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00009056}
9057
Kelvin Li1851df52017-01-03 05:23:48 +00009058StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9059 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009060 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00009061 if (!AStmt)
9062 return StmtError();
9063
Alexey Bataeve3727102018-04-18 15:57:46 +00009064 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00009065 // 1.2.2 OpenMP Language Terminology
9066 // Structured block - An executable statement with a single entry at the
9067 // top and a single exit at the bottom.
9068 // The point of exit cannot be a branch out of the structured block.
9069 // longjmp() and throw() must not violate the entry/exit criteria.
9070 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00009071 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
9072 OMPD_target_teams_distribute_parallel_for_simd);
9073 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9074 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9075 // 1.2.2 OpenMP Language Terminology
9076 // Structured block - An executable statement with a single entry at the
9077 // top and a single exit at the bottom.
9078 // The point of exit cannot be a branch out of the structured block.
9079 // longjmp() and throw() must not violate the entry/exit criteria.
9080 CS->getCapturedDecl()->setNothrow();
9081 }
Kelvin Li1851df52017-01-03 05:23:48 +00009082
9083 OMPLoopDirective::HelperExprs B;
9084 // In presence of clause 'collapse' with number of loops, it will
9085 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009086 unsigned NestedLoopCount =
9087 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00009088 getCollapseNumberExpr(Clauses),
9089 nullptr /*ordered not a clause on distribute*/, CS, *this,
9090 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00009091 if (NestedLoopCount == 0)
9092 return StmtError();
9093
9094 assert((CurContext->isDependentContext() || B.builtAll()) &&
9095 "omp target teams distribute parallel for simd loop exprs were not "
9096 "built");
9097
9098 if (!CurContext->isDependentContext()) {
9099 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009100 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00009101 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9102 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9103 B.NumIterations, *this, CurScope,
9104 DSAStack))
9105 return StmtError();
9106 }
9107 }
9108
Alexey Bataev438388c2017-11-22 18:34:02 +00009109 if (checkSimdlenSafelenSpecified(*this, Clauses))
9110 return StmtError();
9111
Reid Kleckner87a31802018-03-12 21:43:02 +00009112 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00009113 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
9114 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9115}
9116
Kelvin Lida681182017-01-10 18:08:18 +00009117StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
9118 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009119 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00009120 if (!AStmt)
9121 return StmtError();
9122
9123 auto *CS = cast<CapturedStmt>(AStmt);
9124 // 1.2.2 OpenMP Language Terminology
9125 // Structured block - An executable statement with a single entry at the
9126 // top and a single exit at the bottom.
9127 // The point of exit cannot be a branch out of the structured block.
9128 // longjmp() and throw() must not violate the entry/exit criteria.
9129 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009130 for (int ThisCaptureLevel =
9131 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
9132 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9133 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9134 // 1.2.2 OpenMP Language Terminology
9135 // Structured block - An executable statement with a single entry at the
9136 // top and a single exit at the bottom.
9137 // The point of exit cannot be a branch out of the structured block.
9138 // longjmp() and throw() must not violate the entry/exit criteria.
9139 CS->getCapturedDecl()->setNothrow();
9140 }
Kelvin Lida681182017-01-10 18:08:18 +00009141
9142 OMPLoopDirective::HelperExprs B;
9143 // In presence of clause 'collapse' with number of loops, it will
9144 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009145 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00009146 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009147 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00009148 VarsWithImplicitDSA, B);
9149 if (NestedLoopCount == 0)
9150 return StmtError();
9151
9152 assert((CurContext->isDependentContext() || B.builtAll()) &&
9153 "omp target teams distribute simd loop exprs were not built");
9154
Alexey Bataev438388c2017-11-22 18:34:02 +00009155 if (!CurContext->isDependentContext()) {
9156 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009157 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009158 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9159 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9160 B.NumIterations, *this, CurScope,
9161 DSAStack))
9162 return StmtError();
9163 }
9164 }
9165
9166 if (checkSimdlenSafelenSpecified(*this, Clauses))
9167 return StmtError();
9168
Reid Kleckner87a31802018-03-12 21:43:02 +00009169 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00009170 return OMPTargetTeamsDistributeSimdDirective::Create(
9171 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9172}
9173
Alexey Bataeved09d242014-05-28 05:53:51 +00009174OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009175 SourceLocation StartLoc,
9176 SourceLocation LParenLoc,
9177 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009178 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009179 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00009180 case OMPC_final:
9181 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
9182 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00009183 case OMPC_num_threads:
9184 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
9185 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009186 case OMPC_safelen:
9187 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
9188 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00009189 case OMPC_simdlen:
9190 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
9191 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009192 case OMPC_allocator:
9193 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
9194 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00009195 case OMPC_collapse:
9196 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
9197 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009198 case OMPC_ordered:
9199 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
9200 break;
Michael Wonge710d542015-08-07 16:16:36 +00009201 case OMPC_device:
9202 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
9203 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00009204 case OMPC_num_teams:
9205 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
9206 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009207 case OMPC_thread_limit:
9208 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
9209 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00009210 case OMPC_priority:
9211 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
9212 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009213 case OMPC_grainsize:
9214 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
9215 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00009216 case OMPC_num_tasks:
9217 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
9218 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00009219 case OMPC_hint:
9220 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
9221 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009222 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009223 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009224 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009225 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009226 case OMPC_private:
9227 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009228 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009229 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009230 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009231 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009232 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009233 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009234 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009235 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009236 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00009237 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009238 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009239 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009240 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009241 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009242 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009243 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009244 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009245 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009246 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009247 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009248 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00009249 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009250 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009251 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00009252 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009253 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009254 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009255 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009256 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009257 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009258 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009259 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009260 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009261 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009262 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009263 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009264 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009265 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009266 llvm_unreachable("Clause is not allowed.");
9267 }
9268 return Res;
9269}
9270
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009271// An OpenMP directive such as 'target parallel' has two captured regions:
9272// for the 'target' and 'parallel' respectively. This function returns
9273// the region in which to capture expressions associated with a clause.
9274// A return value of OMPD_unknown signifies that the expression should not
9275// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009276static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
9277 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
9278 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009279 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009280 switch (CKind) {
9281 case OMPC_if:
9282 switch (DKind) {
9283 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009284 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009285 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009286 // If this clause applies to the nested 'parallel' region, capture within
9287 // the 'target' region, otherwise do not capture.
9288 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9289 CaptureRegion = OMPD_target;
9290 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00009291 case OMPD_target_teams_distribute_parallel_for:
9292 case OMPD_target_teams_distribute_parallel_for_simd:
9293 // If this clause applies to the nested 'parallel' region, capture within
9294 // the 'teams' region, otherwise do not capture.
9295 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9296 CaptureRegion = OMPD_teams;
9297 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009298 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009299 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009300 CaptureRegion = OMPD_teams;
9301 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009302 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009303 case OMPD_target_enter_data:
9304 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009305 CaptureRegion = OMPD_task;
9306 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009307 case OMPD_cancel:
9308 case OMPD_parallel:
9309 case OMPD_parallel_sections:
9310 case OMPD_parallel_for:
9311 case OMPD_parallel_for_simd:
9312 case OMPD_target:
9313 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009314 case OMPD_target_teams:
9315 case OMPD_target_teams_distribute:
9316 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009317 case OMPD_distribute_parallel_for:
9318 case OMPD_distribute_parallel_for_simd:
9319 case OMPD_task:
9320 case OMPD_taskloop:
9321 case OMPD_taskloop_simd:
9322 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009323 // Do not capture if-clause expressions.
9324 break;
9325 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009326 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009327 case OMPD_taskyield:
9328 case OMPD_barrier:
9329 case OMPD_taskwait:
9330 case OMPD_cancellation_point:
9331 case OMPD_flush:
9332 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009333 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009334 case OMPD_declare_simd:
9335 case OMPD_declare_target:
9336 case OMPD_end_declare_target:
9337 case OMPD_teams:
9338 case OMPD_simd:
9339 case OMPD_for:
9340 case OMPD_for_simd:
9341 case OMPD_sections:
9342 case OMPD_section:
9343 case OMPD_single:
9344 case OMPD_master:
9345 case OMPD_critical:
9346 case OMPD_taskgroup:
9347 case OMPD_distribute:
9348 case OMPD_ordered:
9349 case OMPD_atomic:
9350 case OMPD_distribute_simd:
9351 case OMPD_teams_distribute:
9352 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009353 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009354 llvm_unreachable("Unexpected OpenMP directive with if-clause");
9355 case OMPD_unknown:
9356 llvm_unreachable("Unknown OpenMP directive");
9357 }
9358 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009359 case OMPC_num_threads:
9360 switch (DKind) {
9361 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009362 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009363 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009364 CaptureRegion = OMPD_target;
9365 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009366 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009367 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009368 case OMPD_target_teams_distribute_parallel_for:
9369 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009370 CaptureRegion = OMPD_teams;
9371 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009372 case OMPD_parallel:
9373 case OMPD_parallel_sections:
9374 case OMPD_parallel_for:
9375 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009376 case OMPD_distribute_parallel_for:
9377 case OMPD_distribute_parallel_for_simd:
9378 // Do not capture num_threads-clause expressions.
9379 break;
9380 case OMPD_target_data:
9381 case OMPD_target_enter_data:
9382 case OMPD_target_exit_data:
9383 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009384 case OMPD_target:
9385 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009386 case OMPD_target_teams:
9387 case OMPD_target_teams_distribute:
9388 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009389 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009390 case OMPD_task:
9391 case OMPD_taskloop:
9392 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009393 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009394 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009395 case OMPD_taskyield:
9396 case OMPD_barrier:
9397 case OMPD_taskwait:
9398 case OMPD_cancellation_point:
9399 case OMPD_flush:
9400 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009401 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009402 case OMPD_declare_simd:
9403 case OMPD_declare_target:
9404 case OMPD_end_declare_target:
9405 case OMPD_teams:
9406 case OMPD_simd:
9407 case OMPD_for:
9408 case OMPD_for_simd:
9409 case OMPD_sections:
9410 case OMPD_section:
9411 case OMPD_single:
9412 case OMPD_master:
9413 case OMPD_critical:
9414 case OMPD_taskgroup:
9415 case OMPD_distribute:
9416 case OMPD_ordered:
9417 case OMPD_atomic:
9418 case OMPD_distribute_simd:
9419 case OMPD_teams_distribute:
9420 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009421 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009422 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
9423 case OMPD_unknown:
9424 llvm_unreachable("Unknown OpenMP directive");
9425 }
9426 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009427 case OMPC_num_teams:
9428 switch (DKind) {
9429 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009430 case OMPD_target_teams_distribute:
9431 case OMPD_target_teams_distribute_simd:
9432 case OMPD_target_teams_distribute_parallel_for:
9433 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009434 CaptureRegion = OMPD_target;
9435 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009436 case OMPD_teams_distribute_parallel_for:
9437 case OMPD_teams_distribute_parallel_for_simd:
9438 case OMPD_teams:
9439 case OMPD_teams_distribute:
9440 case OMPD_teams_distribute_simd:
9441 // Do not capture num_teams-clause expressions.
9442 break;
9443 case OMPD_distribute_parallel_for:
9444 case OMPD_distribute_parallel_for_simd:
9445 case OMPD_task:
9446 case OMPD_taskloop:
9447 case OMPD_taskloop_simd:
9448 case OMPD_target_data:
9449 case OMPD_target_enter_data:
9450 case OMPD_target_exit_data:
9451 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009452 case OMPD_cancel:
9453 case OMPD_parallel:
9454 case OMPD_parallel_sections:
9455 case OMPD_parallel_for:
9456 case OMPD_parallel_for_simd:
9457 case OMPD_target:
9458 case OMPD_target_simd:
9459 case OMPD_target_parallel:
9460 case OMPD_target_parallel_for:
9461 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009462 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009463 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009464 case OMPD_taskyield:
9465 case OMPD_barrier:
9466 case OMPD_taskwait:
9467 case OMPD_cancellation_point:
9468 case OMPD_flush:
9469 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009470 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009471 case OMPD_declare_simd:
9472 case OMPD_declare_target:
9473 case OMPD_end_declare_target:
9474 case OMPD_simd:
9475 case OMPD_for:
9476 case OMPD_for_simd:
9477 case OMPD_sections:
9478 case OMPD_section:
9479 case OMPD_single:
9480 case OMPD_master:
9481 case OMPD_critical:
9482 case OMPD_taskgroup:
9483 case OMPD_distribute:
9484 case OMPD_ordered:
9485 case OMPD_atomic:
9486 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009487 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009488 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9489 case OMPD_unknown:
9490 llvm_unreachable("Unknown OpenMP directive");
9491 }
9492 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009493 case OMPC_thread_limit:
9494 switch (DKind) {
9495 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009496 case OMPD_target_teams_distribute:
9497 case OMPD_target_teams_distribute_simd:
9498 case OMPD_target_teams_distribute_parallel_for:
9499 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009500 CaptureRegion = OMPD_target;
9501 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009502 case OMPD_teams_distribute_parallel_for:
9503 case OMPD_teams_distribute_parallel_for_simd:
9504 case OMPD_teams:
9505 case OMPD_teams_distribute:
9506 case OMPD_teams_distribute_simd:
9507 // Do not capture thread_limit-clause expressions.
9508 break;
9509 case OMPD_distribute_parallel_for:
9510 case OMPD_distribute_parallel_for_simd:
9511 case OMPD_task:
9512 case OMPD_taskloop:
9513 case OMPD_taskloop_simd:
9514 case OMPD_target_data:
9515 case OMPD_target_enter_data:
9516 case OMPD_target_exit_data:
9517 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009518 case OMPD_cancel:
9519 case OMPD_parallel:
9520 case OMPD_parallel_sections:
9521 case OMPD_parallel_for:
9522 case OMPD_parallel_for_simd:
9523 case OMPD_target:
9524 case OMPD_target_simd:
9525 case OMPD_target_parallel:
9526 case OMPD_target_parallel_for:
9527 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009528 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009529 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009530 case OMPD_taskyield:
9531 case OMPD_barrier:
9532 case OMPD_taskwait:
9533 case OMPD_cancellation_point:
9534 case OMPD_flush:
9535 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009536 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009537 case OMPD_declare_simd:
9538 case OMPD_declare_target:
9539 case OMPD_end_declare_target:
9540 case OMPD_simd:
9541 case OMPD_for:
9542 case OMPD_for_simd:
9543 case OMPD_sections:
9544 case OMPD_section:
9545 case OMPD_single:
9546 case OMPD_master:
9547 case OMPD_critical:
9548 case OMPD_taskgroup:
9549 case OMPD_distribute:
9550 case OMPD_ordered:
9551 case OMPD_atomic:
9552 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009553 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009554 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
9555 case OMPD_unknown:
9556 llvm_unreachable("Unknown OpenMP directive");
9557 }
9558 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009559 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009560 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00009561 case OMPD_parallel_for:
9562 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009563 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00009564 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009565 case OMPD_teams_distribute_parallel_for:
9566 case OMPD_teams_distribute_parallel_for_simd:
9567 case OMPD_target_parallel_for:
9568 case OMPD_target_parallel_for_simd:
9569 case OMPD_target_teams_distribute_parallel_for:
9570 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009571 CaptureRegion = OMPD_parallel;
9572 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009573 case OMPD_for:
9574 case OMPD_for_simd:
9575 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009576 break;
9577 case OMPD_task:
9578 case OMPD_taskloop:
9579 case OMPD_taskloop_simd:
9580 case OMPD_target_data:
9581 case OMPD_target_enter_data:
9582 case OMPD_target_exit_data:
9583 case OMPD_target_update:
9584 case OMPD_teams:
9585 case OMPD_teams_distribute:
9586 case OMPD_teams_distribute_simd:
9587 case OMPD_target_teams_distribute:
9588 case OMPD_target_teams_distribute_simd:
9589 case OMPD_target:
9590 case OMPD_target_simd:
9591 case OMPD_target_parallel:
9592 case OMPD_cancel:
9593 case OMPD_parallel:
9594 case OMPD_parallel_sections:
9595 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009596 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009597 case OMPD_taskyield:
9598 case OMPD_barrier:
9599 case OMPD_taskwait:
9600 case OMPD_cancellation_point:
9601 case OMPD_flush:
9602 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009603 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009604 case OMPD_declare_simd:
9605 case OMPD_declare_target:
9606 case OMPD_end_declare_target:
9607 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009608 case OMPD_sections:
9609 case OMPD_section:
9610 case OMPD_single:
9611 case OMPD_master:
9612 case OMPD_critical:
9613 case OMPD_taskgroup:
9614 case OMPD_distribute:
9615 case OMPD_ordered:
9616 case OMPD_atomic:
9617 case OMPD_distribute_simd:
9618 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009619 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009620 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9621 case OMPD_unknown:
9622 llvm_unreachable("Unknown OpenMP directive");
9623 }
9624 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009625 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009626 switch (DKind) {
9627 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009628 case OMPD_teams_distribute_parallel_for_simd:
9629 case OMPD_teams_distribute:
9630 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009631 case OMPD_target_teams_distribute_parallel_for:
9632 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009633 case OMPD_target_teams_distribute:
9634 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009635 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009636 break;
9637 case OMPD_distribute_parallel_for:
9638 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009639 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009640 case OMPD_distribute_simd:
9641 // Do not capture thread_limit-clause expressions.
9642 break;
9643 case OMPD_parallel_for:
9644 case OMPD_parallel_for_simd:
9645 case OMPD_target_parallel_for_simd:
9646 case OMPD_target_parallel_for:
9647 case OMPD_task:
9648 case OMPD_taskloop:
9649 case OMPD_taskloop_simd:
9650 case OMPD_target_data:
9651 case OMPD_target_enter_data:
9652 case OMPD_target_exit_data:
9653 case OMPD_target_update:
9654 case OMPD_teams:
9655 case OMPD_target:
9656 case OMPD_target_simd:
9657 case OMPD_target_parallel:
9658 case OMPD_cancel:
9659 case OMPD_parallel:
9660 case OMPD_parallel_sections:
9661 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009662 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009663 case OMPD_taskyield:
9664 case OMPD_barrier:
9665 case OMPD_taskwait:
9666 case OMPD_cancellation_point:
9667 case OMPD_flush:
9668 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009669 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009670 case OMPD_declare_simd:
9671 case OMPD_declare_target:
9672 case OMPD_end_declare_target:
9673 case OMPD_simd:
9674 case OMPD_for:
9675 case OMPD_for_simd:
9676 case OMPD_sections:
9677 case OMPD_section:
9678 case OMPD_single:
9679 case OMPD_master:
9680 case OMPD_critical:
9681 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009682 case OMPD_ordered:
9683 case OMPD_atomic:
9684 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009685 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009686 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9687 case OMPD_unknown:
9688 llvm_unreachable("Unknown OpenMP directive");
9689 }
9690 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009691 case OMPC_device:
9692 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009693 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009694 case OMPD_target_enter_data:
9695 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009696 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009697 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009698 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009699 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009700 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009701 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009702 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009703 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009704 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009705 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009706 CaptureRegion = OMPD_task;
9707 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009708 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009709 // Do not capture device-clause expressions.
9710 break;
9711 case OMPD_teams_distribute_parallel_for:
9712 case OMPD_teams_distribute_parallel_for_simd:
9713 case OMPD_teams:
9714 case OMPD_teams_distribute:
9715 case OMPD_teams_distribute_simd:
9716 case OMPD_distribute_parallel_for:
9717 case OMPD_distribute_parallel_for_simd:
9718 case OMPD_task:
9719 case OMPD_taskloop:
9720 case OMPD_taskloop_simd:
9721 case OMPD_cancel:
9722 case OMPD_parallel:
9723 case OMPD_parallel_sections:
9724 case OMPD_parallel_for:
9725 case OMPD_parallel_for_simd:
9726 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009727 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009728 case OMPD_taskyield:
9729 case OMPD_barrier:
9730 case OMPD_taskwait:
9731 case OMPD_cancellation_point:
9732 case OMPD_flush:
9733 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009734 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009735 case OMPD_declare_simd:
9736 case OMPD_declare_target:
9737 case OMPD_end_declare_target:
9738 case OMPD_simd:
9739 case OMPD_for:
9740 case OMPD_for_simd:
9741 case OMPD_sections:
9742 case OMPD_section:
9743 case OMPD_single:
9744 case OMPD_master:
9745 case OMPD_critical:
9746 case OMPD_taskgroup:
9747 case OMPD_distribute:
9748 case OMPD_ordered:
9749 case OMPD_atomic:
9750 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009751 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009752 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9753 case OMPD_unknown:
9754 llvm_unreachable("Unknown OpenMP directive");
9755 }
9756 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009757 case OMPC_firstprivate:
9758 case OMPC_lastprivate:
9759 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009760 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009761 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009762 case OMPC_linear:
9763 case OMPC_default:
9764 case OMPC_proc_bind:
9765 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009766 case OMPC_safelen:
9767 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009768 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009769 case OMPC_collapse:
9770 case OMPC_private:
9771 case OMPC_shared:
9772 case OMPC_aligned:
9773 case OMPC_copyin:
9774 case OMPC_copyprivate:
9775 case OMPC_ordered:
9776 case OMPC_nowait:
9777 case OMPC_untied:
9778 case OMPC_mergeable:
9779 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009780 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009781 case OMPC_flush:
9782 case OMPC_read:
9783 case OMPC_write:
9784 case OMPC_update:
9785 case OMPC_capture:
9786 case OMPC_seq_cst:
9787 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009788 case OMPC_threads:
9789 case OMPC_simd:
9790 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009791 case OMPC_priority:
9792 case OMPC_grainsize:
9793 case OMPC_nogroup:
9794 case OMPC_num_tasks:
9795 case OMPC_hint:
9796 case OMPC_defaultmap:
9797 case OMPC_unknown:
9798 case OMPC_uniform:
9799 case OMPC_to:
9800 case OMPC_from:
9801 case OMPC_use_device_ptr:
9802 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009803 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009804 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009805 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009806 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009807 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009808 llvm_unreachable("Unexpected OpenMP clause.");
9809 }
9810 return CaptureRegion;
9811}
9812
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009813OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9814 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009815 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009816 SourceLocation NameModifierLoc,
9817 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009818 SourceLocation EndLoc) {
9819 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009820 Stmt *HelperValStmt = nullptr;
9821 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009822 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9823 !Condition->isInstantiationDependent() &&
9824 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009825 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009826 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009827 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009828
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009829 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009830
9831 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9832 CaptureRegion =
9833 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009834 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009835 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009836 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009837 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9838 HelperValStmt = buildPreInits(Context, Captures);
9839 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009840 }
9841
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009842 return new (Context)
9843 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9844 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009845}
9846
Alexey Bataev3778b602014-07-17 07:32:53 +00009847OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9848 SourceLocation StartLoc,
9849 SourceLocation LParenLoc,
9850 SourceLocation EndLoc) {
9851 Expr *ValExpr = Condition;
9852 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9853 !Condition->isInstantiationDependent() &&
9854 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009855 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009856 if (Val.isInvalid())
9857 return nullptr;
9858
Richard Smith03a4aa32016-06-23 19:02:52 +00009859 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009860 }
9861
9862 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9863}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009864ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9865 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009866 if (!Op)
9867 return ExprError();
9868
9869 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9870 public:
9871 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009872 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009873 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9874 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009875 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9876 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009877 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9878 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009879 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9880 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009881 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9882 QualType T,
9883 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009884 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9885 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009886 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9887 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009888 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009889 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009890 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009891 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9892 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009893 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9894 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009895 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9896 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009897 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009898 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009899 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009900 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9901 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009902 llvm_unreachable("conversion functions are permitted");
9903 }
9904 } ConvertDiagnoser;
9905 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9906}
9907
Alexey Bataeve3727102018-04-18 15:57:46 +00009908static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009909 OpenMPClauseKind CKind,
9910 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009911 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9912 !ValExpr->isInstantiationDependent()) {
9913 SourceLocation Loc = ValExpr->getExprLoc();
9914 ExprResult Value =
9915 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9916 if (Value.isInvalid())
9917 return false;
9918
9919 ValExpr = Value.get();
9920 // The expression must evaluate to a non-negative integer value.
9921 llvm::APSInt Result;
9922 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009923 Result.isSigned() &&
9924 !((!StrictlyPositive && Result.isNonNegative()) ||
9925 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009926 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009927 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9928 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009929 return false;
9930 }
9931 }
9932 return true;
9933}
9934
Alexey Bataev568a8332014-03-06 06:15:19 +00009935OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9936 SourceLocation StartLoc,
9937 SourceLocation LParenLoc,
9938 SourceLocation EndLoc) {
9939 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009940 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009941
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009942 // OpenMP [2.5, Restrictions]
9943 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009944 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009945 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009946 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009947
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009948 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009949 OpenMPDirectiveKind CaptureRegion =
9950 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9951 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009952 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009953 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009954 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9955 HelperValStmt = buildPreInits(Context, Captures);
9956 }
9957
9958 return new (Context) OMPNumThreadsClause(
9959 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009960}
9961
Alexey Bataev62c87d22014-03-21 04:51:18 +00009962ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009963 OpenMPClauseKind CKind,
9964 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009965 if (!E)
9966 return ExprError();
9967 if (E->isValueDependent() || E->isTypeDependent() ||
9968 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009969 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009970 llvm::APSInt Result;
9971 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9972 if (ICE.isInvalid())
9973 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009974 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9975 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009976 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009977 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9978 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009979 return ExprError();
9980 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009981 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9982 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9983 << E->getSourceRange();
9984 return ExprError();
9985 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009986 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9987 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009988 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009989 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009990 return ICE;
9991}
9992
9993OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9994 SourceLocation LParenLoc,
9995 SourceLocation EndLoc) {
9996 // OpenMP [2.8.1, simd construct, Description]
9997 // The parameter of the safelen clause must be a constant
9998 // positive integer expression.
9999 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
10000 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010001 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010002 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010003 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000010004}
10005
Alexey Bataev66b15b52015-08-21 11:14:16 +000010006OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
10007 SourceLocation LParenLoc,
10008 SourceLocation EndLoc) {
10009 // OpenMP [2.8.1, simd construct, Description]
10010 // The parameter of the simdlen clause must be a constant
10011 // positive integer expression.
10012 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
10013 if (Simdlen.isInvalid())
10014 return nullptr;
10015 return new (Context)
10016 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
10017}
10018
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010019/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010020static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
10021 DSAStackTy *Stack) {
10022 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010023 if (!OMPAllocatorHandleT.isNull())
10024 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010025 // Build the predefined allocator expressions.
10026 bool ErrorFound = false;
10027 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
10028 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
10029 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
10030 StringRef Allocator =
10031 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
10032 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
10033 auto *VD = dyn_cast_or_null<ValueDecl>(
10034 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
10035 if (!VD) {
10036 ErrorFound = true;
10037 break;
10038 }
10039 QualType AllocatorType =
10040 VD->getType().getNonLValueExprType(S.getASTContext());
10041 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
10042 if (!Res.isUsable()) {
10043 ErrorFound = true;
10044 break;
10045 }
10046 if (OMPAllocatorHandleT.isNull())
10047 OMPAllocatorHandleT = AllocatorType;
10048 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
10049 ErrorFound = true;
10050 break;
10051 }
10052 Stack->setAllocator(AllocatorKind, Res.get());
10053 }
10054 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010055 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
10056 return false;
10057 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000010058 OMPAllocatorHandleT.addConst();
10059 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010060 return true;
10061}
10062
10063OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
10064 SourceLocation LParenLoc,
10065 SourceLocation EndLoc) {
10066 // OpenMP [2.11.3, allocate Directive, Description]
10067 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010068 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010069 return nullptr;
10070
10071 ExprResult Allocator = DefaultLvalueConversion(A);
10072 if (Allocator.isInvalid())
10073 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010074 Allocator = PerformImplicitConversion(Allocator.get(),
10075 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010076 Sema::AA_Initializing,
10077 /*AllowExplicit=*/true);
10078 if (Allocator.isInvalid())
10079 return nullptr;
10080 return new (Context)
10081 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
10082}
10083
Alexander Musman64d33f12014-06-04 07:53:32 +000010084OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
10085 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000010086 SourceLocation LParenLoc,
10087 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000010088 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010089 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000010090 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010091 // The parameter of the collapse clause must be a constant
10092 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000010093 ExprResult NumForLoopsResult =
10094 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
10095 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000010096 return nullptr;
10097 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000010098 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000010099}
10100
Alexey Bataev10e775f2015-07-30 11:36:16 +000010101OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
10102 SourceLocation EndLoc,
10103 SourceLocation LParenLoc,
10104 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000010105 // OpenMP [2.7.1, loop construct, Description]
10106 // OpenMP [2.8.1, simd construct, Description]
10107 // OpenMP [2.9.6, distribute construct, Description]
10108 // The parameter of the ordered clause must be a constant
10109 // positive integer expression if any.
10110 if (NumForLoops && LParenLoc.isValid()) {
10111 ExprResult NumForLoopsResult =
10112 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
10113 if (NumForLoopsResult.isInvalid())
10114 return nullptr;
10115 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010116 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000010117 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010118 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000010119 auto *Clause = OMPOrderedClause::Create(
10120 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
10121 StartLoc, LParenLoc, EndLoc);
10122 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
10123 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010124}
10125
Alexey Bataeved09d242014-05-28 05:53:51 +000010126OMPClause *Sema::ActOnOpenMPSimpleClause(
10127 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
10128 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010129 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010130 switch (Kind) {
10131 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010132 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000010133 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
10134 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010135 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010136 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000010137 Res = ActOnOpenMPProcBindClause(
10138 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
10139 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010140 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010141 case OMPC_atomic_default_mem_order:
10142 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
10143 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
10144 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10145 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010146 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010147 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010148 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010149 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010150 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010151 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010152 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010153 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010154 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010155 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010156 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010157 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010158 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010159 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010160 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010161 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010162 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010163 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010164 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010165 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010166 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010167 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010168 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010169 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010170 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010171 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010172 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010173 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010174 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010175 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010176 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010177 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010178 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010179 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010180 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010181 case OMPC_map:
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:
Samuel Antao661c0902016-05-26 17:39:58 +000010193 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010194 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010195 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010196 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010197 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010198 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010199 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010200 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010201 llvm_unreachable("Clause is not allowed.");
10202 }
10203 return Res;
10204}
10205
Alexey Bataev6402bca2015-12-28 07:25:51 +000010206static std::string
10207getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
10208 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010209 SmallString<256> Buffer;
10210 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000010211 unsigned Bound = Last >= 2 ? Last - 2 : 0;
10212 unsigned Skipped = Exclude.size();
10213 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000010214 for (unsigned I = First; I < Last; ++I) {
10215 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000010216 --Skipped;
10217 continue;
10218 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010219 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
10220 if (I == Bound - Skipped)
10221 Out << " or ";
10222 else if (I != Bound + 1 - Skipped)
10223 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000010224 }
Alexey Bataeve3727102018-04-18 15:57:46 +000010225 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000010226}
10227
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010228OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
10229 SourceLocation KindKwLoc,
10230 SourceLocation StartLoc,
10231 SourceLocation LParenLoc,
10232 SourceLocation EndLoc) {
10233 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000010234 static_assert(OMPC_DEFAULT_unknown > 0,
10235 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010236 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010237 << getListOfPossibleValues(OMPC_default, /*First=*/0,
10238 /*Last=*/OMPC_DEFAULT_unknown)
10239 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010240 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010241 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000010242 switch (Kind) {
10243 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010244 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010245 break;
10246 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010247 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010248 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010249 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010250 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000010251 break;
10252 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010253 return new (Context)
10254 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010255}
10256
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010257OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
10258 SourceLocation KindKwLoc,
10259 SourceLocation StartLoc,
10260 SourceLocation LParenLoc,
10261 SourceLocation EndLoc) {
10262 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010263 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010264 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
10265 /*Last=*/OMPC_PROC_BIND_unknown)
10266 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010267 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010268 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010269 return new (Context)
10270 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010271}
10272
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010273OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
10274 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
10275 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
10276 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
10277 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10278 << getListOfPossibleValues(
10279 OMPC_atomic_default_mem_order, /*First=*/0,
10280 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
10281 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
10282 return nullptr;
10283 }
10284 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
10285 LParenLoc, EndLoc);
10286}
10287
Alexey Bataev56dafe82014-06-20 07:16:17 +000010288OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010289 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010290 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010291 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010292 SourceLocation EndLoc) {
10293 OMPClause *Res = nullptr;
10294 switch (Kind) {
10295 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010296 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
10297 assert(Argument.size() == NumberOfElements &&
10298 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010299 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010300 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
10301 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
10302 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
10303 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
10304 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010305 break;
10306 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010307 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
10308 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
10309 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
10310 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010311 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010312 case OMPC_dist_schedule:
10313 Res = ActOnOpenMPDistScheduleClause(
10314 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
10315 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
10316 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010317 case OMPC_defaultmap:
10318 enum { Modifier, DefaultmapKind };
10319 Res = ActOnOpenMPDefaultmapClause(
10320 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
10321 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000010322 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
10323 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010324 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000010325 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010326 case OMPC_num_threads:
10327 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010328 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010329 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010330 case OMPC_collapse:
10331 case OMPC_default:
10332 case OMPC_proc_bind:
10333 case OMPC_private:
10334 case OMPC_firstprivate:
10335 case OMPC_lastprivate:
10336 case OMPC_shared:
10337 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010338 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010339 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010340 case OMPC_linear:
10341 case OMPC_aligned:
10342 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010343 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010344 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010345 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010346 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010347 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010348 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010349 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010350 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010351 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010352 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010353 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010354 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010355 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010356 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010357 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010358 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010359 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010360 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010361 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010362 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010363 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010364 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010365 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010366 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010367 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010368 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010369 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010370 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010371 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010372 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010373 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010374 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010375 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010376 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010377 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010378 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010379 llvm_unreachable("Clause is not allowed.");
10380 }
10381 return Res;
10382}
10383
Alexey Bataev6402bca2015-12-28 07:25:51 +000010384static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
10385 OpenMPScheduleClauseModifier M2,
10386 SourceLocation M1Loc, SourceLocation M2Loc) {
10387 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
10388 SmallVector<unsigned, 2> Excluded;
10389 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
10390 Excluded.push_back(M2);
10391 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
10392 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
10393 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
10394 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
10395 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
10396 << getListOfPossibleValues(OMPC_schedule,
10397 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
10398 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10399 Excluded)
10400 << getOpenMPClauseName(OMPC_schedule);
10401 return true;
10402 }
10403 return false;
10404}
10405
Alexey Bataev56dafe82014-06-20 07:16:17 +000010406OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010407 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010408 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010409 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10410 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
10411 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
10412 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
10413 return nullptr;
10414 // OpenMP, 2.7.1, Loop Construct, Restrictions
10415 // Either the monotonic modifier or the nonmonotonic modifier can be specified
10416 // but not both.
10417 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
10418 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
10419 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
10420 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
10421 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
10422 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
10423 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
10424 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
10425 return nullptr;
10426 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010427 if (Kind == OMPC_SCHEDULE_unknown) {
10428 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000010429 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
10430 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
10431 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10432 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10433 Exclude);
10434 } else {
10435 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10436 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010437 }
10438 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10439 << Values << getOpenMPClauseName(OMPC_schedule);
10440 return nullptr;
10441 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000010442 // OpenMP, 2.7.1, Loop Construct, Restrictions
10443 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
10444 // schedule(guided).
10445 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
10446 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
10447 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
10448 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
10449 diag::err_omp_schedule_nonmonotonic_static);
10450 return nullptr;
10451 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010452 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010453 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000010454 if (ChunkSize) {
10455 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10456 !ChunkSize->isInstantiationDependent() &&
10457 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010458 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000010459 ExprResult Val =
10460 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10461 if (Val.isInvalid())
10462 return nullptr;
10463
10464 ValExpr = Val.get();
10465
10466 // OpenMP [2.7.1, Restrictions]
10467 // chunk_size must be a loop invariant integer expression with a positive
10468 // value.
10469 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000010470 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10471 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10472 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000010473 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000010474 return nullptr;
10475 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000010476 } else if (getOpenMPCaptureRegionForClause(
10477 DSAStack->getCurrentDirective(), OMPC_schedule) !=
10478 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010479 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010480 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010481 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000010482 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10483 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010484 }
10485 }
10486 }
10487
Alexey Bataev6402bca2015-12-28 07:25:51 +000010488 return new (Context)
10489 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000010490 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010491}
10492
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010493OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
10494 SourceLocation StartLoc,
10495 SourceLocation EndLoc) {
10496 OMPClause *Res = nullptr;
10497 switch (Kind) {
10498 case OMPC_ordered:
10499 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
10500 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000010501 case OMPC_nowait:
10502 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
10503 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010504 case OMPC_untied:
10505 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
10506 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010507 case OMPC_mergeable:
10508 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
10509 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010510 case OMPC_read:
10511 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
10512 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000010513 case OMPC_write:
10514 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
10515 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000010516 case OMPC_update:
10517 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
10518 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000010519 case OMPC_capture:
10520 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
10521 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010522 case OMPC_seq_cst:
10523 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
10524 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000010525 case OMPC_threads:
10526 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
10527 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010528 case OMPC_simd:
10529 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
10530 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000010531 case OMPC_nogroup:
10532 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
10533 break;
Kelvin Li1408f912018-09-26 04:28:39 +000010534 case OMPC_unified_address:
10535 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
10536 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000010537 case OMPC_unified_shared_memory:
10538 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10539 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010540 case OMPC_reverse_offload:
10541 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
10542 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010543 case OMPC_dynamic_allocators:
10544 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
10545 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010546 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010547 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010548 case OMPC_num_threads:
10549 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010550 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010551 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010552 case OMPC_collapse:
10553 case OMPC_schedule:
10554 case OMPC_private:
10555 case OMPC_firstprivate:
10556 case OMPC_lastprivate:
10557 case OMPC_shared:
10558 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010559 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010560 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010561 case OMPC_linear:
10562 case OMPC_aligned:
10563 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010564 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010565 case OMPC_default:
10566 case OMPC_proc_bind:
10567 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010568 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010569 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010570 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010571 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010572 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010573 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010574 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010575 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010576 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000010577 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010578 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010579 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010580 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010581 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010582 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010583 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010584 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010585 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010586 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010587 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010588 llvm_unreachable("Clause is not allowed.");
10589 }
10590 return Res;
10591}
10592
Alexey Bataev236070f2014-06-20 11:19:47 +000010593OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10594 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000010595 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000010596 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10597}
10598
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010599OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10600 SourceLocation EndLoc) {
10601 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10602}
10603
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010604OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10605 SourceLocation EndLoc) {
10606 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10607}
10608
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010609OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10610 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010611 return new (Context) OMPReadClause(StartLoc, EndLoc);
10612}
10613
Alexey Bataevdea47612014-07-23 07:46:59 +000010614OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10615 SourceLocation EndLoc) {
10616 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10617}
10618
Alexey Bataev67a4f222014-07-23 10:25:33 +000010619OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10620 SourceLocation EndLoc) {
10621 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10622}
10623
Alexey Bataev459dec02014-07-24 06:46:57 +000010624OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10625 SourceLocation EndLoc) {
10626 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10627}
10628
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010629OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10630 SourceLocation EndLoc) {
10631 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10632}
10633
Alexey Bataev346265e2015-09-25 10:37:12 +000010634OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10635 SourceLocation EndLoc) {
10636 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10637}
10638
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010639OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10640 SourceLocation EndLoc) {
10641 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10642}
10643
Alexey Bataevb825de12015-12-07 10:51:44 +000010644OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10645 SourceLocation EndLoc) {
10646 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10647}
10648
Kelvin Li1408f912018-09-26 04:28:39 +000010649OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10650 SourceLocation EndLoc) {
10651 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10652}
10653
Patrick Lyster4a370b92018-10-01 13:47:43 +000010654OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10655 SourceLocation EndLoc) {
10656 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10657}
10658
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010659OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10660 SourceLocation EndLoc) {
10661 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10662}
10663
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010664OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10665 SourceLocation EndLoc) {
10666 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10667}
10668
Alexey Bataevc5e02582014-06-16 07:08:35 +000010669OMPClause *Sema::ActOnOpenMPVarListClause(
10670 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010671 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10672 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10673 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010674 OpenMPLinearClauseKind LinKind,
10675 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010676 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10677 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10678 SourceLocation StartLoc = Locs.StartLoc;
10679 SourceLocation LParenLoc = Locs.LParenLoc;
10680 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010681 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010682 switch (Kind) {
10683 case OMPC_private:
10684 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10685 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010686 case OMPC_firstprivate:
10687 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10688 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010689 case OMPC_lastprivate:
10690 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10691 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010692 case OMPC_shared:
10693 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10694 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010695 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010696 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010697 EndLoc, ReductionOrMapperIdScopeSpec,
10698 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010699 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010700 case OMPC_task_reduction:
10701 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010702 EndLoc, ReductionOrMapperIdScopeSpec,
10703 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010704 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010705 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010706 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10707 EndLoc, ReductionOrMapperIdScopeSpec,
10708 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010709 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010710 case OMPC_linear:
10711 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010712 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010713 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010714 case OMPC_aligned:
10715 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10716 ColonLoc, EndLoc);
10717 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010718 case OMPC_copyin:
10719 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10720 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010721 case OMPC_copyprivate:
10722 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10723 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010724 case OMPC_flush:
10725 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10726 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010727 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010728 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010729 StartLoc, LParenLoc, EndLoc);
10730 break;
10731 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010732 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10733 ReductionOrMapperIdScopeSpec,
10734 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10735 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010736 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010737 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010738 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10739 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010740 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010741 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010742 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10743 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010744 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010745 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010746 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010747 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010748 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010749 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010750 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000010751 case OMPC_allocate:
10752 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10753 ColonLoc, EndLoc);
10754 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010755 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010756 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010757 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010758 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010759 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010760 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010761 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010762 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010763 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010764 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010765 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010766 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010767 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010768 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010769 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010770 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010771 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010772 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010773 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010774 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010775 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010776 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010777 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010778 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010779 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010780 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010781 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010782 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010783 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010784 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010785 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010786 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010787 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010788 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010789 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010790 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010791 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010792 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010793 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010794 llvm_unreachable("Clause is not allowed.");
10795 }
10796 return Res;
10797}
10798
Alexey Bataev90c228f2016-02-08 09:29:13 +000010799ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010800 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010801 ExprResult Res = BuildDeclRefExpr(
10802 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10803 if (!Res.isUsable())
10804 return ExprError();
10805 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10806 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10807 if (!Res.isUsable())
10808 return ExprError();
10809 }
10810 if (VK != VK_LValue && Res.get()->isGLValue()) {
10811 Res = DefaultLvalueConversion(Res.get());
10812 if (!Res.isUsable())
10813 return ExprError();
10814 }
10815 return Res;
10816}
10817
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010818OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10819 SourceLocation StartLoc,
10820 SourceLocation LParenLoc,
10821 SourceLocation EndLoc) {
10822 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010823 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010824 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010825 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010826 SourceLocation ELoc;
10827 SourceRange ERange;
10828 Expr *SimpleRefExpr = RefExpr;
10829 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010830 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010831 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010832 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010833 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010834 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010835 ValueDecl *D = Res.first;
10836 if (!D)
10837 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010838
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010839 QualType Type = D->getType();
10840 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010841
10842 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10843 // A variable that appears in a private clause must not have an incomplete
10844 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010845 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010846 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010847 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010848
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010849 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10850 // A variable that is privatized must not have a const-qualified type
10851 // unless it is of class type with a mutable member. This restriction does
10852 // not apply to the firstprivate clause.
10853 //
10854 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10855 // A variable that appears in a private clause must not have a
10856 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010857 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010858 continue;
10859
Alexey Bataev758e55e2013-09-06 18:03:48 +000010860 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10861 // in a Construct]
10862 // Variables with the predetermined data-sharing attributes may not be
10863 // listed in data-sharing attributes clauses, except for the cases
10864 // listed below. For these exceptions only, listing a predetermined
10865 // variable in a data-sharing attribute clause is allowed and overrides
10866 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010867 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010868 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010869 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10870 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010871 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010872 continue;
10873 }
10874
Alexey Bataeve3727102018-04-18 15:57:46 +000010875 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010876 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010877 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010878 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010879 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10880 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010881 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010882 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010883 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010884 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010885 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010886 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010887 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010888 continue;
10889 }
10890
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010891 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10892 // A list item cannot appear in both a map clause and a data-sharing
10893 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010894 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010895 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010896 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010897 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010898 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10899 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10900 ConflictKind = WhereFoundClauseKind;
10901 return true;
10902 })) {
10903 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010904 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010905 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010906 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010907 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010908 continue;
10909 }
10910 }
10911
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010912 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10913 // A variable of class type (or array thereof) that appears in a private
10914 // clause requires an accessible, unambiguous default constructor for the
10915 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010916 // Generate helper private variable and initialize it with the default
10917 // value. The address of the original variable is replaced by the address of
10918 // the new private variable in CodeGen. This new variable is not added to
10919 // IdResolver, so the code in the OpenMP region uses original variable for
10920 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010921 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010922 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010923 buildVarDecl(*this, ELoc, Type, D->getName(),
10924 D->hasAttrs() ? &D->getAttrs() : nullptr,
10925 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010926 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010927 if (VDPrivate->isInvalidDecl())
10928 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010929 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010930 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010931
Alexey Bataev90c228f2016-02-08 09:29:13 +000010932 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010933 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010934 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010935 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010936 Vars.push_back((VD || CurContext->isDependentContext())
10937 ? RefExpr->IgnoreParens()
10938 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010939 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010940 }
10941
Alexey Bataeved09d242014-05-28 05:53:51 +000010942 if (Vars.empty())
10943 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010944
Alexey Bataev03b340a2014-10-21 03:16:40 +000010945 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10946 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010947}
10948
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010949namespace {
10950class DiagsUninitializedSeveretyRAII {
10951private:
10952 DiagnosticsEngine &Diags;
10953 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010954 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010955
10956public:
10957 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10958 bool IsIgnored)
10959 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10960 if (!IsIgnored) {
10961 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10962 /*Map*/ diag::Severity::Ignored, Loc);
10963 }
10964 }
10965 ~DiagsUninitializedSeveretyRAII() {
10966 if (!IsIgnored)
10967 Diags.popMappings(SavedLoc);
10968 }
10969};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010970}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010971
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010972OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10973 SourceLocation StartLoc,
10974 SourceLocation LParenLoc,
10975 SourceLocation EndLoc) {
10976 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010977 SmallVector<Expr *, 8> PrivateCopies;
10978 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010979 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010980 bool IsImplicitClause =
10981 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010982 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010983
Alexey Bataeve3727102018-04-18 15:57:46 +000010984 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010985 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010986 SourceLocation ELoc;
10987 SourceRange ERange;
10988 Expr *SimpleRefExpr = RefExpr;
10989 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010990 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010991 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010992 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010993 PrivateCopies.push_back(nullptr);
10994 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010995 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010996 ValueDecl *D = Res.first;
10997 if (!D)
10998 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010999
Alexey Bataev60da77e2016-02-29 05:54:20 +000011000 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011001 QualType Type = D->getType();
11002 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011003
11004 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11005 // A variable that appears in a private clause must not have an incomplete
11006 // type or a reference type.
11007 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000011008 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011009 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011010 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011011
11012 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
11013 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000011014 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011015 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011016 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011017
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011018 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000011019 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011020 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011021 DSAStackTy::DSAVarData DVar =
11022 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000011023 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011024 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011025 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011026 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
11027 // A list item that specifies a given variable may not appear in more
11028 // than one clause on the same directive, except that a variable may be
11029 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011030 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11031 // A list item may appear in a firstprivate or lastprivate clause but not
11032 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011033 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011034 (isOpenMPDistributeDirective(CurrDir) ||
11035 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011036 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011037 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011038 << getOpenMPClauseName(DVar.CKind)
11039 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011040 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011041 continue;
11042 }
11043
11044 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11045 // in a Construct]
11046 // Variables with the predetermined data-sharing attributes may not be
11047 // listed in data-sharing attributes clauses, except for the cases
11048 // listed below. For these exceptions only, listing a predetermined
11049 // variable in a data-sharing attribute clause is allowed and overrides
11050 // the variable's predetermined data-sharing attributes.
11051 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11052 // in a Construct, C/C++, p.2]
11053 // Variables with const-qualified type having no mutable member may be
11054 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000011055 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011056 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
11057 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011058 << getOpenMPClauseName(DVar.CKind)
11059 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011060 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011061 continue;
11062 }
11063
11064 // OpenMP [2.9.3.4, Restrictions, p.2]
11065 // A list item that is private within a parallel region must not appear
11066 // in a firstprivate clause on a worksharing construct if any of the
11067 // worksharing regions arising from the worksharing construct ever bind
11068 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011069 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11070 // A list item that is private within a teams region must not appear in a
11071 // firstprivate clause on a distribute construct if any of the distribute
11072 // regions arising from the distribute construct ever bind to any of the
11073 // teams regions arising from the teams construct.
11074 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11075 // A list item that appears in a reduction clause of a teams construct
11076 // must not appear in a firstprivate clause on a distribute construct if
11077 // any of the distribute regions arising from the distribute construct
11078 // ever bind to any of the teams regions arising from the teams construct.
11079 if ((isOpenMPWorksharingDirective(CurrDir) ||
11080 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011081 !isOpenMPParallelDirective(CurrDir) &&
11082 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011083 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011084 if (DVar.CKind != OMPC_shared &&
11085 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011086 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011087 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000011088 Diag(ELoc, diag::err_omp_required_access)
11089 << getOpenMPClauseName(OMPC_firstprivate)
11090 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011091 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011092 continue;
11093 }
11094 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011095 // OpenMP [2.9.3.4, Restrictions, p.3]
11096 // A list item that appears in a reduction clause of a parallel construct
11097 // must not appear in a firstprivate clause on a worksharing or task
11098 // construct if any of the worksharing or task regions arising from the
11099 // worksharing or task construct ever bind to any of the parallel regions
11100 // arising from the parallel construct.
11101 // OpenMP [2.9.3.4, Restrictions, p.4]
11102 // A list item that appears in a reduction clause in worksharing
11103 // construct must not appear in a firstprivate clause in a task construct
11104 // encountered during execution of any of the worksharing regions arising
11105 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000011106 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011107 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011108 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
11109 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011110 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011111 isOpenMPWorksharingDirective(K) ||
11112 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011113 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011114 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011115 if (DVar.CKind == OMPC_reduction &&
11116 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011117 isOpenMPWorksharingDirective(DVar.DKind) ||
11118 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011119 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
11120 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000011121 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011122 continue;
11123 }
11124 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000011125
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011126 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11127 // A list item cannot appear in both a map clause and a data-sharing
11128 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000011129 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000011130 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011131 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011132 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000011133 [&ConflictKind](
11134 OMPClauseMappableExprCommon::MappableExprComponentListRef,
11135 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000011136 ConflictKind = WhereFoundClauseKind;
11137 return true;
11138 })) {
11139 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011140 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000011141 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011142 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000011143 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011144 continue;
11145 }
11146 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011147 }
11148
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011149 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011150 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000011151 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011152 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11153 << getOpenMPClauseName(OMPC_firstprivate) << Type
11154 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11155 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011156 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011157 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011158 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011159 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000011160 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011161 continue;
11162 }
11163
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011164 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011165 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011166 buildVarDecl(*this, ELoc, Type, D->getName(),
11167 D->hasAttrs() ? &D->getAttrs() : nullptr,
11168 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011169 // Generate helper private variable and initialize it with the value of the
11170 // original variable. The address of the original variable is replaced by
11171 // the address of the new private variable in the CodeGen. This new variable
11172 // is not added to IdResolver, so the code in the OpenMP region uses
11173 // original variable for proper diagnostics and variable capturing.
11174 Expr *VDInitRefExpr = nullptr;
11175 // For arrays generate initializer for single element and replace it by the
11176 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011177 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011178 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011179 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011180 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011181 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011182 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011183 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
11184 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000011185 InitializedEntity Entity =
11186 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011187 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
11188
11189 InitializationSequence InitSeq(*this, Entity, Kind, Init);
11190 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
11191 if (Result.isInvalid())
11192 VDPrivate->setInvalidDecl();
11193 else
11194 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011195 // Remove temp variable declaration.
11196 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011197 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000011198 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
11199 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000011200 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
11201 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000011202 AddInitializerToDecl(VDPrivate,
11203 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011204 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011205 }
11206 if (VDPrivate->isInvalidDecl()) {
11207 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011208 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011209 diag::note_omp_task_predetermined_firstprivate_here);
11210 }
11211 continue;
11212 }
11213 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011214 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000011215 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
11216 RefExpr->getExprLoc());
11217 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011218 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011219 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011220 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011221 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011222 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011223 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011224 ExprCaptures.push_back(Ref->getDecl());
11225 }
Alexey Bataev417089f2016-02-17 13:19:37 +000011226 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011227 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011228 Vars.push_back((VD || CurContext->isDependentContext())
11229 ? RefExpr->IgnoreParens()
11230 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011231 PrivateCopies.push_back(VDPrivateRefExpr);
11232 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011233 }
11234
Alexey Bataeved09d242014-05-28 05:53:51 +000011235 if (Vars.empty())
11236 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011237
11238 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011239 Vars, PrivateCopies, Inits,
11240 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011241}
11242
Alexander Musman1bb328c2014-06-04 13:06:39 +000011243OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
11244 SourceLocation StartLoc,
11245 SourceLocation LParenLoc,
11246 SourceLocation EndLoc) {
11247 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000011248 SmallVector<Expr *, 8> SrcExprs;
11249 SmallVector<Expr *, 8> DstExprs;
11250 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000011251 SmallVector<Decl *, 4> ExprCaptures;
11252 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000011253 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011254 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011255 SourceLocation ELoc;
11256 SourceRange ERange;
11257 Expr *SimpleRefExpr = RefExpr;
11258 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000011259 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011260 // It will be analyzed later.
11261 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011262 SrcExprs.push_back(nullptr);
11263 DstExprs.push_back(nullptr);
11264 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011265 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011266 ValueDecl *D = Res.first;
11267 if (!D)
11268 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011269
Alexey Bataev74caaf22016-02-20 04:09:36 +000011270 QualType Type = D->getType();
11271 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011272
11273 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
11274 // A variable that appears in a lastprivate clause must not have an
11275 // incomplete type or a reference type.
11276 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000011277 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000011278 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011279 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011280
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011281 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11282 // A variable that is privatized must not have a const-qualified type
11283 // unless it is of class type with a mutable member. This restriction does
11284 // not apply to the firstprivate clause.
11285 //
11286 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
11287 // A variable that appears in a lastprivate clause must not have a
11288 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011289 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011290 continue;
11291
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011292 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011293 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11294 // in a Construct]
11295 // Variables with the predetermined data-sharing attributes may not be
11296 // listed in data-sharing attributes clauses, except for the cases
11297 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011298 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11299 // A list item may appear in a firstprivate or lastprivate clause but not
11300 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000011301 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011302 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011303 (isOpenMPDistributeDirective(CurrDir) ||
11304 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000011305 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
11306 Diag(ELoc, diag::err_omp_wrong_dsa)
11307 << getOpenMPClauseName(DVar.CKind)
11308 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011309 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011310 continue;
11311 }
11312
Alexey Bataevf29276e2014-06-18 04:14:57 +000011313 // OpenMP [2.14.3.5, Restrictions, p.2]
11314 // A list item that is private within a parallel region, or that appears in
11315 // the reduction clause of a parallel construct, must not appear in a
11316 // lastprivate clause on a worksharing construct if any of the corresponding
11317 // worksharing regions ever binds to any of the corresponding parallel
11318 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000011319 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000011320 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011321 !isOpenMPParallelDirective(CurrDir) &&
11322 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000011323 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011324 if (DVar.CKind != OMPC_shared) {
11325 Diag(ELoc, diag::err_omp_required_access)
11326 << getOpenMPClauseName(OMPC_lastprivate)
11327 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011328 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011329 continue;
11330 }
11331 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011332
Alexander Musman1bb328c2014-06-04 13:06:39 +000011333 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000011334 // A variable of class type (or array thereof) that appears in a
11335 // lastprivate clause requires an accessible, unambiguous default
11336 // constructor for the class type, unless the list item is also specified
11337 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000011338 // A variable of class type (or array thereof) that appears in a
11339 // lastprivate clause requires an accessible, unambiguous copy assignment
11340 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000011341 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011342 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
11343 Type.getUnqualifiedType(), ".lastprivate.src",
11344 D->hasAttrs() ? &D->getAttrs() : nullptr);
11345 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000011346 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011347 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011348 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000011349 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011350 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000011351 // For arrays generate assignment operation for single element and replace
11352 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000011353 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
11354 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011355 if (AssignmentOp.isInvalid())
11356 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011357 AssignmentOp =
11358 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000011359 if (AssignmentOp.isInvalid())
11360 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011361
Alexey Bataev74caaf22016-02-20 04:09:36 +000011362 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011363 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011364 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011365 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011366 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011367 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011368 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011369 ExprCaptures.push_back(Ref->getDecl());
11370 }
11371 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000011372 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011373 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011374 ExprResult RefRes = DefaultLvalueConversion(Ref);
11375 if (!RefRes.isUsable())
11376 continue;
11377 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011378 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11379 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011380 if (!PostUpdateRes.isUsable())
11381 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011382 ExprPostUpdates.push_back(
11383 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011384 }
11385 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011386 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011387 Vars.push_back((VD || CurContext->isDependentContext())
11388 ? RefExpr->IgnoreParens()
11389 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000011390 SrcExprs.push_back(PseudoSrcExpr);
11391 DstExprs.push_back(PseudoDstExpr);
11392 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000011393 }
11394
11395 if (Vars.empty())
11396 return nullptr;
11397
11398 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000011399 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011400 buildPreInits(Context, ExprCaptures),
11401 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000011402}
11403
Alexey Bataev758e55e2013-09-06 18:03:48 +000011404OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11405 SourceLocation StartLoc,
11406 SourceLocation LParenLoc,
11407 SourceLocation EndLoc) {
11408 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011409 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011410 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011411 SourceLocation ELoc;
11412 SourceRange ERange;
11413 Expr *SimpleRefExpr = RefExpr;
11414 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011415 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000011416 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011417 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011418 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011419 ValueDecl *D = Res.first;
11420 if (!D)
11421 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011422
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011423 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011424 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11425 // in a Construct]
11426 // Variables with the predetermined data-sharing attributes may not be
11427 // listed in data-sharing attributes clauses, except for the cases
11428 // listed below. For these exceptions only, listing a predetermined
11429 // variable in a data-sharing attribute clause is allowed and overrides
11430 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011431 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000011432 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
11433 DVar.RefExpr) {
11434 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11435 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011436 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011437 continue;
11438 }
11439
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011440 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011441 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000011442 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011443 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011444 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
11445 ? RefExpr->IgnoreParens()
11446 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011447 }
11448
Alexey Bataeved09d242014-05-28 05:53:51 +000011449 if (Vars.empty())
11450 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011451
11452 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
11453}
11454
Alexey Bataevc5e02582014-06-16 07:08:35 +000011455namespace {
11456class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
11457 DSAStackTy *Stack;
11458
11459public:
11460 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011461 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
11462 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011463 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
11464 return false;
11465 if (DVar.CKind != OMPC_unknown)
11466 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011467 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011468 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011469 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011470 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011471 }
11472 return false;
11473 }
11474 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011475 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011476 if (Child && Visit(Child))
11477 return true;
11478 }
11479 return false;
11480 }
Alexey Bataev23b69422014-06-18 07:08:49 +000011481 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011482};
Alexey Bataev23b69422014-06-18 07:08:49 +000011483} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000011484
Alexey Bataev60da77e2016-02-29 05:54:20 +000011485namespace {
11486// Transform MemberExpression for specified FieldDecl of current class to
11487// DeclRefExpr to specified OMPCapturedExprDecl.
11488class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
11489 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000011490 ValueDecl *Field = nullptr;
11491 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011492
11493public:
11494 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
11495 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
11496
11497 ExprResult TransformMemberExpr(MemberExpr *E) {
11498 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
11499 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000011500 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011501 return CapturedExpr;
11502 }
11503 return BaseTransform::TransformMemberExpr(E);
11504 }
11505 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
11506};
11507} // namespace
11508
Alexey Bataev97d18bf2018-04-11 19:21:00 +000011509template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000011510static T filterLookupForUDReductionAndMapper(
11511 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011512 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011513 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011514 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011515 return Res;
11516 }
11517 }
11518 return T();
11519}
11520
Alexey Bataev43b90b72018-09-12 16:31:59 +000011521static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
11522 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
11523
11524 for (auto RD : D->redecls()) {
11525 // Don't bother with extra checks if we already know this one isn't visible.
11526 if (RD == D)
11527 continue;
11528
11529 auto ND = cast<NamedDecl>(RD);
11530 if (LookupResult::isVisible(SemaRef, ND))
11531 return ND;
11532 }
11533
11534 return nullptr;
11535}
11536
11537static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000011538argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000011539 SourceLocation Loc, QualType Ty,
11540 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11541 // Find all of the associated namespaces and classes based on the
11542 // arguments we have.
11543 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11544 Sema::AssociatedClassSet AssociatedClasses;
11545 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11546 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11547 AssociatedClasses);
11548
11549 // C++ [basic.lookup.argdep]p3:
11550 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11551 // and let Y be the lookup set produced by argument dependent
11552 // lookup (defined as follows). If X contains [...] then Y is
11553 // empty. Otherwise Y is the set of declarations found in the
11554 // namespaces associated with the argument types as described
11555 // below. The set of declarations found by the lookup of the name
11556 // is the union of X and Y.
11557 //
11558 // Here, we compute Y and add its members to the overloaded
11559 // candidate set.
11560 for (auto *NS : AssociatedNamespaces) {
11561 // When considering an associated namespace, the lookup is the
11562 // same as the lookup performed when the associated namespace is
11563 // used as a qualifier (3.4.3.2) except that:
11564 //
11565 // -- Any using-directives in the associated namespace are
11566 // ignored.
11567 //
11568 // -- Any namespace-scope friend functions declared in
11569 // associated classes are visible within their respective
11570 // namespaces even if they are not visible during an ordinary
11571 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011572 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011573 for (auto *D : R) {
11574 auto *Underlying = D;
11575 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11576 Underlying = USD->getTargetDecl();
11577
Michael Kruse4304e9d2019-02-19 16:38:20 +000011578 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11579 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011580 continue;
11581
11582 if (!SemaRef.isVisible(D)) {
11583 D = findAcceptableDecl(SemaRef, D);
11584 if (!D)
11585 continue;
11586 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11587 Underlying = USD->getTargetDecl();
11588 }
11589 Lookups.emplace_back();
11590 Lookups.back().addDecl(Underlying);
11591 }
11592 }
11593}
11594
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011595static ExprResult
11596buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11597 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11598 const DeclarationNameInfo &ReductionId, QualType Ty,
11599 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11600 if (ReductionIdScopeSpec.isInvalid())
11601 return ExprError();
11602 SmallVector<UnresolvedSet<8>, 4> Lookups;
11603 if (S) {
11604 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11605 Lookup.suppressDiagnostics();
11606 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011607 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011608 do {
11609 S = S->getParent();
11610 } while (S && !S->isDeclScope(D));
11611 if (S)
11612 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011613 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011614 Lookups.back().append(Lookup.begin(), Lookup.end());
11615 Lookup.clear();
11616 }
11617 } else if (auto *ULE =
11618 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11619 Lookups.push_back(UnresolvedSet<8>());
11620 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011621 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011622 if (D == PrevD)
11623 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011624 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011625 Lookups.back().addDecl(DRD);
11626 PrevD = D;
11627 }
11628 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011629 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11630 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011631 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011632 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011633 return !D->isInvalidDecl() &&
11634 (D->getType()->isDependentType() ||
11635 D->getType()->isInstantiationDependentType() ||
11636 D->getType()->containsUnexpandedParameterPack());
11637 })) {
11638 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011639 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011640 if (Set.empty())
11641 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011642 ResSet.append(Set.begin(), Set.end());
11643 // The last item marks the end of all declarations at the specified scope.
11644 ResSet.addDecl(Set[Set.size() - 1]);
11645 }
11646 return UnresolvedLookupExpr::Create(
11647 SemaRef.Context, /*NamingClass=*/nullptr,
11648 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11649 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11650 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011651 // Lookup inside the classes.
11652 // C++ [over.match.oper]p3:
11653 // For a unary operator @ with an operand of a type whose
11654 // cv-unqualified version is T1, and for a binary operator @ with
11655 // a left operand of a type whose cv-unqualified version is T1 and
11656 // a right operand of a type whose cv-unqualified version is T2,
11657 // three sets of candidate functions, designated member
11658 // candidates, non-member candidates and built-in candidates, are
11659 // constructed as follows:
11660 // -- If T1 is a complete class type or a class currently being
11661 // defined, the set of member candidates is the result of the
11662 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11663 // the set of member candidates is empty.
11664 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11665 Lookup.suppressDiagnostics();
11666 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11667 // Complete the type if it can be completed.
11668 // If the type is neither complete nor being defined, bail out now.
11669 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11670 TyRec->getDecl()->getDefinition()) {
11671 Lookup.clear();
11672 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11673 if (Lookup.empty()) {
11674 Lookups.emplace_back();
11675 Lookups.back().append(Lookup.begin(), Lookup.end());
11676 }
11677 }
11678 }
11679 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000011680 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000011681 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000011682 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11683 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11684 if (!D->isInvalidDecl() &&
11685 SemaRef.Context.hasSameType(D->getType(), Ty))
11686 return D;
11687 return nullptr;
11688 }))
11689 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11690 VK_LValue, Loc);
11691 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000011692 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11693 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11694 if (!D->isInvalidDecl() &&
11695 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11696 !Ty.isMoreQualifiedThan(D->getType()))
11697 return D;
11698 return nullptr;
11699 })) {
11700 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11701 /*DetectVirtual=*/false);
11702 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11703 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11704 VD->getType().getUnqualifiedType()))) {
11705 if (SemaRef.CheckBaseClassAccess(
11706 Loc, VD->getType(), Ty, Paths.front(),
11707 /*DiagID=*/0) != Sema::AR_inaccessible) {
11708 SemaRef.BuildBasePathArray(Paths, BasePath);
11709 return SemaRef.BuildDeclRefExpr(
11710 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11711 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011712 }
11713 }
11714 }
11715 }
11716 if (ReductionIdScopeSpec.isSet()) {
11717 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11718 return ExprError();
11719 }
11720 return ExprEmpty();
11721}
11722
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011723namespace {
11724/// Data for the reduction-based clauses.
11725struct ReductionData {
11726 /// List of original reduction items.
11727 SmallVector<Expr *, 8> Vars;
11728 /// List of private copies of the reduction items.
11729 SmallVector<Expr *, 8> Privates;
11730 /// LHS expressions for the reduction_op expressions.
11731 SmallVector<Expr *, 8> LHSs;
11732 /// RHS expressions for the reduction_op expressions.
11733 SmallVector<Expr *, 8> RHSs;
11734 /// Reduction operation expression.
11735 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011736 /// Taskgroup descriptors for the corresponding reduction items in
11737 /// in_reduction clauses.
11738 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011739 /// List of captures for clause.
11740 SmallVector<Decl *, 4> ExprCaptures;
11741 /// List of postupdate expressions.
11742 SmallVector<Expr *, 4> ExprPostUpdates;
11743 ReductionData() = delete;
11744 /// Reserves required memory for the reduction data.
11745 ReductionData(unsigned Size) {
11746 Vars.reserve(Size);
11747 Privates.reserve(Size);
11748 LHSs.reserve(Size);
11749 RHSs.reserve(Size);
11750 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011751 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011752 ExprCaptures.reserve(Size);
11753 ExprPostUpdates.reserve(Size);
11754 }
11755 /// Stores reduction item and reduction operation only (required for dependent
11756 /// reduction item).
11757 void push(Expr *Item, Expr *ReductionOp) {
11758 Vars.emplace_back(Item);
11759 Privates.emplace_back(nullptr);
11760 LHSs.emplace_back(nullptr);
11761 RHSs.emplace_back(nullptr);
11762 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011763 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011764 }
11765 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011766 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11767 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011768 Vars.emplace_back(Item);
11769 Privates.emplace_back(Private);
11770 LHSs.emplace_back(LHS);
11771 RHSs.emplace_back(RHS);
11772 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011773 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011774 }
11775};
11776} // namespace
11777
Alexey Bataeve3727102018-04-18 15:57:46 +000011778static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011779 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11780 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11781 const Expr *Length = OASE->getLength();
11782 if (Length == nullptr) {
11783 // For array sections of the form [1:] or [:], we would need to analyze
11784 // the lower bound...
11785 if (OASE->getColonLoc().isValid())
11786 return false;
11787
11788 // This is an array subscript which has implicit length 1!
11789 SingleElement = true;
11790 ArraySizes.push_back(llvm::APSInt::get(1));
11791 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011792 Expr::EvalResult Result;
11793 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011794 return false;
11795
Fangrui Song407659a2018-11-30 23:41:18 +000011796 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011797 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11798 ArraySizes.push_back(ConstantLengthValue);
11799 }
11800
11801 // Get the base of this array section and walk up from there.
11802 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11803
11804 // We require length = 1 for all array sections except the right-most to
11805 // guarantee that the memory region is contiguous and has no holes in it.
11806 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11807 Length = TempOASE->getLength();
11808 if (Length == nullptr) {
11809 // For array sections of the form [1:] or [:], we would need to analyze
11810 // the lower bound...
11811 if (OASE->getColonLoc().isValid())
11812 return false;
11813
11814 // This is an array subscript which has implicit length 1!
11815 ArraySizes.push_back(llvm::APSInt::get(1));
11816 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011817 Expr::EvalResult Result;
11818 if (!Length->EvaluateAsInt(Result, Context))
11819 return false;
11820
11821 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11822 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011823 return false;
11824
11825 ArraySizes.push_back(ConstantLengthValue);
11826 }
11827 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11828 }
11829
11830 // If we have a single element, we don't need to add the implicit lengths.
11831 if (!SingleElement) {
11832 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11833 // Has implicit length 1!
11834 ArraySizes.push_back(llvm::APSInt::get(1));
11835 Base = TempASE->getBase()->IgnoreParenImpCasts();
11836 }
11837 }
11838
11839 // This array section can be privatized as a single value or as a constant
11840 // sized array.
11841 return true;
11842}
11843
Alexey Bataeve3727102018-04-18 15:57:46 +000011844static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011845 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11846 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11847 SourceLocation ColonLoc, SourceLocation EndLoc,
11848 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011849 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011850 DeclarationName DN = ReductionId.getName();
11851 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011852 BinaryOperatorKind BOK = BO_Comma;
11853
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011854 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011855 // OpenMP [2.14.3.6, reduction clause]
11856 // C
11857 // reduction-identifier is either an identifier or one of the following
11858 // operators: +, -, *, &, |, ^, && and ||
11859 // C++
11860 // reduction-identifier is either an id-expression or one of the following
11861 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011862 switch (OOK) {
11863 case OO_Plus:
11864 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011865 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011866 break;
11867 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011868 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011869 break;
11870 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011871 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011872 break;
11873 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011874 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011875 break;
11876 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011877 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011878 break;
11879 case OO_AmpAmp:
11880 BOK = BO_LAnd;
11881 break;
11882 case OO_PipePipe:
11883 BOK = BO_LOr;
11884 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011885 case OO_New:
11886 case OO_Delete:
11887 case OO_Array_New:
11888 case OO_Array_Delete:
11889 case OO_Slash:
11890 case OO_Percent:
11891 case OO_Tilde:
11892 case OO_Exclaim:
11893 case OO_Equal:
11894 case OO_Less:
11895 case OO_Greater:
11896 case OO_LessEqual:
11897 case OO_GreaterEqual:
11898 case OO_PlusEqual:
11899 case OO_MinusEqual:
11900 case OO_StarEqual:
11901 case OO_SlashEqual:
11902 case OO_PercentEqual:
11903 case OO_CaretEqual:
11904 case OO_AmpEqual:
11905 case OO_PipeEqual:
11906 case OO_LessLess:
11907 case OO_GreaterGreater:
11908 case OO_LessLessEqual:
11909 case OO_GreaterGreaterEqual:
11910 case OO_EqualEqual:
11911 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011912 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011913 case OO_PlusPlus:
11914 case OO_MinusMinus:
11915 case OO_Comma:
11916 case OO_ArrowStar:
11917 case OO_Arrow:
11918 case OO_Call:
11919 case OO_Subscript:
11920 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011921 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011922 case NUM_OVERLOADED_OPERATORS:
11923 llvm_unreachable("Unexpected reduction identifier");
11924 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011925 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011926 if (II->isStr("max"))
11927 BOK = BO_GT;
11928 else if (II->isStr("min"))
11929 BOK = BO_LT;
11930 }
11931 break;
11932 }
11933 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011934 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011935 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011936 else
11937 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011938 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011939
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011940 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11941 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011942 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011943 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011944 // OpenMP [2.1, C/C++]
11945 // A list item is a variable or array section, subject to the restrictions
11946 // specified in Section 2.4 on page 42 and in each of the sections
11947 // describing clauses and directives for which a list appears.
11948 // OpenMP [2.14.3.3, Restrictions, p.1]
11949 // A variable that is part of another variable (as an array or
11950 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011951 if (!FirstIter && IR != ER)
11952 ++IR;
11953 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011954 SourceLocation ELoc;
11955 SourceRange ERange;
11956 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011957 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011958 /*AllowArraySection=*/true);
11959 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011960 // Try to find 'declare reduction' corresponding construct before using
11961 // builtin/overloaded operators.
11962 QualType Type = Context.DependentTy;
11963 CXXCastPath BasePath;
11964 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011965 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011966 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011967 Expr *ReductionOp = nullptr;
11968 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011969 (DeclareReductionRef.isUnset() ||
11970 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011971 ReductionOp = DeclareReductionRef.get();
11972 // It will be analyzed later.
11973 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011974 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011975 ValueDecl *D = Res.first;
11976 if (!D)
11977 continue;
11978
Alexey Bataev88202be2017-07-27 13:20:36 +000011979 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011980 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011981 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11982 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011983 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011984 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011985 } else if (OASE) {
11986 QualType BaseType =
11987 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11988 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011989 Type = ATy->getElementType();
11990 else
11991 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011992 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011993 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011994 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011995 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011996 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011997
Alexey Bataevc5e02582014-06-16 07:08:35 +000011998 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11999 // A variable that appears in a private clause must not have an incomplete
12000 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000012001 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012002 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012003 continue;
12004 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000012005 // A list item that appears in a reduction clause must not be
12006 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012007 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
12008 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012009 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000012010
12011 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012012 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
12013 // If a list-item is a reference type then it must bind to the same object
12014 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000012015 if (!ASE && !OASE) {
12016 if (VD) {
12017 VarDecl *VDDef = VD->getDefinition();
12018 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
12019 DSARefChecker Check(Stack);
12020 if (Check.Visit(VDDef->getInit())) {
12021 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
12022 << getOpenMPClauseName(ClauseKind) << ERange;
12023 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
12024 continue;
12025 }
Alexey Bataeva1764212015-09-30 09:22:36 +000012026 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000012027 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012028
Alexey Bataevbc529672018-09-28 19:33:14 +000012029 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12030 // in a Construct]
12031 // Variables with the predetermined data-sharing attributes may not be
12032 // listed in data-sharing attributes clauses, except for the cases
12033 // listed below. For these exceptions only, listing a predetermined
12034 // variable in a data-sharing attribute clause is allowed and overrides
12035 // the variable's predetermined data-sharing attributes.
12036 // OpenMP [2.14.3.6, Restrictions, p.3]
12037 // Any number of reduction clauses can be specified on the directive,
12038 // but a list item can appear only once in the reduction clauses for that
12039 // directive.
12040 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
12041 if (DVar.CKind == OMPC_reduction) {
12042 S.Diag(ELoc, diag::err_omp_once_referenced)
12043 << getOpenMPClauseName(ClauseKind);
12044 if (DVar.RefExpr)
12045 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
12046 continue;
12047 }
12048 if (DVar.CKind != OMPC_unknown) {
12049 S.Diag(ELoc, diag::err_omp_wrong_dsa)
12050 << getOpenMPClauseName(DVar.CKind)
12051 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000012052 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012053 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000012054 }
Alexey Bataevbc529672018-09-28 19:33:14 +000012055
12056 // OpenMP [2.14.3.6, Restrictions, p.1]
12057 // A list item that appears in a reduction clause of a worksharing
12058 // construct must be shared in the parallel regions to which any of the
12059 // worksharing regions arising from the worksharing construct bind.
12060 if (isOpenMPWorksharingDirective(CurrDir) &&
12061 !isOpenMPParallelDirective(CurrDir) &&
12062 !isOpenMPTeamsDirective(CurrDir)) {
12063 DVar = Stack->getImplicitDSA(D, true);
12064 if (DVar.CKind != OMPC_shared) {
12065 S.Diag(ELoc, diag::err_omp_required_access)
12066 << getOpenMPClauseName(OMPC_reduction)
12067 << getOpenMPClauseName(OMPC_shared);
12068 reportOriginalDsa(S, Stack, D, DVar);
12069 continue;
12070 }
12071 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000012072 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012073
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012074 // Try to find 'declare reduction' corresponding construct before using
12075 // builtin/overloaded operators.
12076 CXXCastPath BasePath;
12077 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012078 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012079 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
12080 if (DeclareReductionRef.isInvalid())
12081 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012082 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012083 (DeclareReductionRef.isUnset() ||
12084 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012085 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012086 continue;
12087 }
12088 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
12089 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012090 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012091 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012092 << Type << ReductionIdRange;
12093 continue;
12094 }
12095
12096 // OpenMP [2.14.3.6, reduction clause, Restrictions]
12097 // The type of a list item that appears in a reduction clause must be valid
12098 // for the reduction-identifier. For a max or min reduction in C, the type
12099 // of the list item must be an allowed arithmetic data type: char, int,
12100 // float, double, or _Bool, possibly modified with long, short, signed, or
12101 // unsigned. For a max or min reduction in C++, the type of the list item
12102 // must be an allowed arithmetic data type: char, wchar_t, int, float,
12103 // double, or bool, possibly modified with long, short, signed, or unsigned.
12104 if (DeclareReductionRef.isUnset()) {
12105 if ((BOK == BO_GT || BOK == BO_LT) &&
12106 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012107 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
12108 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000012109 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012110 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012111 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12112 VarDecl::DeclarationOnly;
12113 S.Diag(D->getLocation(),
12114 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012115 << D;
12116 }
12117 continue;
12118 }
12119 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012120 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000012121 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
12122 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012123 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012124 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12125 VarDecl::DeclarationOnly;
12126 S.Diag(D->getLocation(),
12127 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012128 << D;
12129 }
12130 continue;
12131 }
12132 }
12133
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012134 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012135 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
12136 D->hasAttrs() ? &D->getAttrs() : nullptr);
12137 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
12138 D->hasAttrs() ? &D->getAttrs() : nullptr);
12139 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012140
12141 // Try if we can determine constant lengths for all array sections and avoid
12142 // the VLA.
12143 bool ConstantLengthOASE = false;
12144 if (OASE) {
12145 bool SingleElement;
12146 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000012147 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012148 Context, OASE, SingleElement, ArraySizes);
12149
12150 // If we don't have a single element, we must emit a constant array type.
12151 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012152 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012153 PrivateTy = Context.getConstantArrayType(
12154 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012155 }
12156 }
12157
12158 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000012159 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000012160 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000012161 if (!Context.getTargetInfo().isVLASupported()) {
12162 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
12163 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12164 S.Diag(ELoc, diag::note_vla_unsupported);
12165 } else {
12166 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
12167 S.targetDiag(ELoc, diag::note_vla_unsupported);
12168 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000012169 continue;
12170 }
David Majnemer9d168222016-08-05 17:44:54 +000012171 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012172 // Create pseudo array type for private copy. The size for this array will
12173 // be generated during codegen.
12174 // For array subscripts or single variables Private Ty is the same as Type
12175 // (type of the variable or single array element).
12176 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012177 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000012178 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012179 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000012180 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000012181 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012182 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012183 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012184 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012185 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012186 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
12187 D->hasAttrs() ? &D->getAttrs() : nullptr,
12188 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012189 // Add initializer for private variable.
12190 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012191 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
12192 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012193 if (DeclareReductionRef.isUsable()) {
12194 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
12195 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
12196 if (DRD->getInitializer()) {
12197 Init = DRDRef;
12198 RHSVD->setInit(DRDRef);
12199 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012200 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012201 } else {
12202 switch (BOK) {
12203 case BO_Add:
12204 case BO_Xor:
12205 case BO_Or:
12206 case BO_LOr:
12207 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
12208 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012209 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012210 break;
12211 case BO_Mul:
12212 case BO_LAnd:
12213 if (Type->isScalarType() || Type->isAnyComplexType()) {
12214 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012215 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012216 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012217 break;
12218 case BO_And: {
12219 // '&' reduction op - initializer is '~0'.
12220 QualType OrigType = Type;
12221 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
12222 Type = ComplexTy->getElementType();
12223 if (Type->isRealFloatingType()) {
12224 llvm::APFloat InitValue =
12225 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
12226 /*isIEEE=*/true);
12227 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12228 Type, ELoc);
12229 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012230 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012231 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
12232 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
12233 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12234 }
12235 if (Init && OrigType->isAnyComplexType()) {
12236 // Init = 0xFFFF + 0xFFFFi;
12237 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012238 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012239 }
12240 Type = OrigType;
12241 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012242 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012243 case BO_LT:
12244 case BO_GT: {
12245 // 'min' reduction op - initializer is 'Largest representable number in
12246 // the reduction list item type'.
12247 // 'max' reduction op - initializer is 'Least representable number in
12248 // the reduction list item type'.
12249 if (Type->isIntegerType() || Type->isPointerType()) {
12250 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000012251 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012252 QualType IntTy =
12253 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
12254 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012255 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
12256 : llvm::APInt::getMinValue(Size)
12257 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
12258 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012259 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12260 if (Type->isPointerType()) {
12261 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012262 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000012263 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012264 if (CastExpr.isInvalid())
12265 continue;
12266 Init = CastExpr.get();
12267 }
12268 } else if (Type->isRealFloatingType()) {
12269 llvm::APFloat InitValue = llvm::APFloat::getLargest(
12270 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
12271 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12272 Type, ELoc);
12273 }
12274 break;
12275 }
12276 case BO_PtrMemD:
12277 case BO_PtrMemI:
12278 case BO_MulAssign:
12279 case BO_Div:
12280 case BO_Rem:
12281 case BO_Sub:
12282 case BO_Shl:
12283 case BO_Shr:
12284 case BO_LE:
12285 case BO_GE:
12286 case BO_EQ:
12287 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000012288 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012289 case BO_AndAssign:
12290 case BO_XorAssign:
12291 case BO_OrAssign:
12292 case BO_Assign:
12293 case BO_AddAssign:
12294 case BO_SubAssign:
12295 case BO_DivAssign:
12296 case BO_RemAssign:
12297 case BO_ShlAssign:
12298 case BO_ShrAssign:
12299 case BO_Comma:
12300 llvm_unreachable("Unexpected reduction operation");
12301 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012302 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012303 if (Init && DeclareReductionRef.isUnset())
12304 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
12305 else if (!Init)
12306 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012307 if (RHSVD->isInvalidDecl())
12308 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000012309 if (!RHSVD->hasInit() &&
12310 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012311 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
12312 << Type << ReductionIdRange;
12313 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12314 VarDecl::DeclarationOnly;
12315 S.Diag(D->getLocation(),
12316 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000012317 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012318 continue;
12319 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012320 // Store initializer for single element in private copy. Will be used during
12321 // codegen.
12322 PrivateVD->setInit(RHSVD->getInit());
12323 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000012324 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012325 ExprResult ReductionOp;
12326 if (DeclareReductionRef.isUsable()) {
12327 QualType RedTy = DeclareReductionRef.get()->getType();
12328 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012329 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
12330 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012331 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012332 LHS = S.DefaultLvalueConversion(LHS.get());
12333 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012334 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12335 CK_UncheckedDerivedToBase, LHS.get(),
12336 &BasePath, LHS.get()->getValueKind());
12337 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12338 CK_UncheckedDerivedToBase, RHS.get(),
12339 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012340 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012341 FunctionProtoType::ExtProtoInfo EPI;
12342 QualType Params[] = {PtrRedTy, PtrRedTy};
12343 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
12344 auto *OVE = new (Context) OpaqueValueExpr(
12345 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012346 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012347 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000012348 ReductionOp =
12349 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012350 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012351 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012352 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012353 if (ReductionOp.isUsable()) {
12354 if (BOK != BO_LT && BOK != BO_GT) {
12355 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012356 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012357 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012358 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000012359 auto *ConditionalOp = new (Context)
12360 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
12361 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012362 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012363 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012364 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012365 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012366 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012367 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
12368 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012369 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012370 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012371 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012372 }
12373
Alexey Bataevfa312f32017-07-21 18:48:21 +000012374 // OpenMP [2.15.4.6, Restrictions, p.2]
12375 // A list item that appears in an in_reduction clause of a task construct
12376 // must appear in a task_reduction clause of a construct associated with a
12377 // taskgroup region that includes the participating task in its taskgroup
12378 // set. The construct associated with the innermost region that meets this
12379 // condition must specify the same reduction-identifier as the in_reduction
12380 // clause.
12381 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000012382 SourceRange ParentSR;
12383 BinaryOperatorKind ParentBOK;
12384 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000012385 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000012386 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012387 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
12388 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012389 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012390 Stack->getTopMostTaskgroupReductionData(
12391 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012392 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
12393 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
12394 if (!IsParentBOK && !IsParentReductionOp) {
12395 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
12396 continue;
12397 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000012398 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
12399 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
12400 IsParentReductionOp) {
12401 bool EmitError = true;
12402 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
12403 llvm::FoldingSetNodeID RedId, ParentRedId;
12404 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
12405 DeclareReductionRef.get()->Profile(RedId, Context,
12406 /*Canonical=*/true);
12407 EmitError = RedId != ParentRedId;
12408 }
12409 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012410 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000012411 diag::err_omp_reduction_identifier_mismatch)
12412 << ReductionIdRange << RefExpr->getSourceRange();
12413 S.Diag(ParentSR.getBegin(),
12414 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000012415 << ParentSR
12416 << (IsParentBOK ? ParentBOKDSA.RefExpr
12417 : ParentReductionOpDSA.RefExpr)
12418 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000012419 continue;
12420 }
12421 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012422 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
12423 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000012424 }
12425
Alexey Bataev60da77e2016-02-29 05:54:20 +000012426 DeclRefExpr *Ref = nullptr;
12427 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012428 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012429 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012430 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012431 VarsExpr =
12432 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
12433 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000012434 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012435 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012436 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012437 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012438 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012439 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012440 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012441 if (!RefRes.isUsable())
12442 continue;
12443 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012444 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12445 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012446 if (!PostUpdateRes.isUsable())
12447 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012448 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
12449 Stack->getCurrentDirective() == OMPD_taskgroup) {
12450 S.Diag(RefExpr->getExprLoc(),
12451 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000012452 << RefExpr->getSourceRange();
12453 continue;
12454 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012455 RD.ExprPostUpdates.emplace_back(
12456 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000012457 }
12458 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012459 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000012460 // All reduction items are still marked as reduction (to do not increase
12461 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012462 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012463 if (CurrDir == OMPD_taskgroup) {
12464 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012465 Stack->addTaskgroupReductionData(D, ReductionIdRange,
12466 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000012467 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012468 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012469 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012470 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
12471 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012472 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012473 return RD.Vars.empty();
12474}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012475
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012476OMPClause *Sema::ActOnOpenMPReductionClause(
12477 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12478 SourceLocation ColonLoc, SourceLocation EndLoc,
12479 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12480 ArrayRef<Expr *> UnresolvedReductions) {
12481 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012482 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012483 StartLoc, LParenLoc, ColonLoc, EndLoc,
12484 ReductionIdScopeSpec, ReductionId,
12485 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012486 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000012487
Alexey Bataevc5e02582014-06-16 07:08:35 +000012488 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012489 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12490 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12491 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12492 buildPreInits(Context, RD.ExprCaptures),
12493 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000012494}
12495
Alexey Bataev169d96a2017-07-18 20:17:46 +000012496OMPClause *Sema::ActOnOpenMPTaskReductionClause(
12497 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12498 SourceLocation ColonLoc, SourceLocation EndLoc,
12499 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12500 ArrayRef<Expr *> UnresolvedReductions) {
12501 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012502 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
12503 StartLoc, LParenLoc, ColonLoc, EndLoc,
12504 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012505 UnresolvedReductions, RD))
12506 return nullptr;
12507
12508 return OMPTaskReductionClause::Create(
12509 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12510 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12511 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12512 buildPreInits(Context, RD.ExprCaptures),
12513 buildPostUpdate(*this, RD.ExprPostUpdates));
12514}
12515
Alexey Bataevfa312f32017-07-21 18:48:21 +000012516OMPClause *Sema::ActOnOpenMPInReductionClause(
12517 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12518 SourceLocation ColonLoc, SourceLocation EndLoc,
12519 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12520 ArrayRef<Expr *> UnresolvedReductions) {
12521 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012522 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012523 StartLoc, LParenLoc, ColonLoc, EndLoc,
12524 ReductionIdScopeSpec, ReductionId,
12525 UnresolvedReductions, RD))
12526 return nullptr;
12527
12528 return OMPInReductionClause::Create(
12529 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12530 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000012531 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012532 buildPreInits(Context, RD.ExprCaptures),
12533 buildPostUpdate(*this, RD.ExprPostUpdates));
12534}
12535
Alexey Bataevecba70f2016-04-12 11:02:11 +000012536bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
12537 SourceLocation LinLoc) {
12538 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
12539 LinKind == OMPC_LINEAR_unknown) {
12540 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
12541 return true;
12542 }
12543 return false;
12544}
12545
Alexey Bataeve3727102018-04-18 15:57:46 +000012546bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000012547 OpenMPLinearClauseKind LinKind,
12548 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012549 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000012550 // A variable must not have an incomplete type or a reference type.
12551 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12552 return true;
12553 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12554 !Type->isReferenceType()) {
12555 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12556 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12557 return true;
12558 }
12559 Type = Type.getNonReferenceType();
12560
Joel E. Dennybae586f2019-01-04 22:12:13 +000012561 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12562 // A variable that is privatized must not have a const-qualified type
12563 // unless it is of class type with a mutable member. This restriction does
12564 // not apply to the firstprivate clause.
12565 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012566 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012567
12568 // A list item must be of integral or pointer type.
12569 Type = Type.getUnqualifiedType().getCanonicalType();
12570 const auto *Ty = Type.getTypePtrOrNull();
12571 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12572 !Ty->isPointerType())) {
12573 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12574 if (D) {
12575 bool IsDecl =
12576 !VD ||
12577 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12578 Diag(D->getLocation(),
12579 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12580 << D;
12581 }
12582 return true;
12583 }
12584 return false;
12585}
12586
Alexey Bataev182227b2015-08-20 10:54:39 +000012587OMPClause *Sema::ActOnOpenMPLinearClause(
12588 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12589 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12590 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012591 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012592 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012593 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012594 SmallVector<Decl *, 4> ExprCaptures;
12595 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012596 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012597 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012598 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012599 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012600 SourceLocation ELoc;
12601 SourceRange ERange;
12602 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012603 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012604 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012605 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012606 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012607 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012608 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012609 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012610 ValueDecl *D = Res.first;
12611 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012612 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012613
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012614 QualType Type = D->getType();
12615 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012616
12617 // OpenMP [2.14.3.7, linear clause]
12618 // A list-item cannot appear in more than one linear clause.
12619 // A list-item that appears in a linear clause cannot appear in any
12620 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012621 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012622 if (DVar.RefExpr) {
12623 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12624 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012625 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012626 continue;
12627 }
12628
Alexey Bataevecba70f2016-04-12 11:02:11 +000012629 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012630 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012631 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012632
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012633 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012634 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012635 buildVarDecl(*this, ELoc, Type, D->getName(),
12636 D->hasAttrs() ? &D->getAttrs() : nullptr,
12637 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012638 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012639 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012640 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012641 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012642 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012643 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012644 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012645 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012646 ExprCaptures.push_back(Ref->getDecl());
12647 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12648 ExprResult RefRes = DefaultLvalueConversion(Ref);
12649 if (!RefRes.isUsable())
12650 continue;
12651 ExprResult PostUpdateRes =
12652 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12653 SimpleRefExpr, RefRes.get());
12654 if (!PostUpdateRes.isUsable())
12655 continue;
12656 ExprPostUpdates.push_back(
12657 IgnoredValueConversions(PostUpdateRes.get()).get());
12658 }
12659 }
12660 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012661 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012662 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012663 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012664 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012665 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012666 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012667 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012668
12669 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012670 Vars.push_back((VD || CurContext->isDependentContext())
12671 ? RefExpr->IgnoreParens()
12672 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012673 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012674 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012675 }
12676
12677 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012678 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012679
12680 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012681 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012682 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12683 !Step->isInstantiationDependent() &&
12684 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012685 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012686 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012687 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012688 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012689 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012690
Alexander Musman3276a272015-03-21 10:12:56 +000012691 // Build var to save the step value.
12692 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012693 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012694 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012695 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012696 ExprResult CalcStep =
12697 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012698 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012699
Alexander Musman8dba6642014-04-22 13:09:42 +000012700 // Warn about zero linear step (it would be probably better specified as
12701 // making corresponding variables 'const').
12702 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012703 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12704 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012705 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12706 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012707 if (!IsConstant && CalcStep.isUsable()) {
12708 // Calculate the step beforehand instead of doing this on each iteration.
12709 // (This is not used if the number of iterations may be kfold-ed).
12710 CalcStepExpr = CalcStep.get();
12711 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012712 }
12713
Alexey Bataev182227b2015-08-20 10:54:39 +000012714 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12715 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012716 StepExpr, CalcStepExpr,
12717 buildPreInits(Context, ExprCaptures),
12718 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012719}
12720
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012721static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12722 Expr *NumIterations, Sema &SemaRef,
12723 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012724 // Walk the vars and build update/final expressions for the CodeGen.
12725 SmallVector<Expr *, 8> Updates;
12726 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000012727 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000012728 Expr *Step = Clause.getStep();
12729 Expr *CalcStep = Clause.getCalcStep();
12730 // OpenMP [2.14.3.7, linear clause]
12731 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012732 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012733 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012734 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012735 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12736 bool HasErrors = false;
12737 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012738 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012739 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12740 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012741 SourceLocation ELoc;
12742 SourceRange ERange;
12743 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012744 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012745 ValueDecl *D = Res.first;
12746 if (Res.second || !D) {
12747 Updates.push_back(nullptr);
12748 Finals.push_back(nullptr);
12749 HasErrors = true;
12750 continue;
12751 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012752 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012753 // OpenMP [2.15.11, distribute simd Construct]
12754 // A list item may not appear in a linear clause, unless it is the loop
12755 // iteration variable.
12756 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12757 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12758 SemaRef.Diag(ELoc,
12759 diag::err_omp_linear_distribute_var_non_loop_iteration);
12760 Updates.push_back(nullptr);
12761 Finals.push_back(nullptr);
12762 HasErrors = true;
12763 continue;
12764 }
Alexander Musman3276a272015-03-21 10:12:56 +000012765 Expr *InitExpr = *CurInit;
12766
12767 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012768 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012769 Expr *CapturedRef;
12770 if (LinKind == OMPC_LINEAR_uval)
12771 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12772 else
12773 CapturedRef =
12774 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12775 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12776 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012777
12778 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012779 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012780 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012781 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012782 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012783 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012784 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012785 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012786 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012787 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012788
12789 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012790 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012791 if (!Info.first)
12792 Final =
12793 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12794 InitExpr, NumIterations, Step, /*Subtract=*/false);
12795 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012796 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012797 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012798 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012799
Alexander Musman3276a272015-03-21 10:12:56 +000012800 if (!Update.isUsable() || !Final.isUsable()) {
12801 Updates.push_back(nullptr);
12802 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000012803 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012804 HasErrors = true;
12805 } else {
12806 Updates.push_back(Update.get());
12807 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000012808 if (!Info.first)
12809 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000012810 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012811 ++CurInit;
12812 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012813 }
Alexey Bataev195ae902019-08-08 13:42:45 +000012814 if (Expr *S = Clause.getStep())
12815 UsedExprs.push_back(S);
12816 // Fill the remaining part with the nullptr.
12817 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012818 Clause.setUpdates(Updates);
12819 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000012820 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000012821 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012822}
12823
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012824OMPClause *Sema::ActOnOpenMPAlignedClause(
12825 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12826 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012827 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012828 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012829 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12830 SourceLocation ELoc;
12831 SourceRange ERange;
12832 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012833 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012834 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012835 // It will be analyzed later.
12836 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012837 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012838 ValueDecl *D = Res.first;
12839 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012840 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012841
Alexey Bataev1efd1662016-03-29 10:59:56 +000012842 QualType QType = D->getType();
12843 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012844
12845 // OpenMP [2.8.1, simd construct, Restrictions]
12846 // The type of list items appearing in the aligned clause must be
12847 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012848 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012849 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012850 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012851 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012852 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012853 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012854 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012855 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012856 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012857 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012858 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012859 continue;
12860 }
12861
12862 // OpenMP [2.8.1, simd construct, Restrictions]
12863 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012864 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012865 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012866 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12867 << getOpenMPClauseName(OMPC_aligned);
12868 continue;
12869 }
12870
Alexey Bataev1efd1662016-03-29 10:59:56 +000012871 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012872 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012873 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12874 Vars.push_back(DefaultFunctionArrayConversion(
12875 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12876 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012877 }
12878
12879 // OpenMP [2.8.1, simd construct, Description]
12880 // The parameter of the aligned clause, alignment, must be a constant
12881 // positive integer expression.
12882 // If no optional parameter is specified, implementation-defined default
12883 // alignments for SIMD instructions on the target platforms are assumed.
12884 if (Alignment != nullptr) {
12885 ExprResult AlignResult =
12886 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12887 if (AlignResult.isInvalid())
12888 return nullptr;
12889 Alignment = AlignResult.get();
12890 }
12891 if (Vars.empty())
12892 return nullptr;
12893
12894 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12895 EndLoc, Vars, Alignment);
12896}
12897
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012898OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12899 SourceLocation StartLoc,
12900 SourceLocation LParenLoc,
12901 SourceLocation EndLoc) {
12902 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012903 SmallVector<Expr *, 8> SrcExprs;
12904 SmallVector<Expr *, 8> DstExprs;
12905 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012906 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012907 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12908 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012909 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012910 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012911 SrcExprs.push_back(nullptr);
12912 DstExprs.push_back(nullptr);
12913 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012914 continue;
12915 }
12916
Alexey Bataeved09d242014-05-28 05:53:51 +000012917 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012918 // OpenMP [2.1, C/C++]
12919 // A list item is a variable name.
12920 // OpenMP [2.14.4.1, Restrictions, p.1]
12921 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012922 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012923 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012924 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12925 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012926 continue;
12927 }
12928
12929 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012930 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012931
12932 QualType Type = VD->getType();
12933 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12934 // It will be analyzed later.
12935 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012936 SrcExprs.push_back(nullptr);
12937 DstExprs.push_back(nullptr);
12938 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012939 continue;
12940 }
12941
12942 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12943 // A list item that appears in a copyin clause must be threadprivate.
12944 if (!DSAStack->isThreadPrivate(VD)) {
12945 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012946 << getOpenMPClauseName(OMPC_copyin)
12947 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012948 continue;
12949 }
12950
12951 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12952 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012953 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012954 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012955 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12956 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012957 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012958 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012959 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012960 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012961 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012962 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012963 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012964 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012965 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012966 // For arrays generate assignment operation for single element and replace
12967 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012968 ExprResult AssignmentOp =
12969 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12970 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012971 if (AssignmentOp.isInvalid())
12972 continue;
12973 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012974 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012975 if (AssignmentOp.isInvalid())
12976 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012977
12978 DSAStack->addDSA(VD, DE, OMPC_copyin);
12979 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012980 SrcExprs.push_back(PseudoSrcExpr);
12981 DstExprs.push_back(PseudoDstExpr);
12982 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012983 }
12984
Alexey Bataeved09d242014-05-28 05:53:51 +000012985 if (Vars.empty())
12986 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012987
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012988 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12989 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012990}
12991
Alexey Bataevbae9a792014-06-27 10:37:06 +000012992OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12993 SourceLocation StartLoc,
12994 SourceLocation LParenLoc,
12995 SourceLocation EndLoc) {
12996 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012997 SmallVector<Expr *, 8> SrcExprs;
12998 SmallVector<Expr *, 8> DstExprs;
12999 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000013000 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000013001 assert(RefExpr && "NULL expr in OpenMP linear clause.");
13002 SourceLocation ELoc;
13003 SourceRange ERange;
13004 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013005 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000013006 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000013007 // It will be analyzed later.
13008 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013009 SrcExprs.push_back(nullptr);
13010 DstExprs.push_back(nullptr);
13011 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013012 }
Alexey Bataeve122da12016-03-17 10:50:17 +000013013 ValueDecl *D = Res.first;
13014 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000013015 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013016
Alexey Bataeve122da12016-03-17 10:50:17 +000013017 QualType Type = D->getType();
13018 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013019
13020 // OpenMP [2.14.4.2, Restrictions, p.2]
13021 // A list item that appears in a copyprivate clause may not appear in a
13022 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000013023 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 DSAStackTy::DSAVarData DVar =
13025 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013026 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
13027 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000013028 Diag(ELoc, diag::err_omp_wrong_dsa)
13029 << getOpenMPClauseName(DVar.CKind)
13030 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013031 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013032 continue;
13033 }
13034
13035 // OpenMP [2.11.4.2, Restrictions, p.1]
13036 // All list items that appear in a copyprivate clause must be either
13037 // threadprivate or private in the enclosing context.
13038 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000013039 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013040 if (DVar.CKind == OMPC_shared) {
13041 Diag(ELoc, diag::err_omp_required_access)
13042 << getOpenMPClauseName(OMPC_copyprivate)
13043 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000013044 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013045 continue;
13046 }
13047 }
13048 }
13049
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013050 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000013051 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013052 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013053 << getOpenMPClauseName(OMPC_copyprivate) << Type
13054 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013055 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000013056 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013057 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000013058 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013059 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000013060 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013061 continue;
13062 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013063
Alexey Bataevbae9a792014-06-27 10:37:06 +000013064 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13065 // A variable of class type (or array thereof) that appears in a
13066 // copyin clause requires an accessible, unambiguous copy assignment
13067 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013068 Type = Context.getBaseElementType(Type.getNonReferenceType())
13069 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013070 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013071 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000013072 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013073 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
13074 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013075 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000013076 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013077 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
13078 ExprResult AssignmentOp = BuildBinOp(
13079 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013080 if (AssignmentOp.isInvalid())
13081 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013082 AssignmentOp =
13083 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013084 if (AssignmentOp.isInvalid())
13085 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013086
13087 // No need to mark vars as copyprivate, they are already threadprivate or
13088 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000013089 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000013090 Vars.push_back(
13091 VD ? RefExpr->IgnoreParens()
13092 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000013093 SrcExprs.push_back(PseudoSrcExpr);
13094 DstExprs.push_back(PseudoDstExpr);
13095 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000013096 }
13097
13098 if (Vars.empty())
13099 return nullptr;
13100
Alexey Bataeva63048e2015-03-23 06:18:07 +000013101 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13102 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013103}
13104
Alexey Bataev6125da92014-07-21 11:26:11 +000013105OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
13106 SourceLocation StartLoc,
13107 SourceLocation LParenLoc,
13108 SourceLocation EndLoc) {
13109 if (VarList.empty())
13110 return nullptr;
13111
13112 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
13113}
Alexey Bataevdea47612014-07-23 07:46:59 +000013114
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013115OMPClause *
13116Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
13117 SourceLocation DepLoc, SourceLocation ColonLoc,
13118 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13119 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013120 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013121 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013122 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013123 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000013124 return nullptr;
13125 }
13126 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013127 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
13128 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000013129 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013130 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013131 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13132 /*Last=*/OMPC_DEPEND_unknown, Except)
13133 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013134 return nullptr;
13135 }
13136 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000013137 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013138 llvm::APSInt DepCounter(/*BitWidth=*/32);
13139 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000013140 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
13141 if (const Expr *OrderedCountExpr =
13142 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013143 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
13144 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013145 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013146 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013147 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000013148 assert(RefExpr && "NULL expr in OpenMP shared clause.");
13149 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
13150 // It will be analyzed later.
13151 Vars.push_back(RefExpr);
13152 continue;
13153 }
13154
13155 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000013156 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000013157 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000013158 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013159 DepCounter >= TotalDepCount) {
13160 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
13161 continue;
13162 }
13163 ++DepCounter;
13164 // OpenMP [2.13.9, Summary]
13165 // depend(dependence-type : vec), where dependence-type is:
13166 // 'sink' and where vec is the iteration vector, which has the form:
13167 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
13168 // where n is the value specified by the ordered clause in the loop
13169 // directive, xi denotes the loop iteration variable of the i-th nested
13170 // loop associated with the loop directive, and di is a constant
13171 // non-negative integer.
13172 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013173 // It will be analyzed later.
13174 Vars.push_back(RefExpr);
13175 continue;
13176 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013177 SimpleExpr = SimpleExpr->IgnoreImplicit();
13178 OverloadedOperatorKind OOK = OO_None;
13179 SourceLocation OOLoc;
13180 Expr *LHS = SimpleExpr;
13181 Expr *RHS = nullptr;
13182 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
13183 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
13184 OOLoc = BO->getOperatorLoc();
13185 LHS = BO->getLHS()->IgnoreParenImpCasts();
13186 RHS = BO->getRHS()->IgnoreParenImpCasts();
13187 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
13188 OOK = OCE->getOperator();
13189 OOLoc = OCE->getOperatorLoc();
13190 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
13191 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
13192 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
13193 OOK = MCE->getMethodDecl()
13194 ->getNameInfo()
13195 .getName()
13196 .getCXXOverloadedOperator();
13197 OOLoc = MCE->getCallee()->getExprLoc();
13198 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
13199 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013200 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013201 SourceLocation ELoc;
13202 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000013203 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013204 if (Res.second) {
13205 // It will be analyzed later.
13206 Vars.push_back(RefExpr);
13207 }
13208 ValueDecl *D = Res.first;
13209 if (!D)
13210 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013211
Alexey Bataev17daedf2018-02-15 22:42:57 +000013212 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
13213 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
13214 continue;
13215 }
13216 if (RHS) {
13217 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
13218 RHS, OMPC_depend, /*StrictlyPositive=*/false);
13219 if (RHSRes.isInvalid())
13220 continue;
13221 }
13222 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013223 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013224 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013225 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000013226 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000013227 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000013228 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
13229 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000013230 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000013231 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000013232 continue;
13233 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013234 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000013235 } else {
13236 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
13237 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
13238 (ASE &&
13239 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
13240 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
13241 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13242 << RefExpr->getSourceRange();
13243 continue;
13244 }
13245 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
13246 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
13247 ExprResult Res =
13248 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
13249 getDiagnostics().setSuppressAllDiagnostics(Suppress);
13250 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
13251 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
13252 << RefExpr->getSourceRange();
13253 continue;
13254 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013255 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013256 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013257 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013258
13259 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
13260 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013261 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013262 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
13263 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
13264 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
13265 }
13266 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
13267 Vars.empty())
13268 return nullptr;
13269
Alexey Bataev8b427062016-05-25 12:36:08 +000013270 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000013271 DepKind, DepLoc, ColonLoc, Vars,
13272 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000013273 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
13274 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000013275 DSAStack->addDoacrossDependClause(C, OpsOffs);
13276 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013277}
Michael Wonge710d542015-08-07 16:16:36 +000013278
13279OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
13280 SourceLocation LParenLoc,
13281 SourceLocation EndLoc) {
13282 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013283 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000013284
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013285 // OpenMP [2.9.1, Restrictions]
13286 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013287 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000013288 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013289 return nullptr;
13290
Alexey Bataev931e19b2017-10-02 16:32:39 +000013291 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013292 OpenMPDirectiveKind CaptureRegion =
13293 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
13294 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013295 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013296 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013297 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13298 HelperValStmt = buildPreInits(Context, Captures);
13299 }
13300
Alexey Bataev8451efa2018-01-15 19:06:12 +000013301 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
13302 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000013303}
Kelvin Li0bff7af2015-11-23 05:32:03 +000013304
Alexey Bataeve3727102018-04-18 15:57:46 +000013305static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000013306 DSAStackTy *Stack, QualType QTy,
13307 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000013308 NamedDecl *ND;
13309 if (QTy->isIncompleteType(&ND)) {
13310 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
13311 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013312 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000013313 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
13314 !QTy.isTrivialType(SemaRef.Context))
13315 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013316 return true;
13317}
13318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013319/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013320/// (array section or array subscript) does NOT specify the whole size of the
13321/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013322static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013323 const Expr *E,
13324 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013325 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013326
13327 // If this is an array subscript, it refers to the whole size if the size of
13328 // the dimension is constant and equals 1. Also, an array section assumes the
13329 // format of an array subscript if no colon is used.
13330 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013331 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013332 return ATy->getSize().getSExtValue() != 1;
13333 // Size can't be evaluated statically.
13334 return false;
13335 }
13336
13337 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013338 const Expr *LowerBound = OASE->getLowerBound();
13339 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013340
13341 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000013342 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013343 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000013344 Expr::EvalResult Result;
13345 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013346 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000013347
13348 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013349 if (ConstLowerBound.getSExtValue())
13350 return true;
13351 }
13352
13353 // If we don't have a length we covering the whole dimension.
13354 if (!Length)
13355 return false;
13356
13357 // If the base is a pointer, we don't have a way to get the size of the
13358 // pointee.
13359 if (BaseQTy->isPointerType())
13360 return false;
13361
13362 // We can only check if the length is the same as the size of the dimension
13363 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000013364 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013365 if (!CATy)
13366 return false;
13367
Fangrui Song407659a2018-11-30 23:41:18 +000013368 Expr::EvalResult Result;
13369 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013370 return false; // Can't get the integer value as a constant.
13371
Fangrui Song407659a2018-11-30 23:41:18 +000013372 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013373 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
13374}
13375
13376// Return true if it can be proven that the provided array expression (array
13377// section or array subscript) does NOT specify a single element of the array
13378// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013379static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000013380 const Expr *E,
13381 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013382 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013383
13384 // An array subscript always refer to a single element. Also, an array section
13385 // assumes the format of an array subscript if no colon is used.
13386 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
13387 return false;
13388
13389 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013390 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013391
13392 // If we don't have a length we have to check if the array has unitary size
13393 // for this dimension. Also, we should always expect a length if the base type
13394 // is pointer.
13395 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013396 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013397 return ATy->getSize().getSExtValue() != 1;
13398 // We cannot assume anything.
13399 return false;
13400 }
13401
13402 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000013403 Expr::EvalResult Result;
13404 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013405 return false; // Can't get the integer value as a constant.
13406
Fangrui Song407659a2018-11-30 23:41:18 +000013407 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013408 return ConstLength.getSExtValue() != 1;
13409}
13410
Samuel Antao661c0902016-05-26 17:39:58 +000013411// Return the expression of the base of the mappable expression or null if it
13412// cannot be determined and do all the necessary checks to see if the expression
13413// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000013414// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013415static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000013416 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000013417 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013418 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013419 SourceLocation ELoc = E->getExprLoc();
13420 SourceRange ERange = E->getSourceRange();
13421
13422 // The base of elements of list in a map clause have to be either:
13423 // - a reference to variable or field.
13424 // - a member expression.
13425 // - an array expression.
13426 //
13427 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
13428 // reference to 'r'.
13429 //
13430 // If we have:
13431 //
13432 // struct SS {
13433 // Bla S;
13434 // foo() {
13435 // #pragma omp target map (S.Arr[:12]);
13436 // }
13437 // }
13438 //
13439 // We want to retrieve the member expression 'this->S';
13440
Alexey Bataeve3727102018-04-18 15:57:46 +000013441 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013442
Samuel Antao5de996e2016-01-22 20:21:36 +000013443 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
13444 // If a list item is an array section, it must specify contiguous storage.
13445 //
13446 // For this restriction it is sufficient that we make sure only references
13447 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013448 // exist except in the rightmost expression (unless they cover the whole
13449 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000013450 //
13451 // r.ArrS[3:5].Arr[6:7]
13452 //
13453 // r.ArrS[3:5].x
13454 //
13455 // but these would be valid:
13456 // r.ArrS[3].Arr[6:7]
13457 //
13458 // r.ArrS[3].x
13459
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013460 bool AllowUnitySizeArraySection = true;
13461 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013462
Dmitry Polukhin644a9252016-03-11 07:58:34 +000013463 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013464 E = E->IgnoreParenImpCasts();
13465
13466 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
13467 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000013468 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013469
13470 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013471
13472 // If we got a reference to a declaration, we should not expect any array
13473 // section before that.
13474 AllowUnitySizeArraySection = false;
13475 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013476
13477 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013478 CurComponents.emplace_back(CurE, CurE->getDecl());
13479 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013480 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000013481
13482 if (isa<CXXThisExpr>(BaseE))
13483 // We found a base expression: this->Val.
13484 RelevantExpr = CurE;
13485 else
13486 E = BaseE;
13487
13488 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013489 if (!NoDiagnose) {
13490 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
13491 << CurE->getSourceRange();
13492 return nullptr;
13493 }
13494 if (RelevantExpr)
13495 return nullptr;
13496 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013497 }
13498
13499 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
13500
13501 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
13502 // A bit-field cannot appear in a map clause.
13503 //
13504 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013505 if (!NoDiagnose) {
13506 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
13507 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
13508 return nullptr;
13509 }
13510 if (RelevantExpr)
13511 return nullptr;
13512 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013513 }
13514
13515 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13516 // If the type of a list item is a reference to a type T then the type
13517 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013518 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013519
13520 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
13521 // A list item cannot be a variable that is a member of a structure with
13522 // a union type.
13523 //
Alexey Bataeve3727102018-04-18 15:57:46 +000013524 if (CurType->isUnionType()) {
13525 if (!NoDiagnose) {
13526 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
13527 << CurE->getSourceRange();
13528 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013529 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013530 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013531 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013532
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013533 // If we got a member expression, we should not expect any array section
13534 // before that:
13535 //
13536 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
13537 // If a list item is an element of a structure, only the rightmost symbol
13538 // of the variable reference can be an array section.
13539 //
13540 AllowUnitySizeArraySection = false;
13541 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013542
13543 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013544 CurComponents.emplace_back(CurE, FD);
13545 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013546 E = CurE->getBase()->IgnoreParenImpCasts();
13547
13548 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013549 if (!NoDiagnose) {
13550 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13551 << 0 << CurE->getSourceRange();
13552 return nullptr;
13553 }
13554 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013555 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013556
13557 // If we got an array subscript that express the whole dimension we
13558 // can have any array expressions before. If it only expressing part of
13559 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000013560 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013561 E->getType()))
13562 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013563
Patrick Lystere13b1e32019-01-02 19:28:48 +000013564 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13565 Expr::EvalResult Result;
13566 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13567 if (!Result.Val.getInt().isNullValue()) {
13568 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13569 diag::err_omp_invalid_map_this_expr);
13570 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13571 diag::note_omp_invalid_subscript_on_this_ptr_map);
13572 }
13573 }
13574 RelevantExpr = TE;
13575 }
13576
Samuel Antao90927002016-04-26 14:54:23 +000013577 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013578 CurComponents.emplace_back(CurE, nullptr);
13579 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013580 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013581 E = CurE->getBase()->IgnoreParenImpCasts();
13582
Alexey Bataev27041fa2017-12-05 15:22:49 +000013583 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013584 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13585
Samuel Antao5de996e2016-01-22 20:21:36 +000013586 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13587 // If the type of a list item is a reference to a type T then the type
13588 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013589 if (CurType->isReferenceType())
13590 CurType = CurType->getPointeeType();
13591
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013592 bool IsPointer = CurType->isAnyPointerType();
13593
13594 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013595 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13596 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013597 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013598 }
13599
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013600 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013601 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013602 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013603 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013604
Samuel Antaodab51bb2016-07-18 23:22:11 +000013605 if (AllowWholeSizeArraySection) {
13606 // Any array section is currently allowed. Allowing a whole size array
13607 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013608 //
13609 // If this array section refers to the whole dimension we can still
13610 // accept other array sections before this one, except if the base is a
13611 // pointer. Otherwise, only unitary sections are accepted.
13612 if (NotWhole || IsPointer)
13613 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013614 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013615 // A unity or whole array section is not allowed and that is not
13616 // compatible with the properties of the current array section.
13617 SemaRef.Diag(
13618 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13619 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013620 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013621 }
Samuel Antao90927002016-04-26 14:54:23 +000013622
Patrick Lystere13b1e32019-01-02 19:28:48 +000013623 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13624 Expr::EvalResult ResultR;
13625 Expr::EvalResult ResultL;
13626 if (CurE->getLength()->EvaluateAsInt(ResultR,
13627 SemaRef.getASTContext())) {
13628 if (!ResultR.Val.getInt().isOneValue()) {
13629 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13630 diag::err_omp_invalid_map_this_expr);
13631 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13632 diag::note_omp_invalid_length_on_this_ptr_mapping);
13633 }
13634 }
13635 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13636 ResultL, SemaRef.getASTContext())) {
13637 if (!ResultL.Val.getInt().isNullValue()) {
13638 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13639 diag::err_omp_invalid_map_this_expr);
13640 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13641 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13642 }
13643 }
13644 RelevantExpr = TE;
13645 }
13646
Samuel Antao90927002016-04-26 14:54:23 +000013647 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013648 CurComponents.emplace_back(CurE, nullptr);
13649 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013650 if (!NoDiagnose) {
13651 // If nothing else worked, this is not a valid map clause expression.
13652 SemaRef.Diag(
13653 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13654 << ERange;
13655 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013656 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013657 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013658 }
13659
13660 return RelevantExpr;
13661}
13662
13663// Return true if expression E associated with value VD has conflicts with other
13664// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013665static bool checkMapConflicts(
13666 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013667 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013668 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13669 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013670 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013671 SourceLocation ELoc = E->getExprLoc();
13672 SourceRange ERange = E->getSourceRange();
13673
13674 // In order to easily check the conflicts we need to match each component of
13675 // the expression under test with the components of the expressions that are
13676 // already in the stack.
13677
Samuel Antao5de996e2016-01-22 20:21:36 +000013678 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013679 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013680 "Map clause expression with unexpected base!");
13681
13682 // Variables to help detecting enclosing problems in data environment nests.
13683 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013684 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013685
Samuel Antao90927002016-04-26 14:54:23 +000013686 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13687 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013688 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13689 ERange, CKind, &EnclosingExpr,
13690 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13691 StackComponents,
13692 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013693 assert(!StackComponents.empty() &&
13694 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013695 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013696 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013697 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013698
Samuel Antao90927002016-04-26 14:54:23 +000013699 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013700 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013701
Samuel Antao5de996e2016-01-22 20:21:36 +000013702 // Expressions must start from the same base. Here we detect at which
13703 // point both expressions diverge from each other and see if we can
13704 // detect if the memory referred to both expressions is contiguous and
13705 // do not overlap.
13706 auto CI = CurComponents.rbegin();
13707 auto CE = CurComponents.rend();
13708 auto SI = StackComponents.rbegin();
13709 auto SE = StackComponents.rend();
13710 for (; CI != CE && SI != SE; ++CI, ++SI) {
13711
13712 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13713 // At most one list item can be an array item derived from a given
13714 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013715 if (CurrentRegionOnly &&
13716 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13717 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13718 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13719 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13720 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013721 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013722 << CI->getAssociatedExpression()->getSourceRange();
13723 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13724 diag::note_used_here)
13725 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013726 return true;
13727 }
13728
13729 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013730 if (CI->getAssociatedExpression()->getStmtClass() !=
13731 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013732 break;
13733
13734 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013735 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013736 break;
13737 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013738 // Check if the extra components of the expressions in the enclosing
13739 // data environment are redundant for the current base declaration.
13740 // If they are, the maps completely overlap, which is legal.
13741 for (; SI != SE; ++SI) {
13742 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013743 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013744 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013745 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013746 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013747 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013748 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013749 Type =
13750 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13751 }
13752 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013753 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013754 SemaRef, SI->getAssociatedExpression(), Type))
13755 break;
13756 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013757
13758 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13759 // List items of map clauses in the same construct must not share
13760 // original storage.
13761 //
13762 // If the expressions are exactly the same or one is a subset of the
13763 // other, it means they are sharing storage.
13764 if (CI == CE && SI == SE) {
13765 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013766 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013767 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013768 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013769 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013770 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13771 << ERange;
13772 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013773 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13774 << RE->getSourceRange();
13775 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013776 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013777 // If we find the same expression in the enclosing data environment,
13778 // that is legal.
13779 IsEnclosedByDataEnvironmentExpr = true;
13780 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013781 }
13782
Samuel Antao90927002016-04-26 14:54:23 +000013783 QualType DerivedType =
13784 std::prev(CI)->getAssociatedDeclaration()->getType();
13785 SourceLocation DerivedLoc =
13786 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013787
13788 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13789 // If the type of a list item is a reference to a type T then the type
13790 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013791 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013792
13793 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13794 // A variable for which the type is pointer and an array section
13795 // derived from that variable must not appear as list items of map
13796 // clauses of the same construct.
13797 //
13798 // Also, cover one of the cases in:
13799 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13800 // If any part of the original storage of a list item has corresponding
13801 // storage in the device data environment, all of the original storage
13802 // must have corresponding storage in the device data environment.
13803 //
13804 if (DerivedType->isAnyPointerType()) {
13805 if (CI == CE || SI == SE) {
13806 SemaRef.Diag(
13807 DerivedLoc,
13808 diag::err_omp_pointer_mapped_along_with_derived_section)
13809 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013810 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13811 << RE->getSourceRange();
13812 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013813 }
13814 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013815 SI->getAssociatedExpression()->getStmtClass() ||
13816 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13817 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013818 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013819 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013820 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013821 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13822 << RE->getSourceRange();
13823 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013824 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013825 }
13826
13827 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13828 // List items of map clauses in the same construct must not share
13829 // original storage.
13830 //
13831 // An expression is a subset of the other.
13832 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013833 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013834 if (CI != CE || SI != SE) {
13835 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13836 // a pointer.
13837 auto Begin =
13838 CI != CE ? CurComponents.begin() : StackComponents.begin();
13839 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13840 auto It = Begin;
13841 while (It != End && !It->getAssociatedDeclaration())
13842 std::advance(It, 1);
13843 assert(It != End &&
13844 "Expected at least one component with the declaration.");
13845 if (It != Begin && It->getAssociatedDeclaration()
13846 ->getType()
13847 .getCanonicalType()
13848 ->isAnyPointerType()) {
13849 IsEnclosedByDataEnvironmentExpr = false;
13850 EnclosingExpr = nullptr;
13851 return false;
13852 }
13853 }
Samuel Antao661c0902016-05-26 17:39:58 +000013854 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013855 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013856 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013857 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13858 << ERange;
13859 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013860 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13861 << RE->getSourceRange();
13862 return true;
13863 }
13864
13865 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013866 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013867 if (!CurrentRegionOnly && SI != SE)
13868 EnclosingExpr = RE;
13869
13870 // The current expression is a subset of the expression in the data
13871 // environment.
13872 IsEnclosedByDataEnvironmentExpr |=
13873 (!CurrentRegionOnly && CI != CE && SI == SE);
13874
13875 return false;
13876 });
13877
13878 if (CurrentRegionOnly)
13879 return FoundError;
13880
13881 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13882 // If any part of the original storage of a list item has corresponding
13883 // storage in the device data environment, all of the original storage must
13884 // have corresponding storage in the device data environment.
13885 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13886 // If a list item is an element of a structure, and a different element of
13887 // the structure has a corresponding list item in the device data environment
13888 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013889 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013890 // data environment prior to the task encountering the construct.
13891 //
13892 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13893 SemaRef.Diag(ELoc,
13894 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13895 << ERange;
13896 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13897 << EnclosingExpr->getSourceRange();
13898 return true;
13899 }
13900
13901 return FoundError;
13902}
13903
Michael Kruse4304e9d2019-02-19 16:38:20 +000013904// Look up the user-defined mapper given the mapper name and mapped type, and
13905// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000013906static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13907 CXXScopeSpec &MapperIdScopeSpec,
13908 const DeclarationNameInfo &MapperId,
13909 QualType Type,
13910 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013911 if (MapperIdScopeSpec.isInvalid())
13912 return ExprError();
13913 // Find all user-defined mappers with the given MapperId.
13914 SmallVector<UnresolvedSet<8>, 4> Lookups;
13915 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13916 Lookup.suppressDiagnostics();
13917 if (S) {
13918 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13919 NamedDecl *D = Lookup.getRepresentativeDecl();
13920 while (S && !S->isDeclScope(D))
13921 S = S->getParent();
13922 if (S)
13923 S = S->getParent();
13924 Lookups.emplace_back();
13925 Lookups.back().append(Lookup.begin(), Lookup.end());
13926 Lookup.clear();
13927 }
13928 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13929 // Extract the user-defined mappers with the given MapperId.
13930 Lookups.push_back(UnresolvedSet<8>());
13931 for (NamedDecl *D : ULE->decls()) {
13932 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13933 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13934 Lookups.back().addDecl(DMD);
13935 }
13936 }
13937 // Defer the lookup for dependent types. The results will be passed through
13938 // UnresolvedMapper on instantiation.
13939 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13940 Type->isInstantiationDependentType() ||
13941 Type->containsUnexpandedParameterPack() ||
13942 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13943 return !D->isInvalidDecl() &&
13944 (D->getType()->isDependentType() ||
13945 D->getType()->isInstantiationDependentType() ||
13946 D->getType()->containsUnexpandedParameterPack());
13947 })) {
13948 UnresolvedSet<8> URS;
13949 for (const UnresolvedSet<8> &Set : Lookups) {
13950 if (Set.empty())
13951 continue;
13952 URS.append(Set.begin(), Set.end());
13953 }
13954 return UnresolvedLookupExpr::Create(
13955 SemaRef.Context, /*NamingClass=*/nullptr,
13956 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13957 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13958 }
13959 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13960 // The type must be of struct, union or class type in C and C++
13961 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13962 return ExprEmpty();
13963 SourceLocation Loc = MapperId.getLoc();
13964 // Perform argument dependent lookup.
13965 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13966 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13967 // Return the first user-defined mapper with the desired type.
13968 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13969 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13970 if (!D->isInvalidDecl() &&
13971 SemaRef.Context.hasSameType(D->getType(), Type))
13972 return D;
13973 return nullptr;
13974 }))
13975 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13976 // Find the first user-defined mapper with a type derived from the desired
13977 // type.
13978 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13979 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13980 if (!D->isInvalidDecl() &&
13981 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13982 !Type.isMoreQualifiedThan(D->getType()))
13983 return D;
13984 return nullptr;
13985 })) {
13986 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13987 /*DetectVirtual=*/false);
13988 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13989 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13990 VD->getType().getUnqualifiedType()))) {
13991 if (SemaRef.CheckBaseClassAccess(
13992 Loc, VD->getType(), Type, Paths.front(),
13993 /*DiagID=*/0) != Sema::AR_inaccessible) {
13994 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13995 }
13996 }
13997 }
13998 }
13999 // Report error if a mapper is specified, but cannot be found.
14000 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
14001 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
14002 << Type << MapperId.getName();
14003 return ExprError();
14004 }
14005 return ExprEmpty();
14006}
14007
Samuel Antao661c0902016-05-26 17:39:58 +000014008namespace {
14009// Utility struct that gathers all the related lists associated with a mappable
14010// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014011struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000014012 // The list of expressions.
14013 ArrayRef<Expr *> VarList;
14014 // The list of processed expressions.
14015 SmallVector<Expr *, 16> ProcessedVarList;
14016 // The mappble components for each expression.
14017 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
14018 // The base declaration of the variable.
14019 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000014020 // The reference to the user-defined mapper associated with every expression.
14021 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000014022
14023 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
14024 // We have a list of components and base declarations for each entry in the
14025 // variable list.
14026 VarComponents.reserve(VarList.size());
14027 VarBaseDeclarations.reserve(VarList.size());
14028 }
14029};
14030}
14031
14032// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000014033// \a CKind. In the check process the valid expressions, mappable expression
14034// components, variables, and user-defined mappers are extracted and used to
14035// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
14036// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
14037// and \a MapperId are expected to be valid if the clause kind is 'map'.
14038static void checkMappableExpressionList(
14039 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
14040 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014041 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
14042 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014043 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000014044 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014045 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
14046 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000014047 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000014048
14049 // If the identifier of user-defined mapper is not specified, it is "default".
14050 // We do not change the actual name in this clause to distinguish whether a
14051 // mapper is specified explicitly, i.e., it is not explicitly specified when
14052 // MapperId.getName() is empty.
14053 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
14054 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
14055 MapperId.setName(DeclNames.getIdentifier(
14056 &SemaRef.getASTContext().Idents.get("default")));
14057 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014058
14059 // Iterators to find the current unresolved mapper expression.
14060 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
14061 bool UpdateUMIt = false;
14062 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014063
Samuel Antao90927002016-04-26 14:54:23 +000014064 // Keep track of the mappable components and base declarations in this clause.
14065 // Each entry in the list is going to have a list of components associated. We
14066 // record each set of the components so that we can build the clause later on.
14067 // In the end we should have the same amount of declarations and component
14068 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000014069
Alexey Bataeve3727102018-04-18 15:57:46 +000014070 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014071 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014072 SourceLocation ELoc = RE->getExprLoc();
14073
Michael Kruse4304e9d2019-02-19 16:38:20 +000014074 // Find the current unresolved mapper expression.
14075 if (UpdateUMIt && UMIt != UMEnd) {
14076 UMIt++;
14077 assert(
14078 UMIt != UMEnd &&
14079 "Expect the size of UnresolvedMappers to match with that of VarList");
14080 }
14081 UpdateUMIt = true;
14082 if (UMIt != UMEnd)
14083 UnresolvedMapper = *UMIt;
14084
Alexey Bataeve3727102018-04-18 15:57:46 +000014085 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014086
14087 if (VE->isValueDependent() || VE->isTypeDependent() ||
14088 VE->isInstantiationDependent() ||
14089 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000014090 // Try to find the associated user-defined mapper.
14091 ExprResult ER = buildUserDefinedMapperRef(
14092 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14093 VE->getType().getCanonicalType(), UnresolvedMapper);
14094 if (ER.isInvalid())
14095 continue;
14096 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000014097 // We can only analyze this information once the missing information is
14098 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000014099 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014100 continue;
14101 }
14102
Alexey Bataeve3727102018-04-18 15:57:46 +000014103 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014104
Samuel Antao5de996e2016-01-22 20:21:36 +000014105 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000014106 SemaRef.Diag(ELoc,
14107 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000014108 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014109 continue;
14110 }
14111
Samuel Antao90927002016-04-26 14:54:23 +000014112 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
14113 ValueDecl *CurDeclaration = nullptr;
14114
14115 // Obtain the array or member expression bases if required. Also, fill the
14116 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000014117 const Expr *BE = checkMapClauseExpressionBase(
14118 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000014119 if (!BE)
14120 continue;
14121
Samuel Antao90927002016-04-26 14:54:23 +000014122 assert(!CurComponents.empty() &&
14123 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014124
Patrick Lystere13b1e32019-01-02 19:28:48 +000014125 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
14126 // Add store "this" pointer to class in DSAStackTy for future checking
14127 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000014128 // Try to find the associated user-defined mapper.
14129 ExprResult ER = buildUserDefinedMapperRef(
14130 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14131 VE->getType().getCanonicalType(), UnresolvedMapper);
14132 if (ER.isInvalid())
14133 continue;
14134 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000014135 // Skip restriction checking for variable or field declarations
14136 MVLI.ProcessedVarList.push_back(RE);
14137 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14138 MVLI.VarComponents.back().append(CurComponents.begin(),
14139 CurComponents.end());
14140 MVLI.VarBaseDeclarations.push_back(nullptr);
14141 continue;
14142 }
14143
Samuel Antao90927002016-04-26 14:54:23 +000014144 // For the following checks, we rely on the base declaration which is
14145 // expected to be associated with the last component. The declaration is
14146 // expected to be a variable or a field (if 'this' is being mapped).
14147 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
14148 assert(CurDeclaration && "Null decl on map clause.");
14149 assert(
14150 CurDeclaration->isCanonicalDecl() &&
14151 "Expecting components to have associated only canonical declarations.");
14152
14153 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000014154 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000014155
14156 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000014157 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014158
14159 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000014160 // threadprivate variables cannot appear in a map clause.
14161 // OpenMP 4.5 [2.10.5, target update Construct]
14162 // threadprivate variables cannot appear in a from clause.
14163 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014164 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014165 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
14166 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000014167 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014168 continue;
14169 }
14170
Samuel Antao5de996e2016-01-22 20:21:36 +000014171 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
14172 // A list item cannot appear in both a map clause and a data-sharing
14173 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000014174
Samuel Antao5de996e2016-01-22 20:21:36 +000014175 // Check conflicts with other map clause expressions. We check the conflicts
14176 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000014177 // environment, because the restrictions are different. We only have to
14178 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000014179 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014180 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014181 break;
Samuel Antao661c0902016-05-26 17:39:58 +000014182 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014183 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000014184 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000014185 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014186
Samuel Antao661c0902016-05-26 17:39:58 +000014187 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000014188 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14189 // If the type of a list item is a reference to a type T then the type will
14190 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000014191 auto I = llvm::find_if(
14192 CurComponents,
14193 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
14194 return MC.getAssociatedDeclaration();
14195 });
14196 assert(I != CurComponents.end() && "Null decl on map clause.");
14197 QualType Type =
14198 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014199
Samuel Antao661c0902016-05-26 17:39:58 +000014200 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
14201 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000014202 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000014203 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014204 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000014205 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000014206 continue;
14207
Samuel Antao661c0902016-05-26 17:39:58 +000014208 if (CKind == OMPC_map) {
14209 // target enter data
14210 // OpenMP [2.10.2, Restrictions, p. 99]
14211 // A map-type must be specified in all map clauses and must be either
14212 // to or alloc.
14213 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
14214 if (DKind == OMPD_target_enter_data &&
14215 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
14216 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14217 << (IsMapTypeImplicit ? 1 : 0)
14218 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14219 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014220 continue;
14221 }
Samuel Antao661c0902016-05-26 17:39:58 +000014222
14223 // target exit_data
14224 // OpenMP [2.10.3, Restrictions, p. 102]
14225 // A map-type must be specified in all map clauses and must be either
14226 // from, release, or delete.
14227 if (DKind == OMPD_target_exit_data &&
14228 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
14229 MapType == OMPC_MAP_delete)) {
14230 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
14231 << (IsMapTypeImplicit ? 1 : 0)
14232 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
14233 << getOpenMPDirectiveName(DKind);
14234 continue;
14235 }
14236
14237 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
14238 // A list item cannot appear in both a map clause and a data-sharing
14239 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000014240 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
14241 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000014242 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000014243 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000014244 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000014245 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000014246 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014247 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000014248 continue;
14249 }
14250 }
Michael Kruse01f670d2019-02-22 22:29:42 +000014251 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014252
Michael Kruse01f670d2019-02-22 22:29:42 +000014253 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000014254 ExprResult ER = buildUserDefinedMapperRef(
14255 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14256 Type.getCanonicalType(), UnresolvedMapper);
14257 if (ER.isInvalid())
14258 continue;
14259 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014260
Samuel Antao90927002016-04-26 14:54:23 +000014261 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000014262 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000014263
14264 // Store the components in the stack so that they can be used to check
14265 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000014266 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
14267 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000014268
14269 // Save the components and declaration to create the clause. For purposes of
14270 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000014271 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000014272 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14273 MVLI.VarComponents.back().append(CurComponents.begin(),
14274 CurComponents.end());
14275 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
14276 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014277 }
Samuel Antao661c0902016-05-26 17:39:58 +000014278}
14279
Michael Kruse4304e9d2019-02-19 16:38:20 +000014280OMPClause *Sema::ActOnOpenMPMapClause(
14281 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14282 ArrayRef<SourceLocation> MapTypeModifiersLoc,
14283 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
14284 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
14285 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
14286 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
14287 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
14288 OMPC_MAP_MODIFIER_unknown,
14289 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000014290 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
14291
14292 // Process map-type-modifiers, flag errors for duplicate modifiers.
14293 unsigned Count = 0;
14294 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
14295 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
14296 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
14297 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
14298 continue;
14299 }
14300 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000014301 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000014302 Modifiers[Count] = MapTypeModifiers[I];
14303 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
14304 ++Count;
14305 }
14306
Michael Kruse4304e9d2019-02-19 16:38:20 +000014307 MappableVarListInfo MVLI(VarList);
14308 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014309 MapperIdScopeSpec, MapperId, UnresolvedMappers,
14310 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000014311
Samuel Antao5de996e2016-01-22 20:21:36 +000014312 // We need to produce a map clause even if we don't have variables so that
14313 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000014314 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
14315 MVLI.VarBaseDeclarations, MVLI.VarComponents,
14316 MVLI.UDMapperList, Modifiers, ModifiersLoc,
14317 MapperIdScopeSpec.getWithLocInContext(Context),
14318 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014319}
Kelvin Li099bb8c2015-11-24 20:50:12 +000014320
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014321QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
14322 TypeResult ParsedType) {
14323 assert(ParsedType.isUsable());
14324
14325 QualType ReductionType = GetTypeFromParser(ParsedType.get());
14326 if (ReductionType.isNull())
14327 return QualType();
14328
14329 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
14330 // A type name in a declare reduction directive cannot be a function type, an
14331 // array type, a reference type, or a type qualified with const, volatile or
14332 // restrict.
14333 if (ReductionType.hasQualifiers()) {
14334 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
14335 return QualType();
14336 }
14337
14338 if (ReductionType->isFunctionType()) {
14339 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
14340 return QualType();
14341 }
14342 if (ReductionType->isReferenceType()) {
14343 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
14344 return QualType();
14345 }
14346 if (ReductionType->isArrayType()) {
14347 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
14348 return QualType();
14349 }
14350 return ReductionType;
14351}
14352
14353Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
14354 Scope *S, DeclContext *DC, DeclarationName Name,
14355 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
14356 AccessSpecifier AS, Decl *PrevDeclInScope) {
14357 SmallVector<Decl *, 8> Decls;
14358 Decls.reserve(ReductionTypes.size());
14359
14360 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000014361 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014362 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
14363 // A reduction-identifier may not be re-declared in the current scope for the
14364 // same type or for a type that is compatible according to the base language
14365 // rules.
14366 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14367 OMPDeclareReductionDecl *PrevDRD = nullptr;
14368 bool InCompoundScope = true;
14369 if (S != nullptr) {
14370 // Find previous declaration with the same name not referenced in other
14371 // declarations.
14372 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14373 InCompoundScope =
14374 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14375 LookupName(Lookup, S);
14376 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14377 /*AllowInlineNamespace=*/false);
14378 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000014379 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014380 while (Filter.hasNext()) {
14381 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
14382 if (InCompoundScope) {
14383 auto I = UsedAsPrevious.find(PrevDecl);
14384 if (I == UsedAsPrevious.end())
14385 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000014386 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014387 UsedAsPrevious[D] = true;
14388 }
14389 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14390 PrevDecl->getLocation();
14391 }
14392 Filter.done();
14393 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014394 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014395 if (!PrevData.second) {
14396 PrevDRD = PrevData.first;
14397 break;
14398 }
14399 }
14400 }
14401 } else if (PrevDeclInScope != nullptr) {
14402 auto *PrevDRDInScope = PrevDRD =
14403 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
14404 do {
14405 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
14406 PrevDRDInScope->getLocation();
14407 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
14408 } while (PrevDRDInScope != nullptr);
14409 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014410 for (const auto &TyData : ReductionTypes) {
14411 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014412 bool Invalid = false;
14413 if (I != PreviousRedeclTypes.end()) {
14414 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
14415 << TyData.first;
14416 Diag(I->second, diag::note_previous_definition);
14417 Invalid = true;
14418 }
14419 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
14420 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
14421 Name, TyData.first, PrevDRD);
14422 DC->addDecl(DRD);
14423 DRD->setAccess(AS);
14424 Decls.push_back(DRD);
14425 if (Invalid)
14426 DRD->setInvalidDecl();
14427 else
14428 PrevDRD = DRD;
14429 }
14430
14431 return DeclGroupPtrTy::make(
14432 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
14433}
14434
14435void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
14436 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14437
14438 // Enter new function scope.
14439 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014440 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014441 getCurFunction()->setHasOMPDeclareReductionCombiner();
14442
14443 if (S != nullptr)
14444 PushDeclContext(S, DRD);
14445 else
14446 CurContext = DRD;
14447
Faisal Valid143a0c2017-04-01 21:30:49 +000014448 PushExpressionEvaluationContext(
14449 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014450
14451 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014452 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
14453 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
14454 // uses semantics of argument handles by value, but it should be passed by
14455 // reference. C lang does not support references, so pass all parameters as
14456 // pointers.
14457 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014458 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014459 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014460 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
14461 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
14462 // uses semantics of argument handles by value, but it should be passed by
14463 // reference. C lang does not support references, so pass all parameters as
14464 // pointers.
14465 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014466 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014467 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
14468 if (S != nullptr) {
14469 PushOnScopeChains(OmpInParm, S);
14470 PushOnScopeChains(OmpOutParm, S);
14471 } else {
14472 DRD->addDecl(OmpInParm);
14473 DRD->addDecl(OmpOutParm);
14474 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014475 Expr *InE =
14476 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
14477 Expr *OutE =
14478 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
14479 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014480}
14481
14482void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
14483 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14484 DiscardCleanupsInEvaluationContext();
14485 PopExpressionEvaluationContext();
14486
14487 PopDeclContext();
14488 PopFunctionScopeInfo();
14489
14490 if (Combiner != nullptr)
14491 DRD->setCombiner(Combiner);
14492 else
14493 DRD->setInvalidDecl();
14494}
14495
Alexey Bataev070f43a2017-09-06 14:49:58 +000014496VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014497 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14498
14499 // Enter new function scope.
14500 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014501 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014502
14503 if (S != nullptr)
14504 PushDeclContext(S, DRD);
14505 else
14506 CurContext = DRD;
14507
Faisal Valid143a0c2017-04-01 21:30:49 +000014508 PushExpressionEvaluationContext(
14509 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014510
14511 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014512 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
14513 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
14514 // uses semantics of argument handles by value, but it should be passed by
14515 // reference. C lang does not support references, so pass all parameters as
14516 // pointers.
14517 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014518 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014519 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014520 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
14521 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
14522 // uses semantics of argument handles by value, but it should be passed by
14523 // reference. C lang does not support references, so pass all parameters as
14524 // pointers.
14525 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014526 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014527 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014528 if (S != nullptr) {
14529 PushOnScopeChains(OmpPrivParm, S);
14530 PushOnScopeChains(OmpOrigParm, S);
14531 } else {
14532 DRD->addDecl(OmpPrivParm);
14533 DRD->addDecl(OmpOrigParm);
14534 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014535 Expr *OrigE =
14536 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
14537 Expr *PrivE =
14538 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
14539 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000014540 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014541}
14542
Alexey Bataev070f43a2017-09-06 14:49:58 +000014543void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
14544 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014545 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14546 DiscardCleanupsInEvaluationContext();
14547 PopExpressionEvaluationContext();
14548
14549 PopDeclContext();
14550 PopFunctionScopeInfo();
14551
Alexey Bataev070f43a2017-09-06 14:49:58 +000014552 if (Initializer != nullptr) {
14553 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14554 } else if (OmpPrivParm->hasInit()) {
14555 DRD->setInitializer(OmpPrivParm->getInit(),
14556 OmpPrivParm->isDirectInit()
14557 ? OMPDeclareReductionDecl::DirectInit
14558 : OMPDeclareReductionDecl::CopyInit);
14559 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014560 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000014561 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014562}
14563
14564Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14565 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014566 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014567 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014568 if (S)
14569 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14570 /*AddToContext=*/false);
14571 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014572 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014573 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014574 }
14575 return DeclReductions;
14576}
14577
Michael Kruse251e1482019-02-01 20:25:04 +000014578TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14579 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14580 QualType T = TInfo->getType();
14581 if (D.isInvalidType())
14582 return true;
14583
14584 if (getLangOpts().CPlusPlus) {
14585 // Check that there are no default arguments (C++ only).
14586 CheckExtraCXXDefaultArguments(D);
14587 }
14588
14589 return CreateParsedType(T, TInfo);
14590}
14591
14592QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14593 TypeResult ParsedType) {
14594 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14595
14596 QualType MapperType = GetTypeFromParser(ParsedType.get());
14597 assert(!MapperType.isNull() && "Expect valid mapper type");
14598
14599 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14600 // The type must be of struct, union or class type in C and C++
14601 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14602 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14603 return QualType();
14604 }
14605 return MapperType;
14606}
14607
14608OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14609 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14610 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14611 Decl *PrevDeclInScope) {
14612 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14613 forRedeclarationInCurContext());
14614 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14615 // A mapper-identifier may not be redeclared in the current scope for the
14616 // same type or for a type that is compatible according to the base language
14617 // rules.
14618 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14619 OMPDeclareMapperDecl *PrevDMD = nullptr;
14620 bool InCompoundScope = true;
14621 if (S != nullptr) {
14622 // Find previous declaration with the same name not referenced in other
14623 // declarations.
14624 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14625 InCompoundScope =
14626 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14627 LookupName(Lookup, S);
14628 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14629 /*AllowInlineNamespace=*/false);
14630 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14631 LookupResult::Filter Filter = Lookup.makeFilter();
14632 while (Filter.hasNext()) {
14633 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14634 if (InCompoundScope) {
14635 auto I = UsedAsPrevious.find(PrevDecl);
14636 if (I == UsedAsPrevious.end())
14637 UsedAsPrevious[PrevDecl] = false;
14638 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14639 UsedAsPrevious[D] = true;
14640 }
14641 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14642 PrevDecl->getLocation();
14643 }
14644 Filter.done();
14645 if (InCompoundScope) {
14646 for (const auto &PrevData : UsedAsPrevious) {
14647 if (!PrevData.second) {
14648 PrevDMD = PrevData.first;
14649 break;
14650 }
14651 }
14652 }
14653 } else if (PrevDeclInScope) {
14654 auto *PrevDMDInScope = PrevDMD =
14655 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14656 do {
14657 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14658 PrevDMDInScope->getLocation();
14659 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14660 } while (PrevDMDInScope != nullptr);
14661 }
14662 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14663 bool Invalid = false;
14664 if (I != PreviousRedeclTypes.end()) {
14665 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14666 << MapperType << Name;
14667 Diag(I->second, diag::note_previous_definition);
14668 Invalid = true;
14669 }
14670 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14671 MapperType, VN, PrevDMD);
14672 DC->addDecl(DMD);
14673 DMD->setAccess(AS);
14674 if (Invalid)
14675 DMD->setInvalidDecl();
14676
14677 // Enter new function scope.
14678 PushFunctionScope();
14679 setFunctionHasBranchProtectedScope();
14680
14681 CurContext = DMD;
14682
14683 return DMD;
14684}
14685
14686void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14687 Scope *S,
14688 QualType MapperType,
14689 SourceLocation StartLoc,
14690 DeclarationName VN) {
14691 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14692 if (S)
14693 PushOnScopeChains(VD, S);
14694 else
14695 DMD->addDecl(VD);
14696 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14697 DMD->setMapperVarRef(MapperVarRefExpr);
14698}
14699
14700Sema::DeclGroupPtrTy
14701Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14702 ArrayRef<OMPClause *> ClauseList) {
14703 PopDeclContext();
14704 PopFunctionScopeInfo();
14705
14706 if (D) {
14707 if (S)
14708 PushOnScopeChains(D, S, /*AddToContext=*/false);
14709 D->CreateClauses(Context, ClauseList);
14710 }
14711
14712 return DeclGroupPtrTy::make(DeclGroupRef(D));
14713}
14714
David Majnemer9d168222016-08-05 17:44:54 +000014715OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014716 SourceLocation StartLoc,
14717 SourceLocation LParenLoc,
14718 SourceLocation EndLoc) {
14719 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014720 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014721
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014722 // OpenMP [teams Constrcut, Restrictions]
14723 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014724 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014725 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014726 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014727
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014728 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014729 OpenMPDirectiveKind CaptureRegion =
14730 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14731 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014732 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014733 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014734 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14735 HelperValStmt = buildPreInits(Context, Captures);
14736 }
14737
14738 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14739 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014740}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014741
14742OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14743 SourceLocation StartLoc,
14744 SourceLocation LParenLoc,
14745 SourceLocation EndLoc) {
14746 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014747 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014748
14749 // OpenMP [teams Constrcut, Restrictions]
14750 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014751 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014752 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014753 return nullptr;
14754
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014755 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014756 OpenMPDirectiveKind CaptureRegion =
14757 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14758 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014759 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014760 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014761 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14762 HelperValStmt = buildPreInits(Context, Captures);
14763 }
14764
14765 return new (Context) OMPThreadLimitClause(
14766 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014767}
Alexey Bataeva0569352015-12-01 10:17:31 +000014768
14769OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14770 SourceLocation StartLoc,
14771 SourceLocation LParenLoc,
14772 SourceLocation EndLoc) {
14773 Expr *ValExpr = Priority;
14774
14775 // OpenMP [2.9.1, task Constrcut]
14776 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014777 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014778 /*StrictlyPositive=*/false))
14779 return nullptr;
14780
14781 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14782}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014783
14784OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14785 SourceLocation StartLoc,
14786 SourceLocation LParenLoc,
14787 SourceLocation EndLoc) {
14788 Expr *ValExpr = Grainsize;
14789
14790 // OpenMP [2.9.2, taskloop Constrcut]
14791 // The parameter of the grainsize clause must be a positive integer
14792 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014793 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014794 /*StrictlyPositive=*/true))
14795 return nullptr;
14796
14797 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14798}
Alexey Bataev382967a2015-12-08 12:06:20 +000014799
14800OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14801 SourceLocation StartLoc,
14802 SourceLocation LParenLoc,
14803 SourceLocation EndLoc) {
14804 Expr *ValExpr = NumTasks;
14805
14806 // OpenMP [2.9.2, taskloop Constrcut]
14807 // The parameter of the num_tasks clause must be a positive integer
14808 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014809 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014810 /*StrictlyPositive=*/true))
14811 return nullptr;
14812
14813 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14814}
14815
Alexey Bataev28c75412015-12-15 08:19:24 +000014816OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14817 SourceLocation LParenLoc,
14818 SourceLocation EndLoc) {
14819 // OpenMP [2.13.2, critical construct, Description]
14820 // ... where hint-expression is an integer constant expression that evaluates
14821 // to a valid lock hint.
14822 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14823 if (HintExpr.isInvalid())
14824 return nullptr;
14825 return new (Context)
14826 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14827}
14828
Carlo Bertollib4adf552016-01-15 18:50:31 +000014829OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14830 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14831 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14832 SourceLocation EndLoc) {
14833 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14834 std::string Values;
14835 Values += "'";
14836 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14837 Values += "'";
14838 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14839 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14840 return nullptr;
14841 }
14842 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014843 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014844 if (ChunkSize) {
14845 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14846 !ChunkSize->isInstantiationDependent() &&
14847 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014848 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014849 ExprResult Val =
14850 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14851 if (Val.isInvalid())
14852 return nullptr;
14853
14854 ValExpr = Val.get();
14855
14856 // OpenMP [2.7.1, Restrictions]
14857 // chunk_size must be a loop invariant integer expression with a positive
14858 // value.
14859 llvm::APSInt Result;
14860 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14861 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14862 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14863 << "dist_schedule" << ChunkSize->getSourceRange();
14864 return nullptr;
14865 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014866 } else if (getOpenMPCaptureRegionForClause(
14867 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14868 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014869 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014870 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014871 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014872 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14873 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014874 }
14875 }
14876 }
14877
14878 return new (Context)
14879 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014880 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014881}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014882
14883OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14884 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14885 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14886 SourceLocation KindLoc, SourceLocation EndLoc) {
14887 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014888 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014889 std::string Value;
14890 SourceLocation Loc;
14891 Value += "'";
14892 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14893 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014894 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014895 Loc = MLoc;
14896 } else {
14897 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014898 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014899 Loc = KindLoc;
14900 }
14901 Value += "'";
14902 Diag(Loc, diag::err_omp_unexpected_clause_value)
14903 << Value << getOpenMPClauseName(OMPC_defaultmap);
14904 return nullptr;
14905 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014906 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014907
14908 return new (Context)
14909 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14910}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014911
14912bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14913 DeclContext *CurLexicalContext = getCurLexicalContext();
14914 if (!CurLexicalContext->isFileContext() &&
14915 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014916 !CurLexicalContext->isExternCXXContext() &&
14917 !isa<CXXRecordDecl>(CurLexicalContext) &&
14918 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14919 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14920 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014921 Diag(Loc, diag::err_omp_region_not_file_context);
14922 return false;
14923 }
Kelvin Libc38e632018-09-10 02:07:09 +000014924 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014925 return true;
14926}
14927
14928void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014929 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014930 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014931 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014932}
14933
David Majnemer9d168222016-08-05 17:44:54 +000014934void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14935 CXXScopeSpec &ScopeSpec,
14936 const DeclarationNameInfo &Id,
14937 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14938 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014939 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14940 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14941
14942 if (Lookup.isAmbiguous())
14943 return;
14944 Lookup.suppressDiagnostics();
14945
14946 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000014947 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014948 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000014949 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014950 CTK_ErrorRecovery)) {
14951 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14952 << Id.getName());
14953 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14954 return;
14955 }
14956
14957 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14958 return;
14959 }
14960
14961 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014962 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14963 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014964 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14965 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014966 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14967 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14968 cast<ValueDecl>(ND));
14969 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014970 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014971 ND->addAttr(A);
14972 if (ASTMutationListener *ML = Context.getASTMutationListener())
14973 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014974 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014975 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014976 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14977 << Id.getName();
14978 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014979 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014980 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014981 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014982}
14983
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014984static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14985 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014986 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014987 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014988 auto *VD = cast<VarDecl>(D);
14989 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14990 return;
14991 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14992 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014993}
14994
14995static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14996 Sema &SemaRef, DSAStackTy *Stack,
14997 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014998 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14999 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
15000 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015001}
15002
Kelvin Li1ce87c72017-12-12 20:08:12 +000015003void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
15004 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015005 if (!D || D->isInvalidDecl())
15006 return;
15007 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015008 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000015009 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000015010 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000015011 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
15012 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000015013 return;
15014 // 2.10.6: threadprivate variable cannot appear in a declare target
15015 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015016 if (DSAStack->isThreadPrivate(VD)) {
15017 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000015018 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015019 return;
15020 }
15021 }
Alexey Bataev97b72212018-08-14 18:31:20 +000015022 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
15023 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000015024 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000015025 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
15026 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
15027 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000015028 assert(IdLoc.isValid() && "Source location is expected");
15029 Diag(IdLoc, diag::err_omp_function_in_link_clause);
15030 Diag(FD->getLocation(), diag::note_defined_here) << FD;
15031 return;
15032 }
15033 }
Alexey Bataev30a78212018-09-11 13:59:10 +000015034 if (auto *VD = dyn_cast<ValueDecl>(D)) {
15035 // Problem if any with var declared with incomplete type will be reported
15036 // as normal, so no need to check it here.
15037 if ((E || !VD->getType()->isIncompleteType()) &&
15038 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
15039 return;
15040 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
15041 // Checking declaration inside declare target region.
15042 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
15043 isa<FunctionTemplateDecl>(D)) {
15044 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
15045 Context, OMPDeclareTargetDeclAttr::MT_To);
15046 D->addAttr(A);
15047 if (ASTMutationListener *ML = Context.getASTMutationListener())
15048 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
15049 }
15050 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015051 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015052 }
Alexey Bataev30a78212018-09-11 13:59:10 +000015053 if (!E)
15054 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015055 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
15056}
Samuel Antao661c0902016-05-26 17:39:58 +000015057
15058OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000015059 CXXScopeSpec &MapperIdScopeSpec,
15060 DeclarationNameInfo &MapperId,
15061 const OMPVarListLocTy &Locs,
15062 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000015063 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015064 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
15065 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000015066 if (MVLI.ProcessedVarList.empty())
15067 return nullptr;
15068
Michael Kruse01f670d2019-02-22 22:29:42 +000015069 return OMPToClause::Create(
15070 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15071 MVLI.VarComponents, MVLI.UDMapperList,
15072 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000015073}
Samuel Antaoec172c62016-05-26 17:49:04 +000015074
15075OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000015076 CXXScopeSpec &MapperIdScopeSpec,
15077 DeclarationNameInfo &MapperId,
15078 const OMPVarListLocTy &Locs,
15079 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015080 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015081 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
15082 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000015083 if (MVLI.ProcessedVarList.empty())
15084 return nullptr;
15085
Michael Kruse0336c752019-02-25 20:34:15 +000015086 return OMPFromClause::Create(
15087 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15088 MVLI.VarComponents, MVLI.UDMapperList,
15089 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000015090}
Carlo Bertolli2404b172016-07-13 15:37:16 +000015091
15092OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015093 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000015094 MappableVarListInfo MVLI(VarList);
15095 SmallVector<Expr *, 8> PrivateCopies;
15096 SmallVector<Expr *, 8> Inits;
15097
Alexey Bataeve3727102018-04-18 15:57:46 +000015098 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015099 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
15100 SourceLocation ELoc;
15101 SourceRange ERange;
15102 Expr *SimpleRefExpr = RefExpr;
15103 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15104 if (Res.second) {
15105 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000015106 MVLI.ProcessedVarList.push_back(RefExpr);
15107 PrivateCopies.push_back(nullptr);
15108 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015109 }
15110 ValueDecl *D = Res.first;
15111 if (!D)
15112 continue;
15113
15114 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000015115 Type = Type.getNonReferenceType().getUnqualifiedType();
15116
15117 auto *VD = dyn_cast<VarDecl>(D);
15118
15119 // Item should be a pointer or reference to pointer.
15120 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000015121 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
15122 << 0 << RefExpr->getSourceRange();
15123 continue;
15124 }
Samuel Antaocc10b852016-07-28 14:23:26 +000015125
15126 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000015127 auto VDPrivate =
15128 buildVarDecl(*this, ELoc, Type, D->getName(),
15129 D->hasAttrs() ? &D->getAttrs() : nullptr,
15130 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000015131 if (VDPrivate->isInvalidDecl())
15132 continue;
15133
15134 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000015135 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000015136 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
15137
15138 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000015139 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000015140 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000015141 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
15142 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000015143 AddInitializerToDecl(VDPrivate,
15144 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000015145 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000015146
15147 // If required, build a capture to implement the privatization initialized
15148 // with the current list item value.
15149 DeclRefExpr *Ref = nullptr;
15150 if (!VD)
15151 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
15152 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
15153 PrivateCopies.push_back(VDPrivateRefExpr);
15154 Inits.push_back(VDInitRefExpr);
15155
15156 // We need to add a data sharing attribute for this variable to make sure it
15157 // is correctly captured. A variable that shows up in a use_device_ptr has
15158 // similar properties of a first private variable.
15159 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
15160
15161 // Create a mappable component for the list item. List items in this clause
15162 // only need a component.
15163 MVLI.VarBaseDeclarations.push_back(D);
15164 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15165 MVLI.VarComponents.back().push_back(
15166 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000015167 }
15168
Samuel Antaocc10b852016-07-28 14:23:26 +000015169 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000015170 return nullptr;
15171
Samuel Antaocc10b852016-07-28 14:23:26 +000015172 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000015173 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
15174 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000015175}
Carlo Bertolli70594e92016-07-13 17:16:49 +000015176
15177OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015178 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000015179 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000015180 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000015181 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000015182 SourceLocation ELoc;
15183 SourceRange ERange;
15184 Expr *SimpleRefExpr = RefExpr;
15185 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15186 if (Res.second) {
15187 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000015188 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015189 }
15190 ValueDecl *D = Res.first;
15191 if (!D)
15192 continue;
15193
15194 QualType Type = D->getType();
15195 // item should be a pointer or array or reference to pointer or array
15196 if (!Type.getNonReferenceType()->isPointerType() &&
15197 !Type.getNonReferenceType()->isArrayType()) {
15198 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
15199 << 0 << RefExpr->getSourceRange();
15200 continue;
15201 }
Samuel Antao6890b092016-07-28 14:25:09 +000015202
15203 // Check if the declaration in the clause does not show up in any data
15204 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000015205 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000015206 if (isOpenMPPrivate(DVar.CKind)) {
15207 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
15208 << getOpenMPClauseName(DVar.CKind)
15209 << getOpenMPClauseName(OMPC_is_device_ptr)
15210 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015211 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000015212 continue;
15213 }
15214
Alexey Bataeve3727102018-04-18 15:57:46 +000015215 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000015216 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000015217 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000015218 [&ConflictExpr](
15219 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
15220 OpenMPClauseKind) -> bool {
15221 ConflictExpr = R.front().getAssociatedExpression();
15222 return true;
15223 })) {
15224 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
15225 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
15226 << ConflictExpr->getSourceRange();
15227 continue;
15228 }
15229
15230 // Store the components in the stack so that they can be used to check
15231 // against other clauses later on.
15232 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
15233 DSAStack->addMappableExpressionComponents(
15234 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
15235
15236 // Record the expression we've just processed.
15237 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
15238
15239 // Create a mappable component for the list item. List items in this clause
15240 // only need a component. We use a null declaration to signal fields in
15241 // 'this'.
15242 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
15243 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
15244 "Unexpected device pointer expression!");
15245 MVLI.VarBaseDeclarations.push_back(
15246 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
15247 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15248 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015249 }
15250
Samuel Antao6890b092016-07-28 14:25:09 +000015251 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000015252 return nullptr;
15253
Michael Kruse4304e9d2019-02-19 16:38:20 +000015254 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
15255 MVLI.VarBaseDeclarations,
15256 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015257}
Alexey Bataeve04483e2019-03-27 14:14:31 +000015258
15259OMPClause *Sema::ActOnOpenMPAllocateClause(
15260 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15261 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15262 if (Allocator) {
15263 // OpenMP [2.11.4 allocate Clause, Description]
15264 // allocator is an expression of omp_allocator_handle_t type.
15265 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
15266 return nullptr;
15267
15268 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
15269 if (AllocatorRes.isInvalid())
15270 return nullptr;
15271 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
15272 DSAStack->getOMPAllocatorHandleT(),
15273 Sema::AA_Initializing,
15274 /*AllowExplicit=*/true);
15275 if (AllocatorRes.isInvalid())
15276 return nullptr;
15277 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000015278 } else {
15279 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
15280 // allocate clauses that appear on a target construct or on constructs in a
15281 // target region must specify an allocator expression unless a requires
15282 // directive with the dynamic_allocators clause is present in the same
15283 // compilation unit.
15284 if (LangOpts.OpenMPIsDevice &&
15285 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
15286 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000015287 }
15288 // Analyze and build list of variables.
15289 SmallVector<Expr *, 8> Vars;
15290 for (Expr *RefExpr : VarList) {
15291 assert(RefExpr && "NULL expr in OpenMP private clause.");
15292 SourceLocation ELoc;
15293 SourceRange ERange;
15294 Expr *SimpleRefExpr = RefExpr;
15295 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15296 if (Res.second) {
15297 // It will be analyzed later.
15298 Vars.push_back(RefExpr);
15299 }
15300 ValueDecl *D = Res.first;
15301 if (!D)
15302 continue;
15303
15304 auto *VD = dyn_cast<VarDecl>(D);
15305 DeclRefExpr *Ref = nullptr;
15306 if (!VD && !CurContext->isDependentContext())
15307 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15308 Vars.push_back((VD || CurContext->isDependentContext())
15309 ? RefExpr->IgnoreParens()
15310 : Ref);
15311 }
15312
15313 if (Vars.empty())
15314 return nullptr;
15315
15316 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
15317 ColonLoc, EndLoc, Vars);
15318}