blob: c7e0d2aee036e0a1172fda3850a54f0f770d7857 [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 Bataevd1caf932019-09-30 14:05:26 +0000173 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000174 /// 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 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000525 /// Returns the capture region at the specified level.
526 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
527 unsigned OpenMPCaptureLevel) const {
528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
529 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
530 return CaptureRegions[OpenMPCaptureLevel];
531 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000533 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000534 const SharingMapTy *Parent = getSecondOnStackOrNull();
535 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000536 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000537
Kelvin Li1408f912018-09-26 04:28:39 +0000538 /// Add requires decl to internal vector
539 void addRequiresDecl(OMPRequiresDecl *RD) {
540 RequiresDecls.push_back(RD);
541 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000542
Alexey Bataev318f431b2019-03-22 15:25:12 +0000543 /// Checks if the defined 'requires' directive has specified type of clause.
544 template <typename ClauseType>
545 bool hasRequiresDeclWithClause() {
546 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
547 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
548 return isa<ClauseType>(C);
549 });
550 });
551 }
552
Kelvin Li1408f912018-09-26 04:28:39 +0000553 /// Checks for a duplicate clause amongst previously declared requires
554 /// directives
555 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
556 bool IsDuplicate = false;
557 for (OMPClause *CNew : ClauseList) {
558 for (const OMPRequiresDecl *D : RequiresDecls) {
559 for (const OMPClause *CPrev : D->clauselists()) {
560 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
561 SemaRef.Diag(CNew->getBeginLoc(),
562 diag::err_omp_requires_clause_redeclaration)
563 << getOpenMPClauseName(CNew->getClauseKind());
564 SemaRef.Diag(CPrev->getBeginLoc(),
565 diag::note_omp_requires_previous_clause)
566 << getOpenMPClauseName(CPrev->getClauseKind());
567 IsDuplicate = true;
568 }
569 }
570 }
571 }
572 return IsDuplicate;
573 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000574
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000575 /// Add location of previously encountered target to internal vector
576 void addTargetDirLocation(SourceLocation LocStart) {
577 TargetLocations.push_back(LocStart);
578 }
579
580 // Return previously encountered target region locations.
581 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
582 return TargetLocations;
583 }
584
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000585 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000586 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000587 getTopOfStack().DefaultAttr = DSA_none;
588 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000589 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000590 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000591 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000592 getTopOfStack().DefaultAttr = DSA_shared;
593 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000594 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000595 /// Set default data mapping attribute to 'tofrom:scalar'.
596 void setDefaultDMAToFromScalar(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000597 getTopOfStack().DefaultMapAttr = DMA_tofrom_scalar;
598 getTopOfStack().DefaultMapAttrLoc = Loc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000599 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000600
601 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000602 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000603 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000604 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000605 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000606 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000607 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000608 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000609 DefaultMapAttributes getDefaultDMA() const {
610 return isStackEmpty() ? DMA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000611 : getTopOfStack().DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000612 }
613 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000614 return getStackElemAtLevel(Level).DefaultMapAttr;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000615 }
616 SourceLocation getDefaultDMALocation() const {
617 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000618 : getTopOfStack().DefaultMapAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000619 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000620
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000621 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000622 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000623 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000624 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000625 }
626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000627 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000628 void setOrderedRegion(bool IsOrdered, const Expr *Param,
629 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000630 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000631 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000632 else
Richard Smith375dec52019-05-30 23:21:14 +0000633 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000634 }
635 /// Returns true, if region is ordered (has associated 'ordered' clause),
636 /// false - otherwise.
637 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000638 if (const SharingMapTy *Top = getTopOfStackOrNull())
639 return Top->OrderedRegion.hasValue();
640 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000641 }
642 /// Returns optional parameter for the ordered region.
643 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000644 if (const SharingMapTy *Top = getTopOfStackOrNull())
645 if (Top->OrderedRegion.hasValue())
646 return Top->OrderedRegion.getValue();
647 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000648 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000649 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000650 /// 'ordered' clause), false - otherwise.
651 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000652 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
653 return Parent->OrderedRegion.hasValue();
654 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000655 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000656 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000657 std::pair<const Expr *, OMPOrderedClause *>
658 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000659 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
660 if (Parent->OrderedRegion.hasValue())
661 return Parent->OrderedRegion.getValue();
662 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000663 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000664 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000665 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000666 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000667 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000668 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000669 /// 'nowait' clause), false - otherwise.
670 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000671 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
672 return Parent->NowaitRegion;
673 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000674 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000675 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000676 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000677 if (SharingMapTy *Parent = getSecondOnStackOrNull())
678 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000679 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000680 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000681 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000682 const SharingMapTy *Top = getTopOfStackOrNull();
683 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000684 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000685
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000686 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000687 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000688 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000689 if (Val > 1)
690 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000691 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000692 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000693 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000694 const SharingMapTy *Top = getTopOfStackOrNull();
695 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000696 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000697 /// Returns true if the construct is associated with multiple loops.
698 bool hasMutipleLoops() const {
699 const SharingMapTy *Top = getTopOfStackOrNull();
700 return Top ? Top->HasMutipleLoops : false;
701 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000702
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000703 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000704 /// region.
705 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000706 if (SharingMapTy *Parent = getSecondOnStackOrNull())
707 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000708 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000709 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000710 bool hasInnerTeamsRegion() const {
711 return getInnerTeamsRegionLoc().isValid();
712 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000713 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000714 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000715 const SharingMapTy *Top = getTopOfStackOrNull();
716 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000717 }
718
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000719 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000720 const SharingMapTy *Top = getTopOfStackOrNull();
721 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000722 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000723 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000724 const SharingMapTy *Top = getTopOfStackOrNull();
725 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000726 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000727
Samuel Antao4c8035b2016-12-12 18:00:20 +0000728 /// Do the check specified in \a Check to all component lists and return true
729 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000730 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000731 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000732 const llvm::function_ref<
733 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000734 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000735 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty())
737 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000738 auto SI = begin();
739 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000740
741 if (SI == SE)
742 return false;
743
Alexey Bataeve3727102018-04-18 15:57:46 +0000744 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000745 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000746 else
747 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000748
749 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000750 auto MI = SI->MappedExprComponents.find(VD);
751 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000752 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
753 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000754 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000755 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000756 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000757 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000758 }
759
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000760 /// Do the check specified in \a Check to all component lists at a given level
761 /// and return true if any issue is found.
762 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000763 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000764 const llvm::function_ref<
765 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000766 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000767 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000768 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000769 return false;
770
Richard Smith375dec52019-05-30 23:21:14 +0000771 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
772 auto MI = StackElem.MappedExprComponents.find(VD);
773 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000774 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
775 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000776 if (Check(L, MI->second.Kind))
777 return true;
778 return false;
779 }
780
Samuel Antao4c8035b2016-12-12 18:00:20 +0000781 /// Create a new mappable expression component list associated with a given
782 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000783 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000784 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000785 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
786 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000787 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000788 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000789 MEC.Components.resize(MEC.Components.size() + 1);
790 MEC.Components.back().append(Components.begin(), Components.end());
791 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000792 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000793
794 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000795 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000796 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000797 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000798 void addDoacrossDependClause(OMPDependClause *C,
799 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000800 SharingMapTy *Parent = getSecondOnStackOrNull();
801 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
802 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000803 }
804 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
805 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000806 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000807 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000808 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000809 return llvm::make_range(Ref.begin(), Ref.end());
810 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000811 return llvm::make_range(StackElem.DoacrossDepends.end(),
812 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000813 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000814
815 // Store types of classes which have been explicitly mapped
816 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000817 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000818 StackElem.MappedClassesQualTypes.insert(QT);
819 }
820
821 // Return set of mapped classes types
822 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000823 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000824 return StackElem.MappedClassesQualTypes.count(QT) != 0;
825 }
826
Alexey Bataeva495c642019-03-11 19:51:42 +0000827 /// Adds global declare target to the parent target region.
828 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
829 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
830 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
831 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000832 for (auto &Elem : *this) {
833 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
834 Elem.DeclareTargetLinkVarDecls.push_back(E);
835 return;
836 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000837 }
838 }
839
840 /// Returns the list of globals with declare target link if current directive
841 /// is target.
842 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
843 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
844 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000845 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000846 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000847};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000848
849bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
850 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
851}
852
853bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000854 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
855 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000856}
Alexey Bataeve3727102018-04-18 15:57:46 +0000857
Alexey Bataeved09d242014-05-28 05:53:51 +0000858} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000859
Alexey Bataeve3727102018-04-18 15:57:46 +0000860static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000861 if (const auto *FE = dyn_cast<FullExpr>(E))
862 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000863
Alexey Bataeve3727102018-04-18 15:57:46 +0000864 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000865 E = MTE->GetTemporaryExpr();
866
Alexey Bataeve3727102018-04-18 15:57:46 +0000867 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000868 E = Binder->getSubExpr();
869
Alexey Bataeve3727102018-04-18 15:57:46 +0000870 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000871 E = ICE->getSubExprAsWritten();
872 return E->IgnoreParens();
873}
874
Alexey Bataeve3727102018-04-18 15:57:46 +0000875static Expr *getExprAsWritten(Expr *E) {
876 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
877}
878
879static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
880 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
881 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000882 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000883 const auto *VD = dyn_cast<VarDecl>(D);
884 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000885 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000886 VD = VD->getCanonicalDecl();
887 D = VD;
888 } else {
889 assert(FD);
890 FD = FD->getCanonicalDecl();
891 D = FD;
892 }
893 return D;
894}
895
Alexey Bataeve3727102018-04-18 15:57:46 +0000896static ValueDecl *getCanonicalDecl(ValueDecl *D) {
897 return const_cast<ValueDecl *>(
898 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
899}
900
Richard Smith375dec52019-05-30 23:21:14 +0000901DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000902 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000903 D = getCanonicalDecl(D);
904 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000905 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000906 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000907 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000908 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
909 // in a region but not in construct]
910 // File-scope or namespace-scope variables referenced in called routines
911 // in the region are shared unless they appear in a threadprivate
912 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000914 DVar.CKind = OMPC_shared;
915
916 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
917 // in a region but not in construct]
918 // Variables with static storage duration that are declared in called
919 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000920 if (VD && VD->hasGlobalStorage())
921 DVar.CKind = OMPC_shared;
922
923 // Non-static data members are shared by default.
924 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000925 DVar.CKind = OMPC_shared;
926
Alexey Bataev758e55e2013-09-06 18:03:48 +0000927 return DVar;
928 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000929
Alexey Bataevec3da872014-01-31 05:15:34 +0000930 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
931 // in a Construct, C/C++, predetermined, p.1]
932 // Variables with automatic storage duration that are declared in a scope
933 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000934 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
935 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000936 DVar.CKind = OMPC_private;
937 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000938 }
939
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000940 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000941 // Explicitly specified attributes and local variables with predetermined
942 // attributes.
943 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000944 const DSAInfo &Data = Iter->SharingMap.lookup(D);
945 DVar.RefExpr = Data.RefExpr.getPointer();
946 DVar.PrivateCopy = Data.PrivateCopy;
947 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000948 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000949 return DVar;
950 }
951
952 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
953 // in a Construct, C/C++, implicitly determined, p.1]
954 // In a parallel or task construct, the data-sharing attributes of these
955 // variables are determined by the default clause, if present.
956 switch (Iter->DefaultAttr) {
957 case DSA_shared:
958 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000959 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000960 return DVar;
961 case DSA_none:
962 return DVar;
963 case DSA_unspecified:
964 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
965 // in a Construct, implicitly determined, p.2]
966 // In a parallel construct, if no default clause is present, these
967 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000968 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +0000969 if ((isOpenMPParallelDirective(DVar.DKind) &&
970 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +0000971 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000972 DVar.CKind = OMPC_shared;
973 return DVar;
974 }
975
976 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
977 // in a Construct, implicitly determined, p.4]
978 // In a task construct, if no default clause is present, a variable that in
979 // the enclosing context is determined to be shared by all implicit tasks
980 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000981 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000982 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +0000983 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000984 do {
985 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000986 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000987 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000988 // In a task construct, if no default clause is present, a variable
989 // whose data-sharing attribute is not determined by the rules above is
990 // firstprivate.
991 DVarTemp = getDSA(I, D);
992 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000993 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000994 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000995 return DVar;
996 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000997 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000998 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000999 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001000 return DVar;
1001 }
1002 }
1003 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1004 // in a Construct, implicitly determined, p.3]
1005 // For constructs other than task, if no default clause is present, these
1006 // variables inherit their data-sharing attributes from the enclosing
1007 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001008 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001009}
1010
Alexey Bataeve3727102018-04-18 15:57:46 +00001011const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1012 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001013 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001014 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001015 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001016 auto It = StackElem.AlignedMap.find(D);
1017 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001018 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001019 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001020 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001021 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 assert(It->second && "Unexpected nullptr expr in the aligned map");
1023 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001024}
1025
Alexey Bataeve3727102018-04-18 15:57:46 +00001026void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001027 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001028 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001029 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001030 StackElem.LCVMap.try_emplace(
1031 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001032}
1033
Alexey Bataeve3727102018-04-18 15:57:46 +00001034const DSAStackTy::LCDeclInfo
1035DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001037 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001038 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001039 auto It = StackElem.LCVMap.find(D);
1040 if (It != StackElem.LCVMap.end())
1041 return It->second;
1042 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001043}
1044
Alexey Bataeve3727102018-04-18 15:57:46 +00001045const DSAStackTy::LCDeclInfo
1046DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001047 const SharingMapTy *Parent = getSecondOnStackOrNull();
1048 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001049 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001050 auto It = Parent->LCVMap.find(D);
1051 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001052 return It->second;
1053 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001054}
1055
Alexey Bataeve3727102018-04-18 15:57:46 +00001056const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001057 const SharingMapTy *Parent = getSecondOnStackOrNull();
1058 assert(Parent && "Data-sharing attributes stack is empty");
1059 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001060 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001061 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001062 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001063 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001064 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001068 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001069 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001070 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001071 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001072 Data.Attributes = A;
1073 Data.RefExpr.setPointer(E);
1074 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001075 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001076 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001077 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1078 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1079 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1080 (isLoopControlVariable(D).first && A == OMPC_private));
1081 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1082 Data.RefExpr.setInt(/*IntVal=*/true);
1083 return;
1084 }
1085 const bool IsLastprivate =
1086 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1087 Data.Attributes = A;
1088 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1089 Data.PrivateCopy = PrivateCopy;
1090 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001091 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001092 Data.Attributes = A;
1093 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1094 Data.PrivateCopy = nullptr;
1095 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001096 }
1097}
1098
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001099/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001100static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001101 StringRef Name, const AttrVec *Attrs = nullptr,
1102 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001103 DeclContext *DC = SemaRef.CurContext;
1104 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1105 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001106 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001107 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1108 if (Attrs) {
1109 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1110 I != E; ++I)
1111 Decl->addAttr(*I);
1112 }
1113 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001114 if (OrigRef) {
1115 Decl->addAttr(
1116 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1117 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001118 return Decl;
1119}
1120
1121static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1122 SourceLocation Loc,
1123 bool RefersToCapture = false) {
1124 D->setReferenced();
1125 D->markUsed(S.Context);
1126 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1127 SourceLocation(), D, RefersToCapture, Loc, Ty,
1128 VK_LValue);
1129}
1130
Alexey Bataeve3727102018-04-18 15:57:46 +00001131void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001132 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001133 D = getCanonicalDecl(D);
1134 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001135 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001136 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001137 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001138 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001139 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001140 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001141 "Additional reduction info may be specified only once for reduction "
1142 "items.");
1143 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001144 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001145 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001146 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001147 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1148 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001149 TaskgroupReductionRef =
1150 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001151 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001152}
1153
Alexey Bataeve3727102018-04-18 15:57:46 +00001154void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001155 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001156 D = getCanonicalDecl(D);
1157 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001158 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001159 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001160 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001161 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001162 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001163 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001164 "Additional reduction info may be specified only once for reduction "
1165 "items.");
1166 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001167 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001168 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001169 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001170 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1171 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001172 TaskgroupReductionRef =
1173 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001174 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001175}
1176
Alexey Bataeve3727102018-04-18 15:57:46 +00001177const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1178 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1179 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001180 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001181 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001182 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001183 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001184 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001185 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001186 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001187 if (!ReductionData.ReductionOp ||
1188 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001189 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001190 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001191 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001192 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1193 "expression for the descriptor is not "
1194 "set.");
1195 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001196 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1197 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001198 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001199 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001200}
1201
Alexey Bataeve3727102018-04-18 15:57:46 +00001202const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1203 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1204 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001205 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001206 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001207 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001208 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001209 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001210 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001211 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001212 if (!ReductionData.ReductionOp ||
1213 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001214 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001215 SR = ReductionData.ReductionRange;
1216 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001217 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1218 "expression for the descriptor is not "
1219 "set.");
1220 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001221 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1222 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001223 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001224 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001225}
1226
Richard Smith375dec52019-05-30 23:21:14 +00001227bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001228 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001229 for (const_iterator E = end(); I != E; ++I) {
1230 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1231 isOpenMPTargetExecutionDirective(I->Directive)) {
1232 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1233 Scope *CurScope = getCurScope();
1234 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1235 CurScope = CurScope->getParent();
1236 return CurScope != TopScope;
1237 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001238 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001239 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001240}
1241
Joel E. Dennyd2649292019-01-04 22:11:56 +00001242static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1243 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001244 bool *IsClassType = nullptr) {
1245 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001246 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001247 bool IsConstant = Type.isConstant(Context);
1248 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001249 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1250 ? Type->getAsCXXRecordDecl()
1251 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001252 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1253 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1254 RD = CTD->getTemplatedDecl();
1255 if (IsClassType)
1256 *IsClassType = RD;
1257 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1258 RD->hasDefinition() && RD->hasMutableFields());
1259}
1260
Joel E. Dennyd2649292019-01-04 22:11:56 +00001261static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1262 QualType Type, OpenMPClauseKind CKind,
1263 SourceLocation ELoc,
1264 bool AcceptIfMutable = true,
1265 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001266 ASTContext &Context = SemaRef.getASTContext();
1267 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001268 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1269 unsigned Diag = ListItemNotVar
1270 ? diag::err_omp_const_list_item
1271 : IsClassType ? diag::err_omp_const_not_mutable_variable
1272 : diag::err_omp_const_variable;
1273 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1274 if (!ListItemNotVar && D) {
1275 const VarDecl *VD = dyn_cast<VarDecl>(D);
1276 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1277 VarDecl::DeclarationOnly;
1278 SemaRef.Diag(D->getLocation(),
1279 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1280 << D;
1281 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001282 return true;
1283 }
1284 return false;
1285}
1286
Alexey Bataeve3727102018-04-18 15:57:46 +00001287const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1288 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001289 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001290 DSAVarData DVar;
1291
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001292 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001293 auto TI = Threadprivates.find(D);
1294 if (TI != Threadprivates.end()) {
1295 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001296 DVar.CKind = OMPC_threadprivate;
1297 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001298 }
1299 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001300 DVar.RefExpr = buildDeclRefExpr(
1301 SemaRef, VD, D->getType().getNonReferenceType(),
1302 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1303 DVar.CKind = OMPC_threadprivate;
1304 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001305 return DVar;
1306 }
1307 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1308 // in a Construct, C/C++, predetermined, p.1]
1309 // Variables appearing in threadprivate directives are threadprivate.
1310 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1311 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1312 SemaRef.getLangOpts().OpenMPUseTLS &&
1313 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1314 (VD && VD->getStorageClass() == SC_Register &&
1315 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1316 DVar.RefExpr = buildDeclRefExpr(
1317 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1318 DVar.CKind = OMPC_threadprivate;
1319 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1320 return DVar;
1321 }
1322 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1323 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1324 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001325 const_iterator IterTarget =
1326 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1327 return isOpenMPTargetExecutionDirective(Data.Directive);
1328 });
1329 if (IterTarget != end()) {
1330 const_iterator ParentIterTarget = IterTarget + 1;
1331 for (const_iterator Iter = begin();
1332 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001333 if (isOpenMPLocal(VD, Iter)) {
1334 DVar.RefExpr =
1335 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1336 D->getLocation());
1337 DVar.CKind = OMPC_threadprivate;
1338 return DVar;
1339 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001340 }
Richard Smith375dec52019-05-30 23:21:14 +00001341 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001342 auto DSAIter = IterTarget->SharingMap.find(D);
1343 if (DSAIter != IterTarget->SharingMap.end() &&
1344 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1345 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1346 DVar.CKind = OMPC_threadprivate;
1347 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001348 }
Richard Smith375dec52019-05-30 23:21:14 +00001349 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001350 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001351 D, std::distance(ParentIterTarget, End),
1352 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001353 DVar.RefExpr =
1354 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1355 IterTarget->ConstructLoc);
1356 DVar.CKind = OMPC_threadprivate;
1357 return DVar;
1358 }
1359 }
1360 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001361 }
1362
Alexey Bataev4b465392017-04-26 15:06:24 +00001363 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001364 // Not in OpenMP execution region and top scope was already checked.
1365 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001366
Alexey Bataev758e55e2013-09-06 18:03:48 +00001367 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001368 // in a Construct, C/C++, predetermined, p.4]
1369 // Static data members are shared.
1370 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1371 // in a Construct, C/C++, predetermined, p.7]
1372 // Variables with static storage duration that are declared in a scope
1373 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001374 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001375 // Check for explicitly specified attributes.
1376 const_iterator I = begin();
1377 const_iterator EndI = end();
1378 if (FromParent && I != EndI)
1379 ++I;
1380 auto It = I->SharingMap.find(D);
1381 if (It != I->SharingMap.end()) {
1382 const DSAInfo &Data = It->getSecond();
1383 DVar.RefExpr = Data.RefExpr.getPointer();
1384 DVar.PrivateCopy = Data.PrivateCopy;
1385 DVar.CKind = Data.Attributes;
1386 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1387 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001388 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001389 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001390
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001391 DVar.CKind = OMPC_shared;
1392 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001393 }
1394
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001395 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001396 // The predetermined shared attribute for const-qualified types having no
1397 // mutable members was removed after OpenMP 3.1.
1398 if (SemaRef.LangOpts.OpenMP <= 31) {
1399 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1400 // in a Construct, C/C++, predetermined, p.6]
1401 // Variables with const qualified type having no mutable member are
1402 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001403 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001404 // Variables with const-qualified type having no mutable member may be
1405 // listed in a firstprivate clause, even if they are static data members.
1406 DSAVarData DVarTemp = hasInnermostDSA(
1407 D,
1408 [](OpenMPClauseKind C) {
1409 return C == OMPC_firstprivate || C == OMPC_shared;
1410 },
1411 MatchesAlways, FromParent);
1412 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1413 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001414
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001415 DVar.CKind = OMPC_shared;
1416 return DVar;
1417 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001418 }
1419
Alexey Bataev758e55e2013-09-06 18:03:48 +00001420 // Explicitly specified attributes and local variables with predetermined
1421 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001422 const_iterator I = begin();
1423 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001424 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001425 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001426 auto It = I->SharingMap.find(D);
1427 if (It != I->SharingMap.end()) {
1428 const DSAInfo &Data = It->getSecond();
1429 DVar.RefExpr = Data.RefExpr.getPointer();
1430 DVar.PrivateCopy = Data.PrivateCopy;
1431 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001432 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001433 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001434 }
1435
1436 return DVar;
1437}
1438
Alexey Bataeve3727102018-04-18 15:57:46 +00001439const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1440 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001441 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001442 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001443 return getDSA(I, D);
1444 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001445 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001446 const_iterator StartI = begin();
1447 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001448 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001449 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001450 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001451}
1452
Alexey Bataeve3727102018-04-18 15:57:46 +00001453const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001454DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001455 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1456 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001457 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001458 if (isStackEmpty())
1459 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001460 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001461 const_iterator I = begin();
1462 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001463 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001464 ++I;
1465 for (; I != EndI; ++I) {
1466 if (!DPred(I->Directive) &&
1467 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001468 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001469 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001470 DSAVarData DVar = getDSA(NewI, D);
1471 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001472 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001473 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001474 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001475}
1476
Alexey Bataeve3727102018-04-18 15:57:46 +00001477const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001478 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1479 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001480 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001481 if (isStackEmpty())
1482 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001483 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001484 const_iterator StartI = begin();
1485 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001486 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001487 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001488 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001489 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001490 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001491 DSAVarData DVar = getDSA(NewI, D);
1492 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001493}
1494
Alexey Bataevaac108a2015-06-23 04:51:00 +00001495bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001496 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1497 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001498 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001499 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001500 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001501 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1502 auto I = StackElem.SharingMap.find(D);
1503 if (I != StackElem.SharingMap.end() &&
1504 I->getSecond().RefExpr.getPointer() &&
1505 CPred(I->getSecond().Attributes) &&
1506 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001507 return true;
1508 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001509 auto LI = StackElem.LCVMap.find(D);
1510 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001511 return CPred(OMPC_private);
1512 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001513}
1514
Samuel Antao4be30e92015-10-02 17:14:03 +00001515bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001516 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1517 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001518 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001519 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001520 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1521 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001522}
1523
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001524bool DSAStackTy::hasDirective(
1525 const llvm::function_ref<bool(OpenMPDirectiveKind,
1526 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001527 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001528 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001529 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001530 size_t Skip = FromParent ? 2 : 1;
1531 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1532 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001533 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1534 return true;
1535 }
1536 return false;
1537}
1538
Alexey Bataev758e55e2013-09-06 18:03:48 +00001539void Sema::InitDataSharingAttributesStack() {
1540 VarDataSharingAttributesStack = new DSAStackTy(*this);
1541}
1542
1543#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1544
Alexey Bataev4b465392017-04-26 15:06:24 +00001545void Sema::pushOpenMPFunctionRegion() {
1546 DSAStack->pushFunction();
1547}
1548
1549void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1550 DSAStack->popFunction(OldFSI);
1551}
1552
Alexey Bataevc416e642019-02-08 18:02:25 +00001553static bool isOpenMPDeviceDelayedContext(Sema &S) {
1554 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1555 "Expected OpenMP device compilation.");
1556 return !S.isInOpenMPTargetExecutionDirective() &&
1557 !S.isInOpenMPDeclareTargetContext();
1558}
1559
Alexey Bataev729e2422019-08-23 16:11:14 +00001560namespace {
1561/// Status of the function emission on the host/device.
1562enum class FunctionEmissionStatus {
1563 Emitted,
1564 Discarded,
1565 Unknown,
1566};
1567} // anonymous namespace
1568
Alexey Bataevc416e642019-02-08 18:02:25 +00001569Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1570 unsigned DiagID) {
1571 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1572 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001573 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001574 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1575 switch (FES) {
1576 case FunctionEmissionStatus::Emitted:
1577 Kind = DeviceDiagBuilder::K_Immediate;
1578 break;
1579 case FunctionEmissionStatus::Unknown:
1580 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1581 : DeviceDiagBuilder::K_Immediate;
1582 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001583 case FunctionEmissionStatus::TemplateDiscarded:
1584 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001585 Kind = DeviceDiagBuilder::K_Nop;
1586 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001587 case FunctionEmissionStatus::CUDADiscarded:
1588 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1589 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001590 }
1591
1592 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1593}
1594
Alexey Bataev729e2422019-08-23 16:11:14 +00001595Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1596 unsigned DiagID) {
1597 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1598 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001599 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001600 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1601 switch (FES) {
1602 case FunctionEmissionStatus::Emitted:
1603 Kind = DeviceDiagBuilder::K_Immediate;
1604 break;
1605 case FunctionEmissionStatus::Unknown:
1606 Kind = DeviceDiagBuilder::K_Deferred;
1607 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001608 case FunctionEmissionStatus::TemplateDiscarded:
1609 case FunctionEmissionStatus::OMPDiscarded:
1610 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001611 Kind = DeviceDiagBuilder::K_Nop;
1612 break;
1613 }
1614
1615 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001616}
1617
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001618void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1619 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001620 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1621 "Expected OpenMP device compilation.");
1622 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001623 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001624 FunctionDecl *Caller = getCurFunctionDecl();
1625
Alexey Bataev729e2422019-08-23 16:11:14 +00001626 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001627 if (Caller) {
1628 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1629 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1630 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1631 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1632 "CUDADiscarded unexpected in OpenMP device function check");
1633 if ((CallerS == FunctionEmissionStatus::Emitted ||
1634 (!isOpenMPDeviceDelayedContext(*this) &&
1635 CallerS == FunctionEmissionStatus::Unknown)) &&
1636 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1637 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1638 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1639 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1640 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1641 diag::note_omp_marked_device_type_here)
1642 << HostDevTy;
1643 return;
1644 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001645 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001646 // If the caller is known-emitted, mark the callee as known-emitted.
1647 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001648 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1649 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001650 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001651 markKnownEmitted(*this, Caller, Callee, Loc,
1652 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001653 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001654 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001655 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001656 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001657 else if (Caller)
1658 DeviceCallGraph[Caller].insert({Callee, Loc});
1659}
1660
Alexey Bataev729e2422019-08-23 16:11:14 +00001661void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1662 bool CheckCaller) {
1663 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1664 "Expected OpenMP host compilation.");
1665 assert(Callee && "Callee may not be null.");
1666 Callee = Callee->getMostRecentDecl();
1667 FunctionDecl *Caller = getCurFunctionDecl();
1668
1669 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001670 if (Caller) {
1671 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1672 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1673 assert(
1674 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1675 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1676 "CUDADiscarded unexpected in OpenMP host function check");
1677 if (CallerS == FunctionEmissionStatus::Emitted &&
1678 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1679 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1680 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1681 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1682 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1683 diag::note_omp_marked_device_type_here)
1684 << NoHostDevTy;
1685 return;
1686 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001687 }
1688 // If the caller is known-emitted, mark the callee as known-emitted.
1689 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001690 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1691 if ((!CheckCaller && !Caller) ||
1692 (Caller &&
1693 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1694 markKnownEmitted(
1695 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1696 return CheckCaller &&
1697 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1698 });
1699 else if (Caller)
1700 DeviceCallGraph[Caller].insert({Callee, Loc});
1701 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001702}
1703
Alexey Bataev123ad192019-02-27 20:29:45 +00001704void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1705 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1706 "OpenMP device compilation mode is expected.");
1707 QualType Ty = E->getType();
1708 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001709 ((Ty->isFloat128Type() ||
1710 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1711 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001712 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1713 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001714 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1715 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1716 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001717}
1718
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001719bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1720 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001721 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1722
Alexey Bataeve3727102018-04-18 15:57:46 +00001723 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001724 bool IsByRef = true;
1725
1726 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001727 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001728 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001729
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001730 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001731 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001732 // This table summarizes how a given variable should be passed to the device
1733 // given its type and the clauses where it appears. This table is based on
1734 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1735 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1736 //
1737 // =========================================================================
1738 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1739 // | |(tofrom:scalar)| | pvt | | | |
1740 // =========================================================================
1741 // | scl | | | | - | | bycopy|
1742 // | scl | | - | x | - | - | bycopy|
1743 // | scl | | x | - | - | - | null |
1744 // | scl | x | | | - | | byref |
1745 // | scl | x | - | x | - | - | bycopy|
1746 // | scl | x | x | - | - | - | null |
1747 // | scl | | - | - | - | x | byref |
1748 // | scl | x | - | - | - | x | byref |
1749 //
1750 // | agg | n.a. | | | - | | byref |
1751 // | agg | n.a. | - | x | - | - | byref |
1752 // | agg | n.a. | x | - | - | - | null |
1753 // | agg | n.a. | - | - | - | x | byref |
1754 // | agg | n.a. | - | - | - | x[] | byref |
1755 //
1756 // | ptr | n.a. | | | - | | bycopy|
1757 // | ptr | n.a. | - | x | - | - | bycopy|
1758 // | ptr | n.a. | x | - | - | - | null |
1759 // | ptr | n.a. | - | - | - | x | byref |
1760 // | ptr | n.a. | - | - | - | x[] | bycopy|
1761 // | ptr | n.a. | - | - | x | | bycopy|
1762 // | ptr | n.a. | - | - | x | x | bycopy|
1763 // | ptr | n.a. | - | - | x | x[] | bycopy|
1764 // =========================================================================
1765 // Legend:
1766 // scl - scalar
1767 // ptr - pointer
1768 // agg - aggregate
1769 // x - applies
1770 // - - invalid in this combination
1771 // [] - mapped with an array section
1772 // byref - should be mapped by reference
1773 // byval - should be mapped by value
1774 // null - initialize a local variable to null on the device
1775 //
1776 // Observations:
1777 // - All scalar declarations that show up in a map clause have to be passed
1778 // by reference, because they may have been mapped in the enclosing data
1779 // environment.
1780 // - If the scalar value does not fit the size of uintptr, it has to be
1781 // passed by reference, regardless the result in the table above.
1782 // - For pointers mapped by value that have either an implicit map or an
1783 // array section, the runtime library may pass the NULL value to the
1784 // device instead of the value passed to it by the compiler.
1785
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001786 if (Ty->isReferenceType())
1787 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001788
1789 // Locate map clauses and see if the variable being captured is referred to
1790 // in any of those clauses. Here we only care about variables, not fields,
1791 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001792 bool IsVariableAssociatedWithSection = false;
1793
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001794 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001795 D, Level,
1796 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1797 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001798 MapExprComponents,
1799 OpenMPClauseKind WhereFoundClauseKind) {
1800 // Only the map clause information influences how a variable is
1801 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001802 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001803 if (WhereFoundClauseKind != OMPC_map)
1804 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001805
1806 auto EI = MapExprComponents.rbegin();
1807 auto EE = MapExprComponents.rend();
1808
1809 assert(EI != EE && "Invalid map expression!");
1810
1811 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1812 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1813
1814 ++EI;
1815 if (EI == EE)
1816 return false;
1817
1818 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1819 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1820 isa<MemberExpr>(EI->getAssociatedExpression())) {
1821 IsVariableAssociatedWithSection = true;
1822 // There is nothing more we need to know about this variable.
1823 return true;
1824 }
1825
1826 // Keep looking for more map info.
1827 return false;
1828 });
1829
1830 if (IsVariableUsedInMapClause) {
1831 // If variable is identified in a map clause it is always captured by
1832 // reference except if it is a pointer that is dereferenced somehow.
1833 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1834 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001835 // By default, all the data that has a scalar type is mapped by copy
1836 // (except for reduction variables).
1837 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001838 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1839 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001840 !Ty->isScalarType() ||
1841 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1842 DSAStack->hasExplicitDSA(
1843 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001844 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001845 }
1846
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001847 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001848 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001849 ((IsVariableUsedInMapClause &&
1850 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1851 OMPD_target) ||
1852 !DSAStack->hasExplicitDSA(
1853 D,
1854 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1855 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001856 // If the variable is artificial and must be captured by value - try to
1857 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001858 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1859 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001860 }
1861
Samuel Antao86ace552016-04-27 22:40:57 +00001862 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001863 // and alignment, because the runtime library only deals with uintptr types.
1864 // If it does not fit the uintptr size, we need to pass the data by reference
1865 // instead.
1866 if (!IsByRef &&
1867 (Ctx.getTypeSizeInChars(Ty) >
1868 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001869 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001870 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001871 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001872
1873 return IsByRef;
1874}
1875
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001876unsigned Sema::getOpenMPNestingLevel() const {
1877 assert(getLangOpts().OpenMP);
1878 return DSAStack->getNestingLevel();
1879}
1880
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001881bool Sema::isInOpenMPTargetExecutionDirective() const {
1882 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1883 !DSAStack->isClauseParsingMode()) ||
1884 DSAStack->hasDirective(
1885 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1886 SourceLocation) -> bool {
1887 return isOpenMPTargetExecutionDirective(K);
1888 },
1889 false);
1890}
1891
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001892VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1893 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001894 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001895 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001896
Richard Smith0621a8f2019-05-31 00:45:10 +00001897 // If we want to determine whether the variable should be captured from the
1898 // perspective of the current capturing scope, and we've already left all the
1899 // capturing scopes of the top directive on the stack, check from the
1900 // perspective of its parent directive (if any) instead.
1901 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1902 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1903
Samuel Antao4be30e92015-10-02 17:14:03 +00001904 // If we are attempting to capture a global variable in a directive with
1905 // 'target' we return true so that this global is also mapped to the device.
1906 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001907 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001908 if (VD && !VD->hasLocalStorage() &&
1909 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1910 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001911 // Try to mark variable as declare target if it is used in capturing
1912 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001913 if (LangOpts.OpenMP <= 45 &&
1914 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001915 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001916 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001917 } else if (isInOpenMPTargetExecutionDirective()) {
1918 // If the declaration is enclosed in a 'declare target' directive,
1919 // then it should not be captured.
1920 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001921 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001922 return nullptr;
1923 return VD;
1924 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001925 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001926
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001927 if (CheckScopeInfo) {
1928 bool OpenMPFound = false;
1929 for (unsigned I = StopAt + 1; I > 0; --I) {
1930 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1931 if(!isa<CapturingScopeInfo>(FSI))
1932 return nullptr;
1933 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1934 if (RSI->CapRegionKind == CR_OpenMP) {
1935 OpenMPFound = true;
1936 break;
1937 }
1938 }
1939 if (!OpenMPFound)
1940 return nullptr;
1941 }
1942
Alexey Bataev48977c32015-08-04 08:10:48 +00001943 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1944 (!DSAStack->isClauseParsingMode() ||
1945 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001946 auto &&Info = DSAStack->isLoopControlVariable(D);
1947 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001948 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001949 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001950 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001951 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001952 DSAStackTy::DSAVarData DVarPrivate =
1953 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001954 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001955 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00001956 // Threadprivate variables must not be captured.
1957 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
1958 return nullptr;
1959 // The variable is not private or it is the variable in the directive with
1960 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001961 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1962 [](OpenMPDirectiveKind) { return true; },
1963 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001964 if (DVarPrivate.CKind != OMPC_unknown ||
1965 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001966 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001967 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001968 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001969}
1970
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001971void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1972 unsigned Level) const {
1973 SmallVector<OpenMPDirectiveKind, 4> Regions;
1974 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1975 FunctionScopesIndex -= Regions.size();
1976}
1977
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001978void Sema::startOpenMPLoop() {
1979 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1980 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1981 DSAStack->loopInit();
1982}
1983
Alexey Bataevbef93a92019-10-07 18:54:57 +00001984void Sema::startOpenMPCXXRangeFor() {
1985 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1986 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1987 DSAStack->resetPossibleLoopCounter();
1988 DSAStack->loopStart();
1989 }
1990}
1991
Alexey Bataeve3727102018-04-18 15:57:46 +00001992bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001993 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001994 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1995 if (DSAStack->getAssociatedLoops() > 0 &&
1996 !DSAStack->isLoopStarted()) {
1997 DSAStack->resetPossibleLoopCounter(D);
1998 DSAStack->loopStart();
1999 return true;
2000 }
2001 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2002 DSAStack->isLoopControlVariable(D).first) &&
2003 !DSAStack->hasExplicitDSA(
2004 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2005 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2006 return true;
2007 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002008 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2009 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2010 DSAStack->isForceVarCapturing() &&
2011 !DSAStack->hasExplicitDSA(
2012 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2013 return true;
2014 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002015 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002016 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002017 (DSAStack->isClauseParsingMode() &&
2018 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002019 // Consider taskgroup reduction descriptor variable a private to avoid
2020 // possible capture in the region.
2021 (DSAStack->hasExplicitDirective(
2022 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2023 Level) &&
2024 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002025}
2026
Alexey Bataeve3727102018-04-18 15:57:46 +00002027void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2028 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002029 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2030 D = getCanonicalDecl(D);
2031 OpenMPClauseKind OMPC = OMPC_unknown;
2032 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2033 const unsigned NewLevel = I - 1;
2034 if (DSAStack->hasExplicitDSA(D,
2035 [&OMPC](const OpenMPClauseKind K) {
2036 if (isOpenMPPrivate(K)) {
2037 OMPC = K;
2038 return true;
2039 }
2040 return false;
2041 },
2042 NewLevel))
2043 break;
2044 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2045 D, NewLevel,
2046 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2047 OpenMPClauseKind) { return true; })) {
2048 OMPC = OMPC_map;
2049 break;
2050 }
2051 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2052 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002053 OMPC = OMPC_map;
2054 if (D->getType()->isScalarType() &&
2055 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
2056 DefaultMapAttributes::DMA_tofrom_scalar)
2057 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002058 break;
2059 }
2060 }
2061 if (OMPC != OMPC_unknown)
2062 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2063}
2064
Alexey Bataeve3727102018-04-18 15:57:46 +00002065bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2066 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002067 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2068 // Return true if the current level is no longer enclosed in a target region.
2069
Alexey Bataeve3727102018-04-18 15:57:46 +00002070 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002071 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002072 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2073 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002074}
2075
Alexey Bataeved09d242014-05-28 05:53:51 +00002076void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002077
Alexey Bataev729e2422019-08-23 16:11:14 +00002078void Sema::finalizeOpenMPDelayedAnalysis() {
2079 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2080 // Diagnose implicit declare target functions and their callees.
2081 for (const auto &CallerCallees : DeviceCallGraph) {
2082 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2083 OMPDeclareTargetDeclAttr::getDeviceType(
2084 CallerCallees.getFirst()->getMostRecentDecl());
2085 // Ignore host functions during device analyzis.
2086 if (LangOpts.OpenMPIsDevice && DevTy &&
2087 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2088 continue;
2089 // Ignore nohost functions during host analyzis.
2090 if (!LangOpts.OpenMPIsDevice && DevTy &&
2091 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2092 continue;
2093 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2094 &Callee : CallerCallees.getSecond()) {
2095 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2096 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2097 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2098 if (LangOpts.OpenMPIsDevice && DevTy &&
2099 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2100 // Diagnose host function called during device codegen.
2101 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2102 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2103 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2104 << HostDevTy << 0;
2105 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2106 diag::note_omp_marked_device_type_here)
2107 << HostDevTy;
2108 continue;
2109 }
2110 if (!LangOpts.OpenMPIsDevice && DevTy &&
2111 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2112 // Diagnose nohost function called during host codegen.
2113 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2114 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2115 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2116 << NoHostDevTy << 1;
2117 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2118 diag::note_omp_marked_device_type_here)
2119 << NoHostDevTy;
2120 continue;
2121 }
2122 }
2123 }
2124}
2125
Alexey Bataev758e55e2013-09-06 18:03:48 +00002126void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2127 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002128 Scope *CurScope, SourceLocation Loc) {
2129 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002130 PushExpressionEvaluationContext(
2131 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002132}
2133
Alexey Bataevaac108a2015-06-23 04:51:00 +00002134void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2135 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002136}
2137
Alexey Bataevaac108a2015-06-23 04:51:00 +00002138void Sema::EndOpenMPClause() {
2139 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002140}
2141
Alexey Bataeve106f252019-04-01 14:25:31 +00002142static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2143 ArrayRef<OMPClause *> Clauses);
2144
Alexey Bataev758e55e2013-09-06 18:03:48 +00002145void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002146 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2147 // A variable of class type (or array thereof) that appears in a lastprivate
2148 // clause requires an accessible, unambiguous default constructor for the
2149 // class type, unless the list item is also specified in a firstprivate
2150 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002151 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2152 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002153 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2154 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002155 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002156 if (DE->isValueDependent() || DE->isTypeDependent()) {
2157 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002158 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002159 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002160 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002161 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002162 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002163 const DSAStackTy::DSAVarData DVar =
2164 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002165 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002166 // Generate helper private variable and initialize it with the
2167 // default value. The address of the original variable is replaced
2168 // by the address of the new private variable in CodeGen. This new
2169 // variable is not added to IdResolver, so the code in the OpenMP
2170 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002171 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002172 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002173 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002174 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002175 if (VDPrivate->isInvalidDecl()) {
2176 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002177 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002178 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002179 PrivateCopies.push_back(buildDeclRefExpr(
2180 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002181 } else {
2182 // The variable is also a firstprivate, so initialization sequence
2183 // for private copy is generated already.
2184 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002185 }
2186 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002187 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002188 }
2189 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002190 // Check allocate clauses.
2191 if (!CurContext->isDependentContext())
2192 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002193 }
2194
Alexey Bataev758e55e2013-09-06 18:03:48 +00002195 DSAStack->pop();
2196 DiscardCleanupsInEvaluationContext();
2197 PopExpressionEvaluationContext();
2198}
2199
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002200static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2201 Expr *NumIterations, Sema &SemaRef,
2202 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002203
Alexey Bataeva769e072013-03-22 06:34:35 +00002204namespace {
2205
Alexey Bataeve3727102018-04-18 15:57:46 +00002206class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002207private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002208 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002209
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002210public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002211 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002212 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002213 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002214 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002215 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002216 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2217 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002218 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002219 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002220 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002221
2222 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002223 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002224 }
2225
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002226};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002227
Alexey Bataeve3727102018-04-18 15:57:46 +00002228class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002229private:
2230 Sema &SemaRef;
2231
2232public:
2233 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2234 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2235 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002236 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2237 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002238 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2239 SemaRef.getCurScope());
2240 }
2241 return false;
2242 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002243
2244 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002245 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002246 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002247};
2248
Alexey Bataeved09d242014-05-28 05:53:51 +00002249} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002250
2251ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2252 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002253 const DeclarationNameInfo &Id,
2254 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002255 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2256 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2257
2258 if (Lookup.isAmbiguous())
2259 return ExprError();
2260
2261 VarDecl *VD;
2262 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002263 VarDeclFilterCCC CCC(*this);
2264 if (TypoCorrection Corrected =
2265 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2266 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002267 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002268 PDiag(Lookup.empty()
2269 ? diag::err_undeclared_var_use_suggest
2270 : diag::err_omp_expected_var_arg_suggest)
2271 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002272 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002273 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002274 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2275 : diag::err_omp_expected_var_arg)
2276 << Id.getName();
2277 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002278 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002279 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2280 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2281 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2282 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002283 }
2284 Lookup.suppressDiagnostics();
2285
2286 // OpenMP [2.9.2, Syntax, C/C++]
2287 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002288 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002289 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002290 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002291 bool IsDecl =
2292 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002293 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002294 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2295 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002296 return ExprError();
2297 }
2298
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002299 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002300 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002301 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2302 // A threadprivate directive for file-scope variables must appear outside
2303 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002304 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2305 !getCurLexicalContext()->isTranslationUnit()) {
2306 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002307 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002308 bool IsDecl =
2309 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2310 Diag(VD->getLocation(),
2311 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2312 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002313 return ExprError();
2314 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2316 // A threadprivate directive for static class member variables must appear
2317 // in the class definition, in the same scope in which the member
2318 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002319 if (CanonicalVD->isStaticDataMember() &&
2320 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2321 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002322 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002323 bool IsDecl =
2324 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2325 Diag(VD->getLocation(),
2326 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2327 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002328 return ExprError();
2329 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002330 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2331 // A threadprivate directive for namespace-scope variables must appear
2332 // outside any definition or declaration other than the namespace
2333 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002334 if (CanonicalVD->getDeclContext()->isNamespace() &&
2335 (!getCurLexicalContext()->isFileContext() ||
2336 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2337 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002338 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002339 bool IsDecl =
2340 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2341 Diag(VD->getLocation(),
2342 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2343 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002344 return ExprError();
2345 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002346 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2347 // A threadprivate directive for static block-scope variables must appear
2348 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002349 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002350 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002351 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002352 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002353 bool IsDecl =
2354 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2355 Diag(VD->getLocation(),
2356 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2357 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002358 return ExprError();
2359 }
2360
2361 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2362 // A threadprivate directive must lexically precede all references to any
2363 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002364 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2365 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002366 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002367 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002368 return ExprError();
2369 }
2370
2371 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002372 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2373 SourceLocation(), VD,
2374 /*RefersToEnclosingVariableOrCapture=*/false,
2375 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002376}
2377
Alexey Bataeved09d242014-05-28 05:53:51 +00002378Sema::DeclGroupPtrTy
2379Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2380 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002381 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002382 CurContext->addDecl(D);
2383 return DeclGroupPtrTy::make(DeclGroupRef(D));
2384 }
David Blaikie0403cb12016-01-15 23:43:25 +00002385 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002386}
2387
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002388namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002389class LocalVarRefChecker final
2390 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002391 Sema &SemaRef;
2392
2393public:
2394 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002395 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002396 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002397 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002398 diag::err_omp_local_var_in_threadprivate_init)
2399 << E->getSourceRange();
2400 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2401 << VD << VD->getSourceRange();
2402 return true;
2403 }
2404 }
2405 return false;
2406 }
2407 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002408 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002409 if (Child && Visit(Child))
2410 return true;
2411 }
2412 return false;
2413 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002414 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002415};
2416} // namespace
2417
Alexey Bataeved09d242014-05-28 05:53:51 +00002418OMPThreadPrivateDecl *
2419Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002420 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002421 for (Expr *RefExpr : VarList) {
2422 auto *DE = cast<DeclRefExpr>(RefExpr);
2423 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002424 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002425
Alexey Bataev376b4a42016-02-09 09:41:09 +00002426 // Mark variable as used.
2427 VD->setReferenced();
2428 VD->markUsed(Context);
2429
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002430 QualType QType = VD->getType();
2431 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2432 // It will be analyzed later.
2433 Vars.push_back(DE);
2434 continue;
2435 }
2436
Alexey Bataeva769e072013-03-22 06:34:35 +00002437 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2438 // A threadprivate variable must not have an incomplete type.
2439 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002440 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002441 continue;
2442 }
2443
2444 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2445 // A threadprivate variable must not have a reference type.
2446 if (VD->getType()->isReferenceType()) {
2447 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002448 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2449 bool IsDecl =
2450 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2451 Diag(VD->getLocation(),
2452 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2453 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002454 continue;
2455 }
2456
Samuel Antaof8b50122015-07-13 22:54:53 +00002457 // Check if this is a TLS variable. If TLS is not being supported, produce
2458 // the corresponding diagnostic.
2459 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2460 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2461 getLangOpts().OpenMPUseTLS &&
2462 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002463 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2464 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002465 Diag(ILoc, diag::err_omp_var_thread_local)
2466 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002467 bool IsDecl =
2468 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2469 Diag(VD->getLocation(),
2470 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2471 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002472 continue;
2473 }
2474
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002475 // Check if initial value of threadprivate variable reference variable with
2476 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002477 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002478 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002479 if (Checker.Visit(Init))
2480 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002481 }
2482
Alexey Bataeved09d242014-05-28 05:53:51 +00002483 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002484 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002485 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2486 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002487 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002488 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002489 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002490 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002491 if (!Vars.empty()) {
2492 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2493 Vars);
2494 D->setAccess(AS_public);
2495 }
2496 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002497}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002498
Alexey Bataev27ef9512019-03-20 20:14:22 +00002499static OMPAllocateDeclAttr::AllocatorTypeTy
2500getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2501 if (!Allocator)
2502 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2503 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2504 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002505 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002506 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002507 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002508 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002509 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2510 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2511 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002512 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002513 llvm::FoldingSetNodeID AEId, DAEId;
2514 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2515 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2516 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002517 AllocatorKindRes = AllocatorKind;
2518 break;
2519 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002520 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002521 return AllocatorKindRes;
2522}
2523
Alexey Bataeve106f252019-04-01 14:25:31 +00002524static bool checkPreviousOMPAllocateAttribute(
2525 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2526 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2527 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2528 return false;
2529 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2530 Expr *PrevAllocator = A->getAllocator();
2531 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2532 getAllocatorKind(S, Stack, PrevAllocator);
2533 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2534 if (AllocatorsMatch &&
2535 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2536 Allocator && PrevAllocator) {
2537 const Expr *AE = Allocator->IgnoreParenImpCasts();
2538 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2539 llvm::FoldingSetNodeID AEId, PAEId;
2540 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2541 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2542 AllocatorsMatch = AEId == PAEId;
2543 }
2544 if (!AllocatorsMatch) {
2545 SmallString<256> AllocatorBuffer;
2546 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2547 if (Allocator)
2548 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2549 SmallString<256> PrevAllocatorBuffer;
2550 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2551 if (PrevAllocator)
2552 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2553 S.getPrintingPolicy());
2554
2555 SourceLocation AllocatorLoc =
2556 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2557 SourceRange AllocatorRange =
2558 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2559 SourceLocation PrevAllocatorLoc =
2560 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2561 SourceRange PrevAllocatorRange =
2562 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2563 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2564 << (Allocator ? 1 : 0) << AllocatorStream.str()
2565 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2566 << AllocatorRange;
2567 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2568 << PrevAllocatorRange;
2569 return true;
2570 }
2571 return false;
2572}
2573
2574static void
2575applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2576 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2577 Expr *Allocator, SourceRange SR) {
2578 if (VD->hasAttr<OMPAllocateDeclAttr>())
2579 return;
2580 if (Allocator &&
2581 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2582 Allocator->isInstantiationDependent() ||
2583 Allocator->containsUnexpandedParameterPack()))
2584 return;
2585 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2586 Allocator, SR);
2587 VD->addAttr(A);
2588 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2589 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2590}
2591
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002592Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2593 SourceLocation Loc, ArrayRef<Expr *> VarList,
2594 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2595 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2596 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002597 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002598 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2599 // allocate directives that appear in a target region must specify an
2600 // allocator clause unless a requires directive with the dynamic_allocators
2601 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002602 if (LangOpts.OpenMPIsDevice &&
2603 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002604 targetDiag(Loc, diag::err_expected_allocator_clause);
2605 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002606 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002607 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002608 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2609 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002610 SmallVector<Expr *, 8> Vars;
2611 for (Expr *RefExpr : VarList) {
2612 auto *DE = cast<DeclRefExpr>(RefExpr);
2613 auto *VD = cast<VarDecl>(DE->getDecl());
2614
2615 // Check if this is a TLS variable or global register.
2616 if (VD->getTLSKind() != VarDecl::TLS_None ||
2617 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2618 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2619 !VD->isLocalVarDecl()))
2620 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002621
Alexey Bataev282555a2019-03-19 20:33:44 +00002622 // If the used several times in the allocate directive, the same allocator
2623 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002624 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2625 AllocatorKind, Allocator))
2626 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002627
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002628 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2629 // If a list item has a static storage type, the allocator expression in the
2630 // allocator clause must be a constant expression that evaluates to one of
2631 // the predefined memory allocator values.
2632 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002633 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002634 Diag(Allocator->getExprLoc(),
2635 diag::err_omp_expected_predefined_allocator)
2636 << Allocator->getSourceRange();
2637 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2638 VarDecl::DeclarationOnly;
2639 Diag(VD->getLocation(),
2640 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2641 << VD;
2642 continue;
2643 }
2644 }
2645
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002646 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002647 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2648 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002649 }
2650 if (Vars.empty())
2651 return nullptr;
2652 if (!Owner)
2653 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002654 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002655 D->setAccess(AS_public);
2656 Owner->addDecl(D);
2657 return DeclGroupPtrTy::make(DeclGroupRef(D));
2658}
2659
2660Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002661Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2662 ArrayRef<OMPClause *> ClauseList) {
2663 OMPRequiresDecl *D = nullptr;
2664 if (!CurContext->isFileContext()) {
2665 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2666 } else {
2667 D = CheckOMPRequiresDecl(Loc, ClauseList);
2668 if (D) {
2669 CurContext->addDecl(D);
2670 DSAStack->addRequiresDecl(D);
2671 }
2672 }
2673 return DeclGroupPtrTy::make(DeclGroupRef(D));
2674}
2675
2676OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2677 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002678 /// For target specific clauses, the requires directive cannot be
2679 /// specified after the handling of any of the target regions in the
2680 /// current compilation unit.
2681 ArrayRef<SourceLocation> TargetLocations =
2682 DSAStack->getEncounteredTargetLocs();
2683 if (!TargetLocations.empty()) {
2684 for (const OMPClause *CNew : ClauseList) {
2685 // Check if any of the requires clauses affect target regions.
2686 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2687 isa<OMPUnifiedAddressClause>(CNew) ||
2688 isa<OMPReverseOffloadClause>(CNew) ||
2689 isa<OMPDynamicAllocatorsClause>(CNew)) {
2690 Diag(Loc, diag::err_omp_target_before_requires)
2691 << getOpenMPClauseName(CNew->getClauseKind());
2692 for (SourceLocation TargetLoc : TargetLocations) {
2693 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2694 }
2695 }
2696 }
2697 }
2698
Kelvin Li1408f912018-09-26 04:28:39 +00002699 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2700 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2701 ClauseList);
2702 return nullptr;
2703}
2704
Alexey Bataeve3727102018-04-18 15:57:46 +00002705static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2706 const ValueDecl *D,
2707 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002708 bool IsLoopIterVar = false) {
2709 if (DVar.RefExpr) {
2710 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2711 << getOpenMPClauseName(DVar.CKind);
2712 return;
2713 }
2714 enum {
2715 PDSA_StaticMemberShared,
2716 PDSA_StaticLocalVarShared,
2717 PDSA_LoopIterVarPrivate,
2718 PDSA_LoopIterVarLinear,
2719 PDSA_LoopIterVarLastprivate,
2720 PDSA_ConstVarShared,
2721 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002722 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002723 PDSA_LocalVarPrivate,
2724 PDSA_Implicit
2725 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002726 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002727 auto ReportLoc = D->getLocation();
2728 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002729 if (IsLoopIterVar) {
2730 if (DVar.CKind == OMPC_private)
2731 Reason = PDSA_LoopIterVarPrivate;
2732 else if (DVar.CKind == OMPC_lastprivate)
2733 Reason = PDSA_LoopIterVarLastprivate;
2734 else
2735 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002736 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2737 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002738 Reason = PDSA_TaskVarFirstprivate;
2739 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002740 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002741 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002742 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002743 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002744 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002745 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002746 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002747 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002748 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002749 ReportHint = true;
2750 Reason = PDSA_LocalVarPrivate;
2751 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002752 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002753 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002754 << Reason << ReportHint
2755 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2756 } else if (DVar.ImplicitDSALoc.isValid()) {
2757 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2758 << getOpenMPClauseName(DVar.CKind);
2759 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002760}
2761
Alexey Bataev758e55e2013-09-06 18:03:48 +00002762namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002763class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002764 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002765 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002766 bool ErrorFound = false;
2767 CapturedStmt *CS = nullptr;
2768 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2769 llvm::SmallVector<Expr *, 4> ImplicitMap;
2770 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2771 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002772
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002773 void VisitSubCaptures(OMPExecutableDirective *S) {
2774 // Check implicitly captured variables.
2775 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2776 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002777 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002778 }
2779
Alexey Bataev758e55e2013-09-06 18:03:48 +00002780public:
2781 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002782 if (E->isTypeDependent() || E->isValueDependent() ||
2783 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2784 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002785 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002786 // Check the datasharing rules for the expressions in the clauses.
2787 if (!CS) {
2788 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2789 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2790 Visit(CED->getInit());
2791 return;
2792 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002793 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2794 // Do not analyze internal variables and do not enclose them into
2795 // implicit clauses.
2796 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002797 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002798 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002799 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002800 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002801
Alexey Bataeve3727102018-04-18 15:57:46 +00002802 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002803 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002804 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002805 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002806
Alexey Bataevafe50572017-10-06 17:00:28 +00002807 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002808 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002809 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002810 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002811 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2812 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002813 return;
2814
Alexey Bataeve3727102018-04-18 15:57:46 +00002815 SourceLocation ELoc = E->getExprLoc();
2816 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002817 // The default(none) clause requires that each variable that is referenced
2818 // in the construct, and does not have a predetermined data-sharing
2819 // attribute, must have its data-sharing attribute explicitly determined
2820 // by being listed in a data-sharing attribute clause.
2821 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002822 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002823 VarsWithInheritedDSA.count(VD) == 0) {
2824 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825 return;
2826 }
2827
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002828 if (isOpenMPTargetExecutionDirective(DKind) &&
2829 !Stack->isLoopControlVariable(VD).first) {
2830 if (!Stack->checkMappableExprComponentListsForDecl(
2831 VD, /*CurrentRegionOnly=*/true,
2832 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2833 StackComponents,
2834 OpenMPClauseKind) {
2835 // Variable is used if it has been marked as an array, array
2836 // section or the variable iself.
2837 return StackComponents.size() == 1 ||
2838 std::all_of(
2839 std::next(StackComponents.rbegin()),
2840 StackComponents.rend(),
2841 [](const OMPClauseMappableExprCommon::
2842 MappableComponent &MC) {
2843 return MC.getAssociatedDeclaration() ==
2844 nullptr &&
2845 (isa<OMPArraySectionExpr>(
2846 MC.getAssociatedExpression()) ||
2847 isa<ArraySubscriptExpr>(
2848 MC.getAssociatedExpression()));
2849 });
2850 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002851 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002852 // By default lambdas are captured as firstprivates.
2853 if (const auto *RD =
2854 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002855 IsFirstprivate = RD->isLambda();
2856 IsFirstprivate =
2857 IsFirstprivate ||
2858 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002859 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002860 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002861 ImplicitFirstprivate.emplace_back(E);
2862 else
2863 ImplicitMap.emplace_back(E);
2864 return;
2865 }
2866 }
2867
Alexey Bataev758e55e2013-09-06 18:03:48 +00002868 // OpenMP [2.9.3.6, Restrictions, p.2]
2869 // A list item that appears in a reduction clause of the innermost
2870 // enclosing worksharing or parallel construct may not be accessed in an
2871 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002872 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002873 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2874 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002875 return isOpenMPParallelDirective(K) ||
2876 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2877 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002878 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002879 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002880 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002881 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002882 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002883 return;
2884 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002885
2886 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002887 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002888 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002889 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002890 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002891 return;
2892 }
2893
2894 // Store implicitly used globals with declare target link for parent
2895 // target.
2896 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2897 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2898 Stack->addToParentTargetRegionLinkGlobals(E);
2899 return;
2900 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002901 }
2902 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002903 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002904 if (E->isTypeDependent() || E->isValueDependent() ||
2905 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2906 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002907 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002908 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002909 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002910 if (!FD)
2911 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002912 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002913 // Check if the variable has explicit DSA set and stop analysis if it
2914 // so.
2915 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2916 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002917
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002918 if (isOpenMPTargetExecutionDirective(DKind) &&
2919 !Stack->isLoopControlVariable(FD).first &&
2920 !Stack->checkMappableExprComponentListsForDecl(
2921 FD, /*CurrentRegionOnly=*/true,
2922 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2923 StackComponents,
2924 OpenMPClauseKind) {
2925 return isa<CXXThisExpr>(
2926 cast<MemberExpr>(
2927 StackComponents.back().getAssociatedExpression())
2928 ->getBase()
2929 ->IgnoreParens());
2930 })) {
2931 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2932 // A bit-field cannot appear in a map clause.
2933 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002934 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002935 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002936
2937 // Check to see if the member expression is referencing a class that
2938 // has already been explicitly mapped
2939 if (Stack->isClassPreviouslyMapped(TE->getType()))
2940 return;
2941
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002942 ImplicitMap.emplace_back(E);
2943 return;
2944 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002945
Alexey Bataeve3727102018-04-18 15:57:46 +00002946 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002947 // OpenMP [2.9.3.6, Restrictions, p.2]
2948 // A list item that appears in a reduction clause of the innermost
2949 // enclosing worksharing or parallel construct may not be accessed in
2950 // an explicit task.
2951 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002952 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2953 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002954 return isOpenMPParallelDirective(K) ||
2955 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2956 },
2957 /*FromParent=*/true);
2958 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2959 ErrorFound = true;
2960 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002961 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002962 return;
2963 }
2964
2965 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002966 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002967 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002968 !Stack->isLoopControlVariable(FD).first) {
2969 // Check if there is a captured expression for the current field in the
2970 // region. Do not mark it as firstprivate unless there is no captured
2971 // expression.
2972 // TODO: try to make it firstprivate.
2973 if (DVar.CKind != OMPC_unknown)
2974 ImplicitFirstprivate.push_back(E);
2975 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002976 return;
2977 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002978 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002979 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002980 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002981 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002982 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002983 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002984 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2985 if (!Stack->checkMappableExprComponentListsForDecl(
2986 VD, /*CurrentRegionOnly=*/true,
2987 [&CurComponents](
2988 OMPClauseMappableExprCommon::MappableExprComponentListRef
2989 StackComponents,
2990 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002991 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002992 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002993 for (const auto &SC : llvm::reverse(StackComponents)) {
2994 // Do both expressions have the same kind?
2995 if (CCI->getAssociatedExpression()->getStmtClass() !=
2996 SC.getAssociatedExpression()->getStmtClass())
2997 if (!(isa<OMPArraySectionExpr>(
2998 SC.getAssociatedExpression()) &&
2999 isa<ArraySubscriptExpr>(
3000 CCI->getAssociatedExpression())))
3001 return false;
3002
Alexey Bataeve3727102018-04-18 15:57:46 +00003003 const Decl *CCD = CCI->getAssociatedDeclaration();
3004 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003005 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3006 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3007 if (SCD != CCD)
3008 return false;
3009 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003010 if (CCI == CCE)
3011 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003012 }
3013 return true;
3014 })) {
3015 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003016 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003017 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003018 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003019 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003020 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003021 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003022 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003023 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003024 // for task|target directives.
3025 // Skip analysis of arguments of implicitly defined map clause for target
3026 // directives.
3027 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3028 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003029 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003030 if (CC)
3031 Visit(CC);
3032 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003033 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003034 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003035 // Check implicitly captured variables.
3036 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003037 }
3038 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003039 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003040 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003041 // Check implicitly captured variables in the task-based directives to
3042 // check if they must be firstprivatized.
3043 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003044 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003045 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003046 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003047
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003048 void visitSubCaptures(CapturedStmt *S) {
3049 for (const CapturedStmt::Capture &Cap : S->captures()) {
3050 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3051 continue;
3052 VarDecl *VD = Cap.getCapturedVar();
3053 // Do not try to map the variable if it or its sub-component was mapped
3054 // already.
3055 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3056 Stack->checkMappableExprComponentListsForDecl(
3057 VD, /*CurrentRegionOnly=*/true,
3058 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3059 OpenMPClauseKind) { return true; }))
3060 continue;
3061 DeclRefExpr *DRE = buildDeclRefExpr(
3062 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3063 Cap.getLocation(), /*RefersToCapture=*/true);
3064 Visit(DRE);
3065 }
3066 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003067 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003068 ArrayRef<Expr *> getImplicitFirstprivate() const {
3069 return ImplicitFirstprivate;
3070 }
3071 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00003072 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003073 return VarsWithInheritedDSA;
3074 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003075
Alexey Bataev7ff55242014-06-19 09:13:45 +00003076 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003077 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3078 // Process declare target link variables for the target directives.
3079 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3080 for (DeclRefExpr *E : Stack->getLinkGlobals())
3081 Visit(E);
3082 }
3083 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003084};
Alexey Bataeved09d242014-05-28 05:53:51 +00003085} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003086
Alexey Bataevbae9a792014-06-27 10:37:06 +00003087void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003088 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003089 case OMPD_parallel:
3090 case OMPD_parallel_for:
3091 case OMPD_parallel_for_simd:
3092 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003093 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003094 case OMPD_teams_distribute:
3095 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003096 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003097 QualType KmpInt32PtrTy =
3098 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003099 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003100 std::make_pair(".global_tid.", KmpInt32PtrTy),
3101 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3102 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003103 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003104 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3105 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003106 break;
3107 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003108 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003109 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003110 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003111 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003112 case OMPD_target_teams_distribute:
3113 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003114 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3115 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3118 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003119 FunctionProtoType::ExtProtoInfo EPI;
3120 EPI.Variadic = true;
3121 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3122 Sema::CapturedParamNameType Params[] = {
3123 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003124 std::make_pair(".part_id.", KmpInt32PtrTy),
3125 std::make_pair(".privates.", VoidPtrTy),
3126 std::make_pair(
3127 ".copy_fn.",
3128 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003129 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3130 std::make_pair(StringRef(), QualType()) // __context with shared vars
3131 };
3132 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003133 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003134 // Mark this captured region as inlined, because we don't use outlined
3135 // function directly.
3136 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3137 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003138 Context, {}, AttributeCommonInfo::AS_Keyword,
3139 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003140 Sema::CapturedParamNameType ParamsTarget[] = {
3141 std::make_pair(StringRef(), QualType()) // __context with shared vars
3142 };
3143 // Start a captured region for 'target' with no implicit parameters.
3144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003145 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003146 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003147 std::make_pair(".global_tid.", KmpInt32PtrTy),
3148 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003151 // Start a captured region for 'teams' or 'parallel'. Both regions have
3152 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003153 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003154 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003155 break;
3156 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003157 case OMPD_target:
3158 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003159 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3160 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3161 QualType KmpInt32PtrTy =
3162 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3163 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003164 FunctionProtoType::ExtProtoInfo EPI;
3165 EPI.Variadic = true;
3166 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3167 Sema::CapturedParamNameType Params[] = {
3168 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003169 std::make_pair(".part_id.", KmpInt32PtrTy),
3170 std::make_pair(".privates.", VoidPtrTy),
3171 std::make_pair(
3172 ".copy_fn.",
3173 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003174 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3175 std::make_pair(StringRef(), QualType()) // __context with shared vars
3176 };
3177 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003178 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003179 // Mark this captured region as inlined, because we don't use outlined
3180 // function directly.
3181 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3182 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003183 Context, {}, AttributeCommonInfo::AS_Keyword,
3184 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003185 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003186 std::make_pair(StringRef(), QualType()),
3187 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003188 break;
3189 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003190 case OMPD_simd:
3191 case OMPD_for:
3192 case OMPD_for_simd:
3193 case OMPD_sections:
3194 case OMPD_section:
3195 case OMPD_single:
3196 case OMPD_master:
3197 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003198 case OMPD_taskgroup:
3199 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003200 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003201 case OMPD_ordered:
3202 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003203 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003204 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003205 std::make_pair(StringRef(), QualType()) // __context with shared vars
3206 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003207 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3208 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003209 break;
3210 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003211 case OMPD_task: {
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 Bataev3ae88e22015-05-22 08:56:35 +00003217 FunctionProtoType::ExtProtoInfo EPI;
3218 EPI.Variadic = true;
3219 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003220 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003221 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 Bataev48591dd2016-04-20 04:01:36 +00003227 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003228 std::make_pair(StringRef(), QualType()) // __context with shared vars
3229 };
3230 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3231 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003232 // Mark this captured region as inlined, because we don't use outlined
3233 // function directly.
3234 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3235 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003236 Context, {}, AttributeCommonInfo::AS_Keyword,
3237 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003238 break;
3239 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003240 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003241 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003242 case OMPD_master_taskloop:
3243 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003244 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003245 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3246 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003247 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003248 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3249 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003250 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003251 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3252 .withConst();
3253 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3254 QualType KmpInt32PtrTy =
3255 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3256 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003257 FunctionProtoType::ExtProtoInfo EPI;
3258 EPI.Variadic = true;
3259 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003260 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003261 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003262 std::make_pair(".part_id.", KmpInt32PtrTy),
3263 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003264 std::make_pair(
3265 ".copy_fn.",
3266 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3267 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3268 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003269 std::make_pair(".ub.", KmpUInt64Ty),
3270 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003271 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003272 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003273 std::make_pair(StringRef(), QualType()) // __context with shared vars
3274 };
3275 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3276 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003277 // Mark this captured region as inlined, because we don't use outlined
3278 // function directly.
3279 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3280 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003281 Context, {}, AttributeCommonInfo::AS_Keyword,
3282 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003283 break;
3284 }
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003285 case OMPD_parallel_master_taskloop: {
3286 QualType KmpInt32Ty =
3287 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3288 .withConst();
3289 QualType KmpUInt64Ty =
3290 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3291 .withConst();
3292 QualType KmpInt64Ty =
3293 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3294 .withConst();
3295 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3296 QualType KmpInt32PtrTy =
3297 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3298 Sema::CapturedParamNameType ParamsParallel[] = {
3299 std::make_pair(".global_tid.", KmpInt32PtrTy),
3300 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3301 std::make_pair(StringRef(), QualType()) // __context with shared vars
3302 };
3303 // Start a captured region for 'parallel'.
3304 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3305 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3306 QualType Args[] = {VoidPtrTy};
3307 FunctionProtoType::ExtProtoInfo EPI;
3308 EPI.Variadic = true;
3309 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3310 Sema::CapturedParamNameType Params[] = {
3311 std::make_pair(".global_tid.", KmpInt32Ty),
3312 std::make_pair(".part_id.", KmpInt32PtrTy),
3313 std::make_pair(".privates.", VoidPtrTy),
3314 std::make_pair(
3315 ".copy_fn.",
3316 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3317 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3318 std::make_pair(".lb.", KmpUInt64Ty),
3319 std::make_pair(".ub.", KmpUInt64Ty),
3320 std::make_pair(".st.", KmpInt64Ty),
3321 std::make_pair(".liter.", KmpInt32Ty),
3322 std::make_pair(".reductions.", VoidPtrTy),
3323 std::make_pair(StringRef(), QualType()) // __context with shared vars
3324 };
3325 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3326 Params, /*OpenMPCaptureLevel=*/2);
3327 // Mark this captured region as inlined, because we don't use outlined
3328 // function directly.
3329 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3330 AlwaysInlineAttr::CreateImplicit(
3331 Context, {}, AttributeCommonInfo::AS_Keyword,
3332 AlwaysInlineAttr::Keyword_forceinline));
3333 break;
3334 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003335 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003336 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003337 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003338 QualType KmpInt32PtrTy =
3339 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3340 Sema::CapturedParamNameType Params[] = {
3341 std::make_pair(".global_tid.", KmpInt32PtrTy),
3342 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003343 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3344 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003345 std::make_pair(StringRef(), QualType()) // __context with shared vars
3346 };
3347 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3348 Params);
3349 break;
3350 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003351 case OMPD_target_teams_distribute_parallel_for:
3352 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003353 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003354 QualType KmpInt32PtrTy =
3355 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003356 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003357
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003358 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003359 FunctionProtoType::ExtProtoInfo EPI;
3360 EPI.Variadic = true;
3361 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3362 Sema::CapturedParamNameType Params[] = {
3363 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003364 std::make_pair(".part_id.", KmpInt32PtrTy),
3365 std::make_pair(".privates.", VoidPtrTy),
3366 std::make_pair(
3367 ".copy_fn.",
3368 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003369 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3370 std::make_pair(StringRef(), QualType()) // __context with shared vars
3371 };
3372 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003373 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003374 // Mark this captured region as inlined, because we don't use outlined
3375 // function directly.
3376 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3377 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003378 Context, {}, AttributeCommonInfo::AS_Keyword,
3379 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003380 Sema::CapturedParamNameType ParamsTarget[] = {
3381 std::make_pair(StringRef(), QualType()) // __context with shared vars
3382 };
3383 // Start a captured region for 'target' with no implicit parameters.
3384 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003385 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003386
3387 Sema::CapturedParamNameType ParamsTeams[] = {
3388 std::make_pair(".global_tid.", KmpInt32PtrTy),
3389 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3390 std::make_pair(StringRef(), QualType()) // __context with shared vars
3391 };
3392 // Start a captured region for 'target' with no implicit parameters.
3393 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003394 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003395
3396 Sema::CapturedParamNameType ParamsParallel[] = {
3397 std::make_pair(".global_tid.", KmpInt32PtrTy),
3398 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003399 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3400 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003401 std::make_pair(StringRef(), QualType()) // __context with shared vars
3402 };
3403 // Start a captured region for 'teams' or 'parallel'. Both regions have
3404 // the same implicit parameters.
3405 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003406 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003407 break;
3408 }
3409
Alexey Bataev46506272017-12-05 17:41:34 +00003410 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003411 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003412 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003413 QualType KmpInt32PtrTy =
3414 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3415
3416 Sema::CapturedParamNameType ParamsTeams[] = {
3417 std::make_pair(".global_tid.", KmpInt32PtrTy),
3418 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3419 std::make_pair(StringRef(), QualType()) // __context with shared vars
3420 };
3421 // Start a captured region for 'target' with no implicit parameters.
3422 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003423 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003424
3425 Sema::CapturedParamNameType ParamsParallel[] = {
3426 std::make_pair(".global_tid.", KmpInt32PtrTy),
3427 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003428 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3429 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003430 std::make_pair(StringRef(), QualType()) // __context with shared vars
3431 };
3432 // Start a captured region for 'teams' or 'parallel'. Both regions have
3433 // the same implicit parameters.
3434 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003435 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003436 break;
3437 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003438 case OMPD_target_update:
3439 case OMPD_target_enter_data:
3440 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003441 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3442 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3443 QualType KmpInt32PtrTy =
3444 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3445 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003446 FunctionProtoType::ExtProtoInfo EPI;
3447 EPI.Variadic = true;
3448 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3449 Sema::CapturedParamNameType Params[] = {
3450 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003451 std::make_pair(".part_id.", KmpInt32PtrTy),
3452 std::make_pair(".privates.", VoidPtrTy),
3453 std::make_pair(
3454 ".copy_fn.",
3455 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003456 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3457 std::make_pair(StringRef(), QualType()) // __context with shared vars
3458 };
3459 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3460 Params);
3461 // Mark this captured region as inlined, because we don't use outlined
3462 // function directly.
3463 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3464 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003465 Context, {}, AttributeCommonInfo::AS_Keyword,
3466 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003467 break;
3468 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003469 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003470 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003471 case OMPD_taskyield:
3472 case OMPD_barrier:
3473 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003474 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003475 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003476 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003477 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003478 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003479 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003480 case OMPD_declare_target:
3481 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003482 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003483 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003484 llvm_unreachable("OpenMP Directive is not allowed");
3485 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003486 llvm_unreachable("Unknown OpenMP directive");
3487 }
3488}
3489
Alexey Bataev0e100032019-10-14 16:44:01 +00003490int Sema::getNumberOfConstructScopes(unsigned Level) const {
3491 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3492}
3493
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003494int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3495 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3496 getOpenMPCaptureRegions(CaptureRegions, DKind);
3497 return CaptureRegions.size();
3498}
3499
Alexey Bataev3392d762016-02-16 11:18:12 +00003500static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003501 Expr *CaptureExpr, bool WithInit,
3502 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003503 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003504 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003505 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003506 QualType Ty = Init->getType();
3507 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003508 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003509 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003510 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003511 Ty = C.getPointerType(Ty);
3512 ExprResult Res =
3513 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3514 if (!Res.isUsable())
3515 return nullptr;
3516 Init = Res.get();
3517 }
Alexey Bataev61205072016-03-02 04:57:40 +00003518 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003519 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003520 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003521 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003522 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003523 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003524 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003525 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003526 return CED;
3527}
3528
Alexey Bataev61205072016-03-02 04:57:40 +00003529static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3530 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003531 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003532 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003533 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003534 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003535 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3536 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003537 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003538 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003539}
3540
Alexey Bataev5a3af132016-03-29 08:58:54 +00003541static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003542 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003543 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003544 OMPCapturedExprDecl *CD = buildCaptureDecl(
3545 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3546 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003547 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3548 CaptureExpr->getExprLoc());
3549 }
3550 ExprResult Res = Ref;
3551 if (!S.getLangOpts().CPlusPlus &&
3552 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003553 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003554 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003555 if (!Res.isUsable())
3556 return ExprError();
3557 }
3558 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003559}
3560
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003561namespace {
3562// OpenMP directives parsed in this section are represented as a
3563// CapturedStatement with an associated statement. If a syntax error
3564// is detected during the parsing of the associated statement, the
3565// compiler must abort processing and close the CapturedStatement.
3566//
3567// Combined directives such as 'target parallel' have more than one
3568// nested CapturedStatements. This RAII ensures that we unwind out
3569// of all the nested CapturedStatements when an error is found.
3570class CaptureRegionUnwinderRAII {
3571private:
3572 Sema &S;
3573 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003574 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003575
3576public:
3577 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3578 OpenMPDirectiveKind DKind)
3579 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3580 ~CaptureRegionUnwinderRAII() {
3581 if (ErrorFound) {
3582 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3583 while (--ThisCaptureLevel >= 0)
3584 S.ActOnCapturedRegionError();
3585 }
3586 }
3587};
3588} // namespace
3589
Alexey Bataevb600ae32019-07-01 17:46:52 +00003590void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3591 // Capture variables captured by reference in lambdas for target-based
3592 // directives.
3593 if (!CurContext->isDependentContext() &&
3594 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3595 isOpenMPTargetDataManagementDirective(
3596 DSAStack->getCurrentDirective()))) {
3597 QualType Type = V->getType();
3598 if (const auto *RD = Type.getCanonicalType()
3599 .getNonReferenceType()
3600 ->getAsCXXRecordDecl()) {
3601 bool SavedForceCaptureByReferenceInTargetExecutable =
3602 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3603 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3604 /*V=*/true);
3605 if (RD->isLambda()) {
3606 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3607 FieldDecl *ThisCapture;
3608 RD->getCaptureFields(Captures, ThisCapture);
3609 for (const LambdaCapture &LC : RD->captures()) {
3610 if (LC.getCaptureKind() == LCK_ByRef) {
3611 VarDecl *VD = LC.getCapturedVar();
3612 DeclContext *VDC = VD->getDeclContext();
3613 if (!VDC->Encloses(CurContext))
3614 continue;
3615 MarkVariableReferenced(LC.getLocation(), VD);
3616 } else if (LC.getCaptureKind() == LCK_This) {
3617 QualType ThisTy = getCurrentThisType();
3618 if (!ThisTy.isNull() &&
3619 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3620 CheckCXXThisCapture(LC.getLocation());
3621 }
3622 }
3623 }
3624 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3625 SavedForceCaptureByReferenceInTargetExecutable);
3626 }
3627 }
3628}
3629
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003630StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3631 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003632 bool ErrorFound = false;
3633 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3634 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003635 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003636 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003637 return StmtError();
3638 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003639
Alexey Bataev2ba67042017-11-28 21:11:44 +00003640 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3641 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003642 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003643 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003644 SmallVector<const OMPLinearClause *, 4> LCs;
3645 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003646 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003647 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003648 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3649 Clause->getClauseKind() == OMPC_in_reduction) {
3650 // Capture taskgroup task_reduction descriptors inside the tasking regions
3651 // with the corresponding in_reduction items.
3652 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003653 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003654 if (E)
3655 MarkDeclarationsReferencedInExpr(E);
3656 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003657 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003658 Clause->getClauseKind() == OMPC_copyprivate ||
3659 (getLangOpts().OpenMPUseTLS &&
3660 getASTContext().getTargetInfo().isTLSSupported() &&
3661 Clause->getClauseKind() == OMPC_copyin)) {
3662 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003663 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003664 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003665 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003666 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003667 }
3668 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003669 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003670 } else if (CaptureRegions.size() > 1 ||
3671 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003672 if (auto *C = OMPClauseWithPreInit::get(Clause))
3673 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003674 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003675 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003676 MarkDeclarationsReferencedInExpr(E);
3677 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003678 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003679 if (Clause->getClauseKind() == OMPC_schedule)
3680 SC = cast<OMPScheduleClause>(Clause);
3681 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003682 OC = cast<OMPOrderedClause>(Clause);
3683 else if (Clause->getClauseKind() == OMPC_linear)
3684 LCs.push_back(cast<OMPLinearClause>(Clause));
3685 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003686 // OpenMP, 2.7.1 Loop Construct, Restrictions
3687 // The nonmonotonic modifier cannot be specified if an ordered clause is
3688 // specified.
3689 if (SC &&
3690 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3691 SC->getSecondScheduleModifier() ==
3692 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3693 OC) {
3694 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3695 ? SC->getFirstScheduleModifierLoc()
3696 : SC->getSecondScheduleModifierLoc(),
3697 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003698 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003699 ErrorFound = true;
3700 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003701 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003702 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003703 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003704 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003705 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003706 ErrorFound = true;
3707 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003708 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3709 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3710 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003711 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003712 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3713 ErrorFound = true;
3714 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003715 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003716 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003717 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003718 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003719 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003720 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003721 // Mark all variables in private list clauses as used in inner region.
3722 // Required for proper codegen of combined directives.
3723 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003724 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003725 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003726 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3727 // Find the particular capture region for the clause if the
3728 // directive is a combined one with multiple capture regions.
3729 // If the directive is not a combined one, the capture region
3730 // associated with the clause is OMPD_unknown and is generated
3731 // only once.
3732 if (CaptureRegion == ThisCaptureRegion ||
3733 CaptureRegion == OMPD_unknown) {
3734 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003735 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003736 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3737 }
3738 }
3739 }
3740 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003741 if (++CompletedRegions == CaptureRegions.size())
3742 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003743 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003744 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003745 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003746}
3747
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003748static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3749 OpenMPDirectiveKind CancelRegion,
3750 SourceLocation StartLoc) {
3751 // CancelRegion is only needed for cancel and cancellation_point.
3752 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3753 return false;
3754
3755 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3756 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3757 return false;
3758
3759 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3760 << getOpenMPDirectiveName(CancelRegion);
3761 return true;
3762}
3763
Alexey Bataeve3727102018-04-18 15:57:46 +00003764static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003765 OpenMPDirectiveKind CurrentRegion,
3766 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003767 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003768 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003769 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003770 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3771 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003772 bool NestingProhibited = false;
3773 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003774 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003775 enum {
3776 NoRecommend,
3777 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003778 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003779 ShouldBeInTargetRegion,
3780 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003781 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003782 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003783 // OpenMP [2.16, Nesting of Regions]
3784 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003785 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003786 // An ordered construct with the simd clause is the only OpenMP
3787 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003788 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003789 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3790 // message.
3791 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3792 ? diag::err_omp_prohibited_region_simd
3793 : diag::warn_omp_nesting_simd);
3794 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003795 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003796 if (ParentRegion == OMPD_atomic) {
3797 // OpenMP [2.16, Nesting of Regions]
3798 // OpenMP constructs may not be nested inside an atomic region.
3799 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3800 return true;
3801 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003802 if (CurrentRegion == OMPD_section) {
3803 // OpenMP [2.7.2, sections Construct, Restrictions]
3804 // Orphaned section directives are prohibited. That is, the section
3805 // directives must appear within the sections construct and must not be
3806 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003807 if (ParentRegion != OMPD_sections &&
3808 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003809 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3810 << (ParentRegion != OMPD_unknown)
3811 << getOpenMPDirectiveName(ParentRegion);
3812 return true;
3813 }
3814 return false;
3815 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003816 // Allow some constructs (except teams and cancellation constructs) to be
3817 // orphaned (they could be used in functions, called from OpenMP regions
3818 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003819 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003820 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3821 CurrentRegion != OMPD_cancellation_point &&
3822 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003823 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003824 if (CurrentRegion == OMPD_cancellation_point ||
3825 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003826 // OpenMP [2.16, Nesting of Regions]
3827 // A cancellation point construct for which construct-type-clause is
3828 // taskgroup must be nested inside a task construct. A cancellation
3829 // point construct for which construct-type-clause is not taskgroup must
3830 // be closely nested inside an OpenMP construct that matches the type
3831 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003832 // A cancel construct for which construct-type-clause is taskgroup must be
3833 // nested inside a task construct. A cancel construct for which
3834 // construct-type-clause is not taskgroup must be closely nested inside an
3835 // OpenMP construct that matches the type specified in
3836 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003837 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003838 !((CancelRegion == OMPD_parallel &&
3839 (ParentRegion == OMPD_parallel ||
3840 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003841 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003842 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003843 ParentRegion == OMPD_target_parallel_for ||
3844 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003845 ParentRegion == OMPD_teams_distribute_parallel_for ||
3846 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003847 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3848 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003849 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3850 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003851 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003852 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003853 // OpenMP [2.16, Nesting of Regions]
3854 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003855 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003856 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003857 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003858 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3859 // OpenMP [2.16, Nesting of Regions]
3860 // A critical region may not be nested (closely or otherwise) inside a
3861 // critical region with the same name. Note that this restriction is not
3862 // sufficient to prevent deadlock.
3863 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003864 bool DeadLock = Stack->hasDirective(
3865 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3866 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003867 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003868 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3869 PreviousCriticalLoc = Loc;
3870 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003871 }
3872 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003873 },
3874 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003875 if (DeadLock) {
3876 SemaRef.Diag(StartLoc,
3877 diag::err_omp_prohibited_region_critical_same_name)
3878 << CurrentName.getName();
3879 if (PreviousCriticalLoc.isValid())
3880 SemaRef.Diag(PreviousCriticalLoc,
3881 diag::note_omp_previous_critical_region);
3882 return true;
3883 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003884 } else if (CurrentRegion == OMPD_barrier) {
3885 // OpenMP [2.16, Nesting of Regions]
3886 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003887 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003888 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3889 isOpenMPTaskingDirective(ParentRegion) ||
3890 ParentRegion == OMPD_master ||
3891 ParentRegion == OMPD_critical ||
3892 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003893 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003894 !isOpenMPParallelDirective(CurrentRegion) &&
3895 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003896 // OpenMP [2.16, Nesting of Regions]
3897 // A worksharing region may not be closely nested inside a worksharing,
3898 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003899 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3900 isOpenMPTaskingDirective(ParentRegion) ||
3901 ParentRegion == OMPD_master ||
3902 ParentRegion == OMPD_critical ||
3903 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003904 Recommend = ShouldBeInParallelRegion;
3905 } else if (CurrentRegion == OMPD_ordered) {
3906 // OpenMP [2.16, Nesting of Regions]
3907 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003908 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003909 // An ordered region must be closely nested inside a loop region (or
3910 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003911 // OpenMP [2.8.1,simd Construct, Restrictions]
3912 // An ordered construct with the simd clause is the only OpenMP construct
3913 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003914 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003915 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003916 !(isOpenMPSimdDirective(ParentRegion) ||
3917 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003918 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003919 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003920 // OpenMP [2.16, Nesting of Regions]
3921 // If specified, a teams construct must be contained within a target
3922 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00003923 NestingProhibited =
3924 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3925 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3926 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00003927 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003928 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003929 }
Kelvin Libf594a52016-12-17 05:48:59 +00003930 if (!NestingProhibited &&
3931 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3932 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3933 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003934 // OpenMP [2.16, Nesting of Regions]
3935 // distribute, parallel, parallel sections, parallel workshare, and the
3936 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3937 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003938 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3939 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003940 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003941 }
David Majnemer9d168222016-08-05 17:44:54 +00003942 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003943 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003944 // OpenMP 4.5 [2.17 Nesting of Regions]
3945 // The region associated with the distribute construct must be strictly
3946 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003947 NestingProhibited =
3948 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003949 Recommend = ShouldBeInTeamsRegion;
3950 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003951 if (!NestingProhibited &&
3952 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3953 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3954 // OpenMP 4.5 [2.17 Nesting of Regions]
3955 // If a target, target update, target data, target enter data, or
3956 // target exit data construct is encountered during execution of a
3957 // target region, the behavior is unspecified.
3958 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003959 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003960 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003961 if (isOpenMPTargetExecutionDirective(K)) {
3962 OffendingRegion = K;
3963 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003964 }
3965 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003966 },
3967 false /* don't skip top directive */);
3968 CloseNesting = false;
3969 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003970 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003971 if (OrphanSeen) {
3972 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3973 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3974 } else {
3975 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3976 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3977 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3978 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003979 return true;
3980 }
3981 }
3982 return false;
3983}
3984
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003985static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3986 ArrayRef<OMPClause *> Clauses,
3987 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3988 bool ErrorFound = false;
3989 unsigned NamedModifiersNumber = 0;
3990 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3991 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003992 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003993 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003994 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3995 // At most one if clause without a directive-name-modifier can appear on
3996 // the directive.
3997 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3998 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003999 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004000 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4001 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4002 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004003 } else if (CurNM != OMPD_unknown) {
4004 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004005 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004006 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004007 FoundNameModifiers[CurNM] = IC;
4008 if (CurNM == OMPD_unknown)
4009 continue;
4010 // Check if the specified name modifier is allowed for the current
4011 // directive.
4012 // At most one if clause with the particular directive-name-modifier can
4013 // appear on the directive.
4014 bool MatchFound = false;
4015 for (auto NM : AllowedNameModifiers) {
4016 if (CurNM == NM) {
4017 MatchFound = true;
4018 break;
4019 }
4020 }
4021 if (!MatchFound) {
4022 S.Diag(IC->getNameModifierLoc(),
4023 diag::err_omp_wrong_if_directive_name_modifier)
4024 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4025 ErrorFound = true;
4026 }
4027 }
4028 }
4029 // If any if clause on the directive includes a directive-name-modifier then
4030 // all if clauses on the directive must include a directive-name-modifier.
4031 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4032 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004033 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004034 diag::err_omp_no_more_if_clause);
4035 } else {
4036 std::string Values;
4037 std::string Sep(", ");
4038 unsigned AllowedCnt = 0;
4039 unsigned TotalAllowedNum =
4040 AllowedNameModifiers.size() - NamedModifiersNumber;
4041 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4042 ++Cnt) {
4043 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4044 if (!FoundNameModifiers[NM]) {
4045 Values += "'";
4046 Values += getOpenMPDirectiveName(NM);
4047 Values += "'";
4048 if (AllowedCnt + 2 == TotalAllowedNum)
4049 Values += " or ";
4050 else if (AllowedCnt + 1 != TotalAllowedNum)
4051 Values += Sep;
4052 ++AllowedCnt;
4053 }
4054 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004055 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004056 diag::err_omp_unnamed_if_clause)
4057 << (TotalAllowedNum > 1) << Values;
4058 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004059 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004060 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4061 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004062 ErrorFound = true;
4063 }
4064 return ErrorFound;
4065}
4066
Alexey Bataeve106f252019-04-01 14:25:31 +00004067static std::pair<ValueDecl *, bool>
4068getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4069 SourceRange &ERange, bool AllowArraySection = false) {
4070 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4071 RefExpr->containsUnexpandedParameterPack())
4072 return std::make_pair(nullptr, true);
4073
4074 // OpenMP [3.1, C/C++]
4075 // A list item is a variable name.
4076 // OpenMP [2.9.3.3, Restrictions, p.1]
4077 // A variable that is part of another variable (as an array or
4078 // structure element) cannot appear in a private clause.
4079 RefExpr = RefExpr->IgnoreParens();
4080 enum {
4081 NoArrayExpr = -1,
4082 ArraySubscript = 0,
4083 OMPArraySection = 1
4084 } IsArrayExpr = NoArrayExpr;
4085 if (AllowArraySection) {
4086 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4087 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4088 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4089 Base = TempASE->getBase()->IgnoreParenImpCasts();
4090 RefExpr = Base;
4091 IsArrayExpr = ArraySubscript;
4092 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4093 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4094 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4095 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4096 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4097 Base = TempASE->getBase()->IgnoreParenImpCasts();
4098 RefExpr = Base;
4099 IsArrayExpr = OMPArraySection;
4100 }
4101 }
4102 ELoc = RefExpr->getExprLoc();
4103 ERange = RefExpr->getSourceRange();
4104 RefExpr = RefExpr->IgnoreParenImpCasts();
4105 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4106 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4107 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4108 (S.getCurrentThisType().isNull() || !ME ||
4109 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4110 !isa<FieldDecl>(ME->getMemberDecl()))) {
4111 if (IsArrayExpr != NoArrayExpr) {
4112 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4113 << ERange;
4114 } else {
4115 S.Diag(ELoc,
4116 AllowArraySection
4117 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4118 : diag::err_omp_expected_var_name_member_expr)
4119 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4120 }
4121 return std::make_pair(nullptr, false);
4122 }
4123 return std::make_pair(
4124 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4125}
4126
4127static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004128 ArrayRef<OMPClause *> Clauses) {
4129 assert(!S.CurContext->isDependentContext() &&
4130 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004131 auto AllocateRange =
4132 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004133 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4134 DeclToCopy;
4135 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4136 return isOpenMPPrivate(C->getClauseKind());
4137 });
4138 for (OMPClause *Cl : PrivateRange) {
4139 MutableArrayRef<Expr *>::iterator I, It, Et;
4140 if (Cl->getClauseKind() == OMPC_private) {
4141 auto *PC = cast<OMPPrivateClause>(Cl);
4142 I = PC->private_copies().begin();
4143 It = PC->varlist_begin();
4144 Et = PC->varlist_end();
4145 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4146 auto *PC = cast<OMPFirstprivateClause>(Cl);
4147 I = PC->private_copies().begin();
4148 It = PC->varlist_begin();
4149 Et = PC->varlist_end();
4150 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4151 auto *PC = cast<OMPLastprivateClause>(Cl);
4152 I = PC->private_copies().begin();
4153 It = PC->varlist_begin();
4154 Et = PC->varlist_end();
4155 } else if (Cl->getClauseKind() == OMPC_linear) {
4156 auto *PC = cast<OMPLinearClause>(Cl);
4157 I = PC->privates().begin();
4158 It = PC->varlist_begin();
4159 Et = PC->varlist_end();
4160 } else if (Cl->getClauseKind() == OMPC_reduction) {
4161 auto *PC = cast<OMPReductionClause>(Cl);
4162 I = PC->privates().begin();
4163 It = PC->varlist_begin();
4164 Et = PC->varlist_end();
4165 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4166 auto *PC = cast<OMPTaskReductionClause>(Cl);
4167 I = PC->privates().begin();
4168 It = PC->varlist_begin();
4169 Et = PC->varlist_end();
4170 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4171 auto *PC = cast<OMPInReductionClause>(Cl);
4172 I = PC->privates().begin();
4173 It = PC->varlist_begin();
4174 Et = PC->varlist_end();
4175 } else {
4176 llvm_unreachable("Expected private clause.");
4177 }
4178 for (Expr *E : llvm::make_range(It, Et)) {
4179 if (!*I) {
4180 ++I;
4181 continue;
4182 }
4183 SourceLocation ELoc;
4184 SourceRange ERange;
4185 Expr *SimpleRefExpr = E;
4186 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4187 /*AllowArraySection=*/true);
4188 DeclToCopy.try_emplace(Res.first,
4189 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4190 ++I;
4191 }
4192 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004193 for (OMPClause *C : AllocateRange) {
4194 auto *AC = cast<OMPAllocateClause>(C);
4195 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4196 getAllocatorKind(S, Stack, AC->getAllocator());
4197 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4198 // For task, taskloop or target directives, allocation requests to memory
4199 // allocators with the trait access set to thread result in unspecified
4200 // behavior.
4201 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4202 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4203 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4204 S.Diag(AC->getAllocator()->getExprLoc(),
4205 diag::warn_omp_allocate_thread_on_task_target_directive)
4206 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004207 }
4208 for (Expr *E : AC->varlists()) {
4209 SourceLocation ELoc;
4210 SourceRange ERange;
4211 Expr *SimpleRefExpr = E;
4212 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4213 ValueDecl *VD = Res.first;
4214 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4215 if (!isOpenMPPrivate(Data.CKind)) {
4216 S.Diag(E->getExprLoc(),
4217 diag::err_omp_expected_private_copy_for_allocate);
4218 continue;
4219 }
4220 VarDecl *PrivateVD = DeclToCopy[VD];
4221 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4222 AllocatorKind, AC->getAllocator()))
4223 continue;
4224 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4225 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004226 }
4227 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004228}
4229
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004230StmtResult Sema::ActOnOpenMPExecutableDirective(
4231 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4232 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4233 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004234 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004235 // First check CancelRegion which is then used in checkNestingOfRegions.
4236 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4237 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004238 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004239 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004240
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004241 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004242 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004243 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004244 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004245 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004246 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4247
4248 // Check default data sharing attributes for referenced variables.
4249 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004250 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4251 Stmt *S = AStmt;
4252 while (--ThisCaptureLevel >= 0)
4253 S = cast<CapturedStmt>(S)->getCapturedStmt();
4254 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004255 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4256 !isOpenMPTaskingDirective(Kind)) {
4257 // Visit subcaptures to generate implicit clauses for captured vars.
4258 auto *CS = cast<CapturedStmt>(AStmt);
4259 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4260 getOpenMPCaptureRegions(CaptureRegions, Kind);
4261 // Ignore outer tasking regions for target directives.
4262 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4263 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4264 DSAChecker.visitSubCaptures(CS);
4265 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004266 if (DSAChecker.isErrorFound())
4267 return StmtError();
4268 // Generate list of implicitly defined firstprivate variables.
4269 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004270
Alexey Bataev88202be2017-07-27 13:20:36 +00004271 SmallVector<Expr *, 4> ImplicitFirstprivates(
4272 DSAChecker.getImplicitFirstprivate().begin(),
4273 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004274 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4275 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004276 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004277 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004278 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004279 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004280 if (E)
4281 ImplicitFirstprivates.emplace_back(E);
4282 }
4283 }
4284 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004285 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004286 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4287 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004288 ClausesWithImplicit.push_back(Implicit);
4289 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004290 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004291 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004292 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004293 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004294 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004295 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004296 CXXScopeSpec MapperIdScopeSpec;
4297 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004298 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004299 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4300 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4301 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004302 ClausesWithImplicit.emplace_back(Implicit);
4303 ErrorFound |=
4304 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004306 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004307 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004308 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004309 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004310
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004311 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004312 switch (Kind) {
4313 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004314 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4315 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004316 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004317 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004318 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004319 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4320 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004321 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004322 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004323 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4324 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004325 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004326 case OMPD_for_simd:
4327 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4328 EndLoc, VarsWithInheritedDSA);
4329 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004330 case OMPD_sections:
4331 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4332 EndLoc);
4333 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004334 case OMPD_section:
4335 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004336 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004337 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4338 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004339 case OMPD_single:
4340 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4341 EndLoc);
4342 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004343 case OMPD_master:
4344 assert(ClausesWithImplicit.empty() &&
4345 "No clauses are allowed for 'omp master' directive");
4346 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4347 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004348 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004349 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4350 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004351 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004352 case OMPD_parallel_for:
4353 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4354 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004355 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004356 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004357 case OMPD_parallel_for_simd:
4358 Res = ActOnOpenMPParallelForSimdDirective(
4359 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004360 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004361 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004362 case OMPD_parallel_sections:
4363 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4364 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004365 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004366 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004367 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004368 Res =
4369 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004370 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004371 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004372 case OMPD_taskyield:
4373 assert(ClausesWithImplicit.empty() &&
4374 "No clauses are allowed for 'omp taskyield' directive");
4375 assert(AStmt == nullptr &&
4376 "No associated statement allowed for 'omp taskyield' directive");
4377 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4378 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004379 case OMPD_barrier:
4380 assert(ClausesWithImplicit.empty() &&
4381 "No clauses are allowed for 'omp barrier' directive");
4382 assert(AStmt == nullptr &&
4383 "No associated statement allowed for 'omp barrier' directive");
4384 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4385 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004386 case OMPD_taskwait:
4387 assert(ClausesWithImplicit.empty() &&
4388 "No clauses are allowed for 'omp taskwait' directive");
4389 assert(AStmt == nullptr &&
4390 "No associated statement allowed for 'omp taskwait' directive");
4391 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4392 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004393 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004394 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4395 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004396 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004397 case OMPD_flush:
4398 assert(AStmt == nullptr &&
4399 "No associated statement allowed for 'omp flush' directive");
4400 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4401 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004402 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004403 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4404 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004405 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004406 case OMPD_atomic:
4407 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4408 EndLoc);
4409 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004410 case OMPD_teams:
4411 Res =
4412 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4413 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004414 case OMPD_target:
4415 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4416 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004417 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004418 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004419 case OMPD_target_parallel:
4420 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4421 StartLoc, EndLoc);
4422 AllowedNameModifiers.push_back(OMPD_target);
4423 AllowedNameModifiers.push_back(OMPD_parallel);
4424 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004425 case OMPD_target_parallel_for:
4426 Res = ActOnOpenMPTargetParallelForDirective(
4427 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4428 AllowedNameModifiers.push_back(OMPD_target);
4429 AllowedNameModifiers.push_back(OMPD_parallel);
4430 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004431 case OMPD_cancellation_point:
4432 assert(ClausesWithImplicit.empty() &&
4433 "No clauses are allowed for 'omp cancellation point' directive");
4434 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4435 "cancellation point' directive");
4436 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4437 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004438 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004439 assert(AStmt == nullptr &&
4440 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004441 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4442 CancelRegion);
4443 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004444 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004445 case OMPD_target_data:
4446 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4447 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004448 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004449 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004450 case OMPD_target_enter_data:
4451 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004452 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004453 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4454 break;
Samuel Antao72590762016-01-19 20:04:50 +00004455 case OMPD_target_exit_data:
4456 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004457 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004458 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4459 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004460 case OMPD_taskloop:
4461 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4462 EndLoc, VarsWithInheritedDSA);
4463 AllowedNameModifiers.push_back(OMPD_taskloop);
4464 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004465 case OMPD_taskloop_simd:
4466 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4467 EndLoc, VarsWithInheritedDSA);
4468 AllowedNameModifiers.push_back(OMPD_taskloop);
4469 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004470 case OMPD_master_taskloop:
4471 Res = ActOnOpenMPMasterTaskLoopDirective(
4472 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4473 AllowedNameModifiers.push_back(OMPD_taskloop);
4474 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004475 case OMPD_master_taskloop_simd:
4476 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4477 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4478 AllowedNameModifiers.push_back(OMPD_taskloop);
4479 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004480 case OMPD_parallel_master_taskloop:
4481 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4482 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4483 AllowedNameModifiers.push_back(OMPD_taskloop);
4484 AllowedNameModifiers.push_back(OMPD_parallel);
4485 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004486 case OMPD_distribute:
4487 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4488 EndLoc, VarsWithInheritedDSA);
4489 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004490 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004491 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4492 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004493 AllowedNameModifiers.push_back(OMPD_target_update);
4494 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004495 case OMPD_distribute_parallel_for:
4496 Res = ActOnOpenMPDistributeParallelForDirective(
4497 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4498 AllowedNameModifiers.push_back(OMPD_parallel);
4499 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004500 case OMPD_distribute_parallel_for_simd:
4501 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4502 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4503 AllowedNameModifiers.push_back(OMPD_parallel);
4504 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004505 case OMPD_distribute_simd:
4506 Res = ActOnOpenMPDistributeSimdDirective(
4507 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4508 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004509 case OMPD_target_parallel_for_simd:
4510 Res = ActOnOpenMPTargetParallelForSimdDirective(
4511 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4512 AllowedNameModifiers.push_back(OMPD_target);
4513 AllowedNameModifiers.push_back(OMPD_parallel);
4514 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004515 case OMPD_target_simd:
4516 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4517 EndLoc, VarsWithInheritedDSA);
4518 AllowedNameModifiers.push_back(OMPD_target);
4519 break;
Kelvin Li02532872016-08-05 14:37:37 +00004520 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004521 Res = ActOnOpenMPTeamsDistributeDirective(
4522 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004523 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004524 case OMPD_teams_distribute_simd:
4525 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4526 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4527 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004528 case OMPD_teams_distribute_parallel_for_simd:
4529 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4530 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4531 AllowedNameModifiers.push_back(OMPD_parallel);
4532 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004533 case OMPD_teams_distribute_parallel_for:
4534 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4535 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4536 AllowedNameModifiers.push_back(OMPD_parallel);
4537 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004538 case OMPD_target_teams:
4539 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4540 EndLoc);
4541 AllowedNameModifiers.push_back(OMPD_target);
4542 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004543 case OMPD_target_teams_distribute:
4544 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4545 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4546 AllowedNameModifiers.push_back(OMPD_target);
4547 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004548 case OMPD_target_teams_distribute_parallel_for:
4549 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4550 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4551 AllowedNameModifiers.push_back(OMPD_target);
4552 AllowedNameModifiers.push_back(OMPD_parallel);
4553 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004554 case OMPD_target_teams_distribute_parallel_for_simd:
4555 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4556 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4557 AllowedNameModifiers.push_back(OMPD_target);
4558 AllowedNameModifiers.push_back(OMPD_parallel);
4559 break;
Kelvin Lida681182017-01-10 18:08:18 +00004560 case OMPD_target_teams_distribute_simd:
4561 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4562 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4563 AllowedNameModifiers.push_back(OMPD_target);
4564 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004565 case OMPD_declare_target:
4566 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004567 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004568 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004569 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004570 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004571 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004572 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004573 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004574 llvm_unreachable("OpenMP Directive is not allowed");
4575 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004576 llvm_unreachable("Unknown OpenMP directive");
4577 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004578
Roman Lebedevb5700602019-03-20 16:32:36 +00004579 ErrorFound = Res.isInvalid() || ErrorFound;
4580
Alexey Bataev412254a2019-05-09 18:44:53 +00004581 // Check variables in the clauses if default(none) was specified.
4582 if (DSAStack->getDefaultDSA() == DSA_none) {
4583 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4584 for (OMPClause *C : Clauses) {
4585 switch (C->getClauseKind()) {
4586 case OMPC_num_threads:
4587 case OMPC_dist_schedule:
4588 // Do not analyse if no parent teams directive.
4589 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4590 break;
4591 continue;
4592 case OMPC_if:
4593 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4594 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4595 break;
4596 continue;
4597 case OMPC_schedule:
4598 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004599 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004600 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004601 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004602 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004603 // Do not analyze if no parent parallel directive.
4604 if (isOpenMPParallelDirective(DSAStack->getCurrentDirective()))
4605 break;
4606 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004607 case OMPC_ordered:
4608 case OMPC_device:
4609 case OMPC_num_teams:
4610 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004611 case OMPC_hint:
4612 case OMPC_collapse:
4613 case OMPC_safelen:
4614 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004615 case OMPC_default:
4616 case OMPC_proc_bind:
4617 case OMPC_private:
4618 case OMPC_firstprivate:
4619 case OMPC_lastprivate:
4620 case OMPC_shared:
4621 case OMPC_reduction:
4622 case OMPC_task_reduction:
4623 case OMPC_in_reduction:
4624 case OMPC_linear:
4625 case OMPC_aligned:
4626 case OMPC_copyin:
4627 case OMPC_copyprivate:
4628 case OMPC_nowait:
4629 case OMPC_untied:
4630 case OMPC_mergeable:
4631 case OMPC_allocate:
4632 case OMPC_read:
4633 case OMPC_write:
4634 case OMPC_update:
4635 case OMPC_capture:
4636 case OMPC_seq_cst:
4637 case OMPC_depend:
4638 case OMPC_threads:
4639 case OMPC_simd:
4640 case OMPC_map:
4641 case OMPC_nogroup:
4642 case OMPC_defaultmap:
4643 case OMPC_to:
4644 case OMPC_from:
4645 case OMPC_use_device_ptr:
4646 case OMPC_is_device_ptr:
4647 continue;
4648 case OMPC_allocator:
4649 case OMPC_flush:
4650 case OMPC_threadprivate:
4651 case OMPC_uniform:
4652 case OMPC_unknown:
4653 case OMPC_unified_address:
4654 case OMPC_unified_shared_memory:
4655 case OMPC_reverse_offload:
4656 case OMPC_dynamic_allocators:
4657 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004658 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004659 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004660 llvm_unreachable("Unexpected clause");
4661 }
4662 for (Stmt *CC : C->children()) {
4663 if (CC)
4664 DSAChecker.Visit(CC);
4665 }
4666 }
4667 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4668 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4669 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004670 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004671 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4672 continue;
4673 ErrorFound = true;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004674 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4675 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004676 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004677 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004678
4679 if (!AllowedNameModifiers.empty())
4680 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4681 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004682
Alexey Bataeved09d242014-05-28 05:53:51 +00004683 if (ErrorFound)
4684 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004685
4686 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4687 Res.getAs<OMPExecutableDirective>()
4688 ->getStructuredBlock()
4689 ->setIsOMPStructuredBlock(true);
4690 }
4691
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004692 if (!CurContext->isDependentContext() &&
4693 isOpenMPTargetExecutionDirective(Kind) &&
4694 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4695 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4696 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4697 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4698 // Register target to DSA Stack.
4699 DSAStack->addTargetDirLocation(StartLoc);
4700 }
4701
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004702 return Res;
4703}
4704
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004705Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4706 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004707 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004708 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4709 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004710 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004711 assert(Linears.size() == LinModifiers.size());
4712 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004713 if (!DG || DG.get().isNull())
4714 return DeclGroupPtrTy();
4715
Alexey Bataevd158cf62019-09-13 20:18:17 +00004716 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004717 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004718 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4719 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004720 return DG;
4721 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004722 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004723 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4724 ADecl = FTD->getTemplatedDecl();
4725
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004726 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4727 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004728 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004729 return DeclGroupPtrTy();
4730 }
4731
Alexey Bataev2af33e32016-04-07 12:45:37 +00004732 // OpenMP [2.8.2, declare simd construct, Description]
4733 // The parameter of the simdlen clause must be a constant positive integer
4734 // expression.
4735 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004736 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004737 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004738 // OpenMP [2.8.2, declare simd construct, Description]
4739 // The special this pointer can be used as if was one of the arguments to the
4740 // function in any of the linear, aligned, or uniform clauses.
4741 // The uniform clause declares one or more arguments to have an invariant
4742 // value for all concurrent invocations of the function in the execution of a
4743 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004744 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4745 const Expr *UniformedLinearThis = nullptr;
4746 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004747 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004748 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4749 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004750 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4751 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004752 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004753 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004754 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004755 }
4756 if (isa<CXXThisExpr>(E)) {
4757 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004758 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004759 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004760 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4761 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004762 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004763 // OpenMP [2.8.2, declare simd construct, Description]
4764 // The aligned clause declares that the object to which each list item points
4765 // is aligned to the number of bytes expressed in the optional parameter of
4766 // the aligned clause.
4767 // The special this pointer can be used as if was one of the arguments to the
4768 // function in any of the linear, aligned, or uniform clauses.
4769 // The type of list items appearing in the aligned clause must be array,
4770 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004771 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4772 const Expr *AlignedThis = nullptr;
4773 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004774 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004775 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4776 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4777 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004778 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4779 FD->getParamDecl(PVD->getFunctionScopeIndex())
4780 ->getCanonicalDecl() == CanonPVD) {
4781 // OpenMP [2.8.1, simd construct, Restrictions]
4782 // A list-item cannot appear in more than one aligned clause.
4783 if (AlignedArgs.count(CanonPVD) > 0) {
4784 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4785 << 1 << E->getSourceRange();
4786 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4787 diag::note_omp_explicit_dsa)
4788 << getOpenMPClauseName(OMPC_aligned);
4789 continue;
4790 }
4791 AlignedArgs[CanonPVD] = E;
4792 QualType QTy = PVD->getType()
4793 .getNonReferenceType()
4794 .getUnqualifiedType()
4795 .getCanonicalType();
4796 const Type *Ty = QTy.getTypePtrOrNull();
4797 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4798 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4799 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4800 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4801 }
4802 continue;
4803 }
4804 }
4805 if (isa<CXXThisExpr>(E)) {
4806 if (AlignedThis) {
4807 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4808 << 2 << E->getSourceRange();
4809 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4810 << getOpenMPClauseName(OMPC_aligned);
4811 }
4812 AlignedThis = E;
4813 continue;
4814 }
4815 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4816 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4817 }
4818 // The optional parameter of the aligned clause, alignment, must be a constant
4819 // positive integer expression. If no optional parameter is specified,
4820 // implementation-defined default alignments for SIMD instructions on the
4821 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004822 SmallVector<const Expr *, 4> NewAligns;
4823 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004824 ExprResult Align;
4825 if (E)
4826 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4827 NewAligns.push_back(Align.get());
4828 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004829 // OpenMP [2.8.2, declare simd construct, Description]
4830 // The linear clause declares one or more list items to be private to a SIMD
4831 // lane and to have a linear relationship with respect to the iteration space
4832 // of a loop.
4833 // The special this pointer can be used as if was one of the arguments to the
4834 // function in any of the linear, aligned, or uniform clauses.
4835 // When a linear-step expression is specified in a linear clause it must be
4836 // either a constant integer expression or an integer-typed parameter that is
4837 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004838 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004839 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4840 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004841 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004842 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4843 ++MI;
4844 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004845 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4846 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4847 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004848 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4849 FD->getParamDecl(PVD->getFunctionScopeIndex())
4850 ->getCanonicalDecl() == CanonPVD) {
4851 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4852 // A list-item cannot appear in more than one linear clause.
4853 if (LinearArgs.count(CanonPVD) > 0) {
4854 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4855 << getOpenMPClauseName(OMPC_linear)
4856 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4857 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4858 diag::note_omp_explicit_dsa)
4859 << getOpenMPClauseName(OMPC_linear);
4860 continue;
4861 }
4862 // Each argument can appear in at most one uniform or linear clause.
4863 if (UniformedArgs.count(CanonPVD) > 0) {
4864 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4865 << getOpenMPClauseName(OMPC_linear)
4866 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4867 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4868 diag::note_omp_explicit_dsa)
4869 << getOpenMPClauseName(OMPC_uniform);
4870 continue;
4871 }
4872 LinearArgs[CanonPVD] = E;
4873 if (E->isValueDependent() || E->isTypeDependent() ||
4874 E->isInstantiationDependent() ||
4875 E->containsUnexpandedParameterPack())
4876 continue;
4877 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4878 PVD->getOriginalType());
4879 continue;
4880 }
4881 }
4882 if (isa<CXXThisExpr>(E)) {
4883 if (UniformedLinearThis) {
4884 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4885 << getOpenMPClauseName(OMPC_linear)
4886 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4887 << E->getSourceRange();
4888 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4889 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4890 : OMPC_linear);
4891 continue;
4892 }
4893 UniformedLinearThis = E;
4894 if (E->isValueDependent() || E->isTypeDependent() ||
4895 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4896 continue;
4897 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4898 E->getType());
4899 continue;
4900 }
4901 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4902 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4903 }
4904 Expr *Step = nullptr;
4905 Expr *NewStep = nullptr;
4906 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004907 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004908 // Skip the same step expression, it was checked already.
4909 if (Step == E || !E) {
4910 NewSteps.push_back(E ? NewStep : nullptr);
4911 continue;
4912 }
4913 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004914 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4915 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4916 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004917 if (UniformedArgs.count(CanonPVD) == 0) {
4918 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4919 << Step->getSourceRange();
4920 } else if (E->isValueDependent() || E->isTypeDependent() ||
4921 E->isInstantiationDependent() ||
4922 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004923 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004924 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004925 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004926 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4927 << Step->getSourceRange();
4928 }
4929 continue;
4930 }
4931 NewStep = Step;
4932 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4933 !Step->isInstantiationDependent() &&
4934 !Step->containsUnexpandedParameterPack()) {
4935 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4936 .get();
4937 if (NewStep)
4938 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4939 }
4940 NewSteps.push_back(NewStep);
4941 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004942 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4943 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004944 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004945 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4946 const_cast<Expr **>(Linears.data()), Linears.size(),
4947 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4948 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004949 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00004950 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004951}
4952
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004953Optional<std::pair<FunctionDecl *, Expr *>>
4954Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
4955 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004956 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004957 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004958
4959 const int VariantId = 1;
4960 // Must be applied only to single decl.
4961 if (!DG.get().isSingleDecl()) {
4962 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4963 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004964 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004965 }
4966 Decl *ADecl = DG.get().getSingleDecl();
4967 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4968 ADecl = FTD->getTemplatedDecl();
4969
4970 // Decl must be a function.
4971 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4972 if (!FD) {
4973 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
4974 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004975 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004976 }
4977
4978 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
4979 return FD->hasAttrs() &&
4980 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
4981 FD->hasAttr<TargetAttr>());
4982 };
4983 // OpenMP is not compatible with CPU-specific attributes.
4984 if (HasMultiVersionAttributes(FD)) {
4985 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
4986 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004987 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004988 }
4989
4990 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00004991 if (FD->isUsed(false))
4992 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00004993 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00004994
4995 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00004996 const FunctionDecl *Definition;
4997 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
4998 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00004999 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5000 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005001
5002 // The VariantRef must point to function.
5003 if (!VariantRef) {
5004 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005005 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005006 }
5007
5008 // Do not check templates, wait until instantiation.
5009 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5010 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005011 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5012 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005013
5014 // Convert VariantRef expression to the type of the original function to
5015 // resolve possible conflicts.
5016 ExprResult VariantRefCast;
5017 if (LangOpts.CPlusPlus) {
5018 QualType FnPtrType;
5019 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5020 if (Method && !Method->isStatic()) {
5021 const Type *ClassType =
5022 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5023 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5024 ExprResult ER;
5025 {
5026 // Build adrr_of unary op to correctly handle type checks for member
5027 // functions.
5028 Sema::TentativeAnalysisScope Trap(*this);
5029 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5030 VariantRef);
5031 }
5032 if (!ER.isUsable()) {
5033 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5034 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005035 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005036 }
5037 VariantRef = ER.get();
5038 } else {
5039 FnPtrType = Context.getPointerType(FD->getType());
5040 }
5041 ImplicitConversionSequence ICS =
5042 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5043 /*SuppressUserConversions=*/false,
5044 /*AllowExplicit=*/false,
5045 /*InOverloadResolution=*/false,
5046 /*CStyle=*/false,
5047 /*AllowObjCWritebackConversion=*/false);
5048 if (ICS.isFailure()) {
5049 Diag(VariantRef->getExprLoc(),
5050 diag::err_omp_declare_variant_incompat_types)
5051 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005052 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005053 }
5054 VariantRefCast = PerformImplicitConversion(
5055 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5056 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005057 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005058 // Drop previously built artificial addr_of unary op for member functions.
5059 if (Method && !Method->isStatic()) {
5060 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5061 if (auto *UO = dyn_cast<UnaryOperator>(
5062 PossibleAddrOfVariantRef->IgnoreImplicit()))
5063 VariantRefCast = UO->getSubExpr();
5064 }
5065 } else {
5066 VariantRefCast = VariantRef;
5067 }
5068
5069 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5070 if (!ER.isUsable() ||
5071 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5072 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5073 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005074 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005075 }
5076
5077 // The VariantRef must point to function.
5078 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5079 if (!DRE) {
5080 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5081 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005082 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005083 }
5084 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5085 if (!NewFD) {
5086 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5087 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005088 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005089 }
5090
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005091 // Check if variant function is not marked with declare variant directive.
5092 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5093 Diag(VariantRef->getExprLoc(),
5094 diag::warn_omp_declare_variant_marked_as_declare_variant)
5095 << VariantRef->getSourceRange();
5096 SourceRange SR =
5097 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5098 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005099 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005100 }
5101
Alexey Bataevd158cf62019-09-13 20:18:17 +00005102 enum DoesntSupport {
5103 VirtFuncs = 1,
5104 Constructors = 3,
5105 Destructors = 4,
5106 DeletedFuncs = 5,
5107 DefaultedFuncs = 6,
5108 ConstexprFuncs = 7,
5109 ConstevalFuncs = 8,
5110 };
5111 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5112 if (CXXFD->isVirtual()) {
5113 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5114 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005115 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005116 }
5117
5118 if (isa<CXXConstructorDecl>(FD)) {
5119 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5120 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005121 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005122 }
5123
5124 if (isa<CXXDestructorDecl>(FD)) {
5125 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5126 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005127 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005128 }
5129 }
5130
5131 if (FD->isDeleted()) {
5132 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5133 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005134 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005135 }
5136
5137 if (FD->isDefaulted()) {
5138 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5139 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005140 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005141 }
5142
5143 if (FD->isConstexpr()) {
5144 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5145 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005146 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005147 }
5148
5149 // Check general compatibility.
5150 if (areMultiversionVariantFunctionsCompatible(
5151 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5152 PartialDiagnosticAt(
5153 SR.getBegin(),
5154 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5155 PartialDiagnosticAt(
5156 VariantRef->getExprLoc(),
5157 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5158 PartialDiagnosticAt(VariantRef->getExprLoc(),
5159 PDiag(diag::err_omp_declare_variant_diff)
5160 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005161 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5162 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005163 return None;
5164 return std::make_pair(FD, cast<Expr>(DRE));
5165}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005166
Alexey Bataev9ff34742019-09-25 19:43:37 +00005167void Sema::ActOnOpenMPDeclareVariantDirective(
5168 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
5169 const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
5170 if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
5171 Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
5172 return;
Alexey Bataeva15a1412019-10-02 18:19:02 +00005173 Expr *Score = nullptr;
5174 OMPDeclareVariantAttr::ScoreType ST = OMPDeclareVariantAttr::ScoreUnknown;
5175 if (Data.CtxScore.isUsable()) {
5176 ST = OMPDeclareVariantAttr::ScoreSpecified;
5177 Score = Data.CtxScore.get();
5178 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5179 !Score->isInstantiationDependent() &&
5180 !Score->containsUnexpandedParameterPack()) {
5181 llvm::APSInt Result;
5182 ExprResult ICE = VerifyIntegerConstantExpression(Score, &Result);
5183 if (ICE.isInvalid())
5184 return;
5185 }
5186 }
Alexey Bataev9ff34742019-09-25 19:43:37 +00005187 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
Alexey Bataev303657a2019-10-08 19:44:16 +00005188 Context, VariantRef, Score, Data.CtxSet, ST, Data.Ctx,
5189 Data.ImplVendors.begin(), Data.ImplVendors.size(), SR);
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005190 FD->addAttr(NewAttr);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005191}
5192
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005193void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5194 FunctionDecl *Func,
5195 bool MightBeOdrUse) {
5196 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5197
5198 if (!Func->isDependentContext() && Func->hasAttrs()) {
5199 for (OMPDeclareVariantAttr *A :
5200 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5201 // TODO: add checks for active OpenMP context where possible.
5202 Expr *VariantRef = A->getVariantFuncRef();
5203 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5204 auto *F = cast<FunctionDecl>(DRE->getDecl());
5205 if (!F->isDefined() && F->isTemplateInstantiation())
5206 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5207 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5208 }
5209 }
5210}
5211
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005212StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5213 Stmt *AStmt,
5214 SourceLocation StartLoc,
5215 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005216 if (!AStmt)
5217 return StmtError();
5218
Alexey Bataeve3727102018-04-18 15:57:46 +00005219 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005220 // 1.2.2 OpenMP Language Terminology
5221 // Structured block - An executable statement with a single entry at the
5222 // top and a single exit at the bottom.
5223 // The point of exit cannot be a branch out of the structured block.
5224 // longjmp() and throw() must not violate the entry/exit criteria.
5225 CS->getCapturedDecl()->setNothrow();
5226
Reid Kleckner87a31802018-03-12 21:43:02 +00005227 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005228
Alexey Bataev25e5b442015-09-15 12:52:43 +00005229 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5230 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005231}
5232
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005233namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005234/// Iteration space of a single for loop.
5235struct LoopIterationSpace final {
5236 /// True if the condition operator is the strict compare operator (<, > or
5237 /// !=).
5238 bool IsStrictCompare = false;
5239 /// Condition of the loop.
5240 Expr *PreCond = nullptr;
5241 /// This expression calculates the number of iterations in the loop.
5242 /// It is always possible to calculate it before starting the loop.
5243 Expr *NumIterations = nullptr;
5244 /// The loop counter variable.
5245 Expr *CounterVar = nullptr;
5246 /// Private loop counter variable.
5247 Expr *PrivateCounterVar = nullptr;
5248 /// This is initializer for the initial value of #CounterVar.
5249 Expr *CounterInit = nullptr;
5250 /// This is step for the #CounterVar used to generate its update:
5251 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5252 Expr *CounterStep = nullptr;
5253 /// Should step be subtracted?
5254 bool Subtract = false;
5255 /// Source range of the loop init.
5256 SourceRange InitSrcRange;
5257 /// Source range of the loop condition.
5258 SourceRange CondSrcRange;
5259 /// Source range of the loop increment.
5260 SourceRange IncSrcRange;
5261 /// Minimum value that can have the loop control variable. Used to support
5262 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5263 /// since only such variables can be used in non-loop invariant expressions.
5264 Expr *MinValue = nullptr;
5265 /// Maximum value that can have the loop control variable. Used to support
5266 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5267 /// since only such variables can be used in non-loop invariant expressions.
5268 Expr *MaxValue = nullptr;
5269 /// true, if the lower bound depends on the outer loop control var.
5270 bool IsNonRectangularLB = false;
5271 /// true, if the upper bound depends on the outer loop control var.
5272 bool IsNonRectangularUB = false;
5273 /// Index of the loop this loop depends on and forms non-rectangular loop
5274 /// nest.
5275 unsigned LoopDependentIdx = 0;
5276 /// Final condition for the non-rectangular loop nest support. It is used to
5277 /// check that the number of iterations for this particular counter must be
5278 /// finished.
5279 Expr *FinalCondition = nullptr;
5280};
5281
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005282/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005283/// extracting iteration space of each loop in the loop nest, that will be used
5284/// for IR generation.
5285class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005286 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005287 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005288 /// Data-sharing stack.
5289 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005290 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005291 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005292 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005293 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005294 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005295 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005296 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005297 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005298 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005299 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005300 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005301 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005302 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005303 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005304 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005305 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005306 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005307 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005308 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005309 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005310 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005311 /// Var < UB
5312 /// Var <= UB
5313 /// UB > Var
5314 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005315 /// This will have no value when the condition is !=
5316 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005317 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005318 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005319 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005320 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005321 /// The outer loop counter this loop depends on (if any).
5322 const ValueDecl *DepDecl = nullptr;
5323 /// Contains number of loop (starts from 1) on which loop counter init
5324 /// expression of this loop depends on.
5325 Optional<unsigned> InitDependOnLC;
5326 /// Contains number of loop (starts from 1) on which loop counter condition
5327 /// expression of this loop depends on.
5328 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005329 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005330 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005331 /// Original condition required for checking of the exit condition for
5332 /// non-rectangular loop.
5333 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005334
5335public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005336 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5337 SourceLocation DefaultLoc)
5338 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5339 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005340 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005341 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005342 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005343 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005344 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005345 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005346 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005347 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005348 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005349 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005350 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005351 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005352 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005353 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005354 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005355 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005356 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005357 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005358 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005359 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005360 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005361 /// True, if the compare operator is strict (<, > or !=).
5362 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005363 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005364 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005365 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005366 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005367 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005368 Expr *
5369 buildPreCond(Scope *S, Expr *Cond,
5370 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005371 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005372 DeclRefExpr *
5373 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5374 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005375 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005376 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005377 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005378 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005379 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005380 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005381 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005382 /// Build loop data with counter value for depend clauses in ordered
5383 /// directives.
5384 Expr *
5385 buildOrderedLoopData(Scope *S, Expr *Counter,
5386 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5387 SourceLocation Loc, Expr *Inc = nullptr,
5388 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005389 /// Builds the minimum value for the loop counter.
5390 std::pair<Expr *, Expr *> buildMinMaxValues(
5391 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5392 /// Builds final condition for the non-rectangular loops.
5393 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005394 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005395 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005396 /// Returns true if the initializer forms non-rectangular loop.
5397 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5398 /// Returns true if the condition forms non-rectangular loop.
5399 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5400 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5401 unsigned getLoopDependentIdx() const {
5402 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5403 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005404
5405private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005406 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005407 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005408 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005409 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005410 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5411 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005412 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005413 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5414 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005415 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005416 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005417};
5418
Alexey Bataeve3727102018-04-18 15:57:46 +00005419bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005420 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005421 assert(!LB && !UB && !Step);
5422 return false;
5423 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005424 return LCDecl->getType()->isDependentType() ||
5425 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5426 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005427}
5428
Alexey Bataeve3727102018-04-18 15:57:46 +00005429bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005430 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005431 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005432 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005433 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005434 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005435 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005436 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005437 LCDecl = getCanonicalDecl(NewLCDecl);
5438 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005439 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5440 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005441 if ((Ctor->isCopyOrMoveConstructor() ||
5442 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5443 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005444 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005445 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005446 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005447 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005448 return false;
5449}
5450
Alexey Bataev316ccf62019-01-29 18:51:58 +00005451bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5452 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005453 bool StrictOp, SourceRange SR,
5454 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005455 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005456 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5457 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005458 if (!NewUB)
5459 return true;
5460 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005461 if (LessOp)
5462 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005463 TestIsStrictOp = StrictOp;
5464 ConditionSrcRange = SR;
5465 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005466 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005467 return false;
5468}
5469
Alexey Bataeve3727102018-04-18 15:57:46 +00005470bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005471 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005472 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005473 if (!NewStep)
5474 return true;
5475 if (!NewStep->isValueDependent()) {
5476 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005477 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005478 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5479 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005480 if (Val.isInvalid())
5481 return true;
5482 NewStep = Val.get();
5483
5484 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5485 // If test-expr is of form var relational-op b and relational-op is < or
5486 // <= then incr-expr must cause var to increase on each iteration of the
5487 // loop. If test-expr is of form var relational-op b and relational-op is
5488 // > or >= then incr-expr must cause var to decrease on each iteration of
5489 // the loop.
5490 // If test-expr is of form b relational-op var and relational-op is < or
5491 // <= then incr-expr must cause var to decrease on each iteration of the
5492 // loop. If test-expr is of form b relational-op var and relational-op is
5493 // > or >= then incr-expr must cause var to increase on each iteration of
5494 // the loop.
5495 llvm::APSInt Result;
5496 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5497 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5498 bool IsConstNeg =
5499 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005500 bool IsConstPos =
5501 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005502 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005503
5504 // != with increment is treated as <; != with decrement is treated as >
5505 if (!TestIsLessOp.hasValue())
5506 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005507 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005508 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005509 (IsConstNeg || (IsUnsigned && Subtract)) :
5510 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005511 SemaRef.Diag(NewStep->getExprLoc(),
5512 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005513 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005514 SemaRef.Diag(ConditionLoc,
5515 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005516 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005517 return true;
5518 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005519 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005520 NewStep =
5521 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5522 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005523 Subtract = !Subtract;
5524 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005525 }
5526
5527 Step = NewStep;
5528 SubtractStep = Subtract;
5529 return false;
5530}
5531
Alexey Bataev622af1d2019-04-24 19:58:30 +00005532namespace {
5533/// Checker for the non-rectangular loops. Checks if the initializer or
5534/// condition expression references loop counter variable.
5535class LoopCounterRefChecker final
5536 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5537 Sema &SemaRef;
5538 DSAStackTy &Stack;
5539 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005540 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005541 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005542 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005543 unsigned BaseLoopId = 0;
5544 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5545 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5546 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5547 << (IsInitializer ? 0 : 1);
5548 return false;
5549 }
5550 const auto &&Data = Stack.isLoopControlVariable(VD);
5551 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5552 // The type of the loop iterator on which we depend may not have a random
5553 // access iterator type.
5554 if (Data.first && VD->getType()->isRecordType()) {
5555 SmallString<128> Name;
5556 llvm::raw_svector_ostream OS(Name);
5557 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5558 /*Qualified=*/true);
5559 SemaRef.Diag(E->getExprLoc(),
5560 diag::err_omp_wrong_dependency_iterator_type)
5561 << OS.str();
5562 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5563 return false;
5564 }
5565 if (Data.first &&
5566 (DepDecl || (PrevDepDecl &&
5567 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5568 if (!DepDecl && PrevDepDecl)
5569 DepDecl = PrevDepDecl;
5570 SmallString<128> Name;
5571 llvm::raw_svector_ostream OS(Name);
5572 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5573 /*Qualified=*/true);
5574 SemaRef.Diag(E->getExprLoc(),
5575 diag::err_omp_invariant_or_linear_dependency)
5576 << OS.str();
5577 return false;
5578 }
5579 if (Data.first) {
5580 DepDecl = VD;
5581 BaseLoopId = Data.first;
5582 }
5583 return Data.first;
5584 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005585
5586public:
5587 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5588 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005589 if (isa<VarDecl>(VD))
5590 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005591 return false;
5592 }
5593 bool VisitMemberExpr(const MemberExpr *E) {
5594 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5595 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005596 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5597 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005598 }
5599 return false;
5600 }
5601 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005602 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005603 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005604 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005605 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005606 }
5607 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005608 const ValueDecl *CurLCDecl, bool IsInitializer,
5609 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005610 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005611 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5612 unsigned getBaseLoopId() const {
5613 assert(CurLCDecl && "Expected loop dependency.");
5614 return BaseLoopId;
5615 }
5616 const ValueDecl *getDepDecl() const {
5617 assert(CurLCDecl && "Expected loop dependency.");
5618 return DepDecl;
5619 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005620};
5621} // namespace
5622
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005623Optional<unsigned>
5624OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5625 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005626 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005627 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5628 DepDecl);
5629 if (LoopStmtChecker.Visit(S)) {
5630 DepDecl = LoopStmtChecker.getDepDecl();
5631 return LoopStmtChecker.getBaseLoopId();
5632 }
5633 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005634}
5635
Alexey Bataeve3727102018-04-18 15:57:46 +00005636bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005637 // Check init-expr for canonical loop form and save loop counter
5638 // variable - #Var and its initialization value - #LB.
5639 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5640 // var = lb
5641 // integer-type var = lb
5642 // random-access-iterator-type var = lb
5643 // pointer-type var = lb
5644 //
5645 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005646 if (EmitDiags) {
5647 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5648 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005649 return true;
5650 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005651 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5652 if (!ExprTemp->cleanupsHaveSideEffects())
5653 S = ExprTemp->getSubExpr();
5654
Alexander Musmana5f070a2014-10-01 06:03:56 +00005655 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005656 if (Expr *E = dyn_cast<Expr>(S))
5657 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005658 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005659 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005660 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005661 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5662 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5663 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005664 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5665 EmitDiags);
5666 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005667 }
5668 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5669 if (ME->isArrow() &&
5670 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005671 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5672 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005673 }
5674 }
David Majnemer9d168222016-08-05 17:44:54 +00005675 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005676 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005677 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005678 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005679 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005680 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005681 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005682 diag::ext_omp_loop_not_canonical_init)
5683 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005684 return setLCDeclAndLB(
5685 Var,
5686 buildDeclRefExpr(SemaRef, Var,
5687 Var->getType().getNonReferenceType(),
5688 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005689 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005690 }
5691 }
5692 }
David Majnemer9d168222016-08-05 17:44:54 +00005693 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005694 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005695 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005696 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005697 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5698 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005699 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5700 EmitDiags);
5701 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005702 }
5703 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5704 if (ME->isArrow() &&
5705 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005706 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5707 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005708 }
5709 }
5710 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005711
Alexey Bataeve3727102018-04-18 15:57:46 +00005712 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005713 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005714 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005715 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005716 << S->getSourceRange();
5717 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005718 return true;
5719}
5720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005721/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005722/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005723static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005724 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005725 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005726 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005727 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005728 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005729 if ((Ctor->isCopyOrMoveConstructor() ||
5730 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5731 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005732 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005733 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5734 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005735 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005736 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005737 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005738 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5739 return getCanonicalDecl(ME->getMemberDecl());
5740 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005741}
5742
Alexey Bataeve3727102018-04-18 15:57:46 +00005743bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005744 // Check test-expr for canonical form, save upper-bound UB, flags for
5745 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005746 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005747 // var relational-op b
5748 // b relational-op var
5749 //
Alexey Bataev1be63402019-09-11 15:44:06 +00005750 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005751 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00005752 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
5753 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005754 return true;
5755 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00005756 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005757 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005758 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005759 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005760 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005761 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5762 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005763 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5764 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5765 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005766 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5767 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005768 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5769 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5770 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00005771 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
5772 return setUB(
5773 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
5774 /*LessOp=*/llvm::None,
5775 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005776 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005777 if (CE->getNumArgs() == 2) {
5778 auto Op = CE->getOperator();
5779 switch (Op) {
5780 case OO_Greater:
5781 case OO_GreaterEqual:
5782 case OO_Less:
5783 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005784 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5785 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005786 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5787 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005788 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5789 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005790 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5791 CE->getOperatorLoc());
5792 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005793 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00005794 if (IneqCondIsCanonical)
5795 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
5796 : CE->getArg(0),
5797 /*LessOp=*/llvm::None,
5798 /*StrictOp=*/true, CE->getSourceRange(),
5799 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005800 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005801 default:
5802 break;
5803 }
5804 }
5805 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005806 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005807 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005808 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00005809 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005810 return true;
5811}
5812
Alexey Bataeve3727102018-04-18 15:57:46 +00005813bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005814 // RHS of canonical loop form increment can be:
5815 // var + incr
5816 // incr + var
5817 // var - incr
5818 //
5819 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005820 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005821 if (BO->isAdditiveOp()) {
5822 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005823 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5824 return setStep(BO->getRHS(), !IsAdd);
5825 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5826 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005827 }
David Majnemer9d168222016-08-05 17:44:54 +00005828 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005829 bool IsAdd = CE->getOperator() == OO_Plus;
5830 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005831 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5832 return setStep(CE->getArg(1), !IsAdd);
5833 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5834 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005835 }
5836 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005837 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005838 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005839 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005840 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005841 return true;
5842}
5843
Alexey Bataeve3727102018-04-18 15:57:46 +00005844bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005845 // Check incr-expr for canonical loop form and return true if it
5846 // does not conform.
5847 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5848 // ++var
5849 // var++
5850 // --var
5851 // var--
5852 // var += incr
5853 // var -= incr
5854 // var = var + incr
5855 // var = incr + var
5856 // var = var - incr
5857 //
5858 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005859 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005860 return true;
5861 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005862 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5863 if (!ExprTemp->cleanupsHaveSideEffects())
5864 S = ExprTemp->getSubExpr();
5865
Alexander Musmana5f070a2014-10-01 06:03:56 +00005866 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005867 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005868 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005869 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005870 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5871 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005872 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005873 (UO->isDecrementOp() ? -1 : 1))
5874 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005875 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005876 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005877 switch (BO->getOpcode()) {
5878 case BO_AddAssign:
5879 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005880 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5881 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005882 break;
5883 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005884 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5885 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005886 break;
5887 default:
5888 break;
5889 }
David Majnemer9d168222016-08-05 17:44:54 +00005890 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005891 switch (CE->getOperator()) {
5892 case OO_PlusPlus:
5893 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005894 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5895 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005896 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005897 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005898 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5899 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005900 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005901 break;
5902 case OO_PlusEqual:
5903 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005904 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5905 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005906 break;
5907 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005908 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5909 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005910 break;
5911 default:
5912 break;
5913 }
5914 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005915 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005916 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005917 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005918 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005919 return true;
5920}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005921
Alexey Bataev5a3af132016-03-29 08:58:54 +00005922static ExprResult
5923tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005924 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005925 if (SemaRef.CurContext->isDependentContext())
5926 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005927 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5928 return SemaRef.PerformImplicitConversion(
5929 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5930 /*AllowExplicit=*/true);
5931 auto I = Captures.find(Capture);
5932 if (I != Captures.end())
5933 return buildCapture(SemaRef, Capture, I->second);
5934 DeclRefExpr *Ref = nullptr;
5935 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5936 Captures[Capture] = Ref;
5937 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005938}
5939
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005940/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005941Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005942 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005943 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005944 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005945 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005946 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005947 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005948 Expr *LBVal = LB;
5949 Expr *UBVal = UB;
5950 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
5951 // max(LB(MinVal), LB(MaxVal))
5952 if (InitDependOnLC) {
5953 const LoopIterationSpace &IS =
5954 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5955 InitDependOnLC.getValueOr(
5956 CondDependOnLC.getValueOr(0))];
5957 if (!IS.MinValue || !IS.MaxValue)
5958 return nullptr;
5959 // OuterVar = Min
5960 ExprResult MinValue =
5961 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5962 if (!MinValue.isUsable())
5963 return nullptr;
5964
5965 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5966 IS.CounterVar, MinValue.get());
5967 if (!LBMinVal.isUsable())
5968 return nullptr;
5969 // OuterVar = Min, LBVal
5970 LBMinVal =
5971 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
5972 if (!LBMinVal.isUsable())
5973 return nullptr;
5974 // (OuterVar = Min, LBVal)
5975 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
5976 if (!LBMinVal.isUsable())
5977 return nullptr;
5978
5979 // OuterVar = Max
5980 ExprResult MaxValue =
5981 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5982 if (!MaxValue.isUsable())
5983 return nullptr;
5984
5985 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5986 IS.CounterVar, MaxValue.get());
5987 if (!LBMaxVal.isUsable())
5988 return nullptr;
5989 // OuterVar = Max, LBVal
5990 LBMaxVal =
5991 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
5992 if (!LBMaxVal.isUsable())
5993 return nullptr;
5994 // (OuterVar = Max, LBVal)
5995 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
5996 if (!LBMaxVal.isUsable())
5997 return nullptr;
5998
5999 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6000 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6001 if (!LBMin || !LBMax)
6002 return nullptr;
6003 // LB(MinVal) < LB(MaxVal)
6004 ExprResult MinLessMaxRes =
6005 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6006 if (!MinLessMaxRes.isUsable())
6007 return nullptr;
6008 Expr *MinLessMax =
6009 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6010 if (!MinLessMax)
6011 return nullptr;
6012 if (TestIsLessOp.getValue()) {
6013 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6014 // LB(MaxVal))
6015 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6016 MinLessMax, LBMin, LBMax);
6017 if (!MinLB.isUsable())
6018 return nullptr;
6019 LBVal = MinLB.get();
6020 } else {
6021 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6022 // LB(MaxVal))
6023 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6024 MinLessMax, LBMax, LBMin);
6025 if (!MaxLB.isUsable())
6026 return nullptr;
6027 LBVal = MaxLB.get();
6028 }
6029 }
6030 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6031 // min(UB(MinVal), UB(MaxVal))
6032 if (CondDependOnLC) {
6033 const LoopIterationSpace &IS =
6034 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6035 InitDependOnLC.getValueOr(
6036 CondDependOnLC.getValueOr(0))];
6037 if (!IS.MinValue || !IS.MaxValue)
6038 return nullptr;
6039 // OuterVar = Min
6040 ExprResult MinValue =
6041 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6042 if (!MinValue.isUsable())
6043 return nullptr;
6044
6045 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6046 IS.CounterVar, MinValue.get());
6047 if (!UBMinVal.isUsable())
6048 return nullptr;
6049 // OuterVar = Min, UBVal
6050 UBMinVal =
6051 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6052 if (!UBMinVal.isUsable())
6053 return nullptr;
6054 // (OuterVar = Min, UBVal)
6055 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6056 if (!UBMinVal.isUsable())
6057 return nullptr;
6058
6059 // OuterVar = Max
6060 ExprResult MaxValue =
6061 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6062 if (!MaxValue.isUsable())
6063 return nullptr;
6064
6065 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6066 IS.CounterVar, MaxValue.get());
6067 if (!UBMaxVal.isUsable())
6068 return nullptr;
6069 // OuterVar = Max, UBVal
6070 UBMaxVal =
6071 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6072 if (!UBMaxVal.isUsable())
6073 return nullptr;
6074 // (OuterVar = Max, UBVal)
6075 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6076 if (!UBMaxVal.isUsable())
6077 return nullptr;
6078
6079 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6080 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6081 if (!UBMin || !UBMax)
6082 return nullptr;
6083 // UB(MinVal) > UB(MaxVal)
6084 ExprResult MinGreaterMaxRes =
6085 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6086 if (!MinGreaterMaxRes.isUsable())
6087 return nullptr;
6088 Expr *MinGreaterMax =
6089 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6090 if (!MinGreaterMax)
6091 return nullptr;
6092 if (TestIsLessOp.getValue()) {
6093 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6094 // UB(MaxVal))
6095 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6096 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6097 if (!MaxUB.isUsable())
6098 return nullptr;
6099 UBVal = MaxUB.get();
6100 } else {
6101 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6102 // UB(MaxVal))
6103 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6104 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6105 if (!MinUB.isUsable())
6106 return nullptr;
6107 UBVal = MinUB.get();
6108 }
6109 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006110 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006111 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6112 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006113 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6114 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006115 if (!Upper || !Lower)
6116 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006117
6118 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6119
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006120 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006121 // BuildBinOp already emitted error, this one is to point user to upper
6122 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006123 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006124 << Upper->getSourceRange() << Lower->getSourceRange();
6125 return nullptr;
6126 }
6127 }
6128
6129 if (!Diff.isUsable())
6130 return nullptr;
6131
6132 // Upper - Lower [- 1]
6133 if (TestIsStrictOp)
6134 Diff = SemaRef.BuildBinOp(
6135 S, DefaultLoc, BO_Sub, Diff.get(),
6136 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6137 if (!Diff.isUsable())
6138 return nullptr;
6139
6140 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006141 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006142 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006143 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006144 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006145 if (!Diff.isUsable())
6146 return nullptr;
6147
6148 // Parentheses (for dumping/debugging purposes only).
6149 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6150 if (!Diff.isUsable())
6151 return nullptr;
6152
6153 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006154 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006155 if (!Diff.isUsable())
6156 return nullptr;
6157
Alexander Musman174b3ca2014-10-06 11:16:29 +00006158 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006159 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006160 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006161 bool UseVarType = VarType->hasIntegerRepresentation() &&
6162 C.getTypeSize(Type) > C.getTypeSize(VarType);
6163 if (!Type->isIntegerType() || UseVarType) {
6164 unsigned NewSize =
6165 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6166 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6167 : Type->hasSignedIntegerRepresentation();
6168 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006169 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6170 Diff = SemaRef.PerformImplicitConversion(
6171 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6172 if (!Diff.isUsable())
6173 return nullptr;
6174 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006175 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006176 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006177 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6178 if (NewSize != C.getTypeSize(Type)) {
6179 if (NewSize < C.getTypeSize(Type)) {
6180 assert(NewSize == 64 && "incorrect loop var size");
6181 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6182 << InitSrcRange << ConditionSrcRange;
6183 }
6184 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006185 NewSize, Type->hasSignedIntegerRepresentation() ||
6186 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006187 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6188 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6189 Sema::AA_Converting, true);
6190 if (!Diff.isUsable())
6191 return nullptr;
6192 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006193 }
6194 }
6195
Alexander Musmana5f070a2014-10-01 06:03:56 +00006196 return Diff.get();
6197}
6198
Alexey Bataevf8be4762019-08-14 19:30:06 +00006199std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6200 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6201 // Do not build for iterators, they cannot be used in non-rectangular loop
6202 // nests.
6203 if (LCDecl->getType()->isRecordType())
6204 return std::make_pair(nullptr, nullptr);
6205 // If we subtract, the min is in the condition, otherwise the min is in the
6206 // init value.
6207 Expr *MinExpr = nullptr;
6208 Expr *MaxExpr = nullptr;
6209 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6210 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6211 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6212 : CondDependOnLC.hasValue();
6213 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6214 : InitDependOnLC.hasValue();
6215 Expr *Lower =
6216 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6217 Expr *Upper =
6218 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6219 if (!Upper || !Lower)
6220 return std::make_pair(nullptr, nullptr);
6221
6222 if (TestIsLessOp.getValue())
6223 MinExpr = Lower;
6224 else
6225 MaxExpr = Upper;
6226
6227 // Build minimum/maximum value based on number of iterations.
6228 ExprResult Diff;
6229 QualType VarType = LCDecl->getType().getNonReferenceType();
6230
6231 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6232 if (!Diff.isUsable())
6233 return std::make_pair(nullptr, nullptr);
6234
6235 // Upper - Lower [- 1]
6236 if (TestIsStrictOp)
6237 Diff = SemaRef.BuildBinOp(
6238 S, DefaultLoc, BO_Sub, Diff.get(),
6239 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6240 if (!Diff.isUsable())
6241 return std::make_pair(nullptr, nullptr);
6242
6243 // Upper - Lower [- 1] + Step
6244 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6245 if (!NewStep.isUsable())
6246 return std::make_pair(nullptr, nullptr);
6247
6248 // Parentheses (for dumping/debugging purposes only).
6249 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6250 if (!Diff.isUsable())
6251 return std::make_pair(nullptr, nullptr);
6252
6253 // (Upper - Lower [- 1]) / Step
6254 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6255 if (!Diff.isUsable())
6256 return std::make_pair(nullptr, nullptr);
6257
6258 // ((Upper - Lower [- 1]) / Step) * Step
6259 // Parentheses (for dumping/debugging purposes only).
6260 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6261 if (!Diff.isUsable())
6262 return std::make_pair(nullptr, nullptr);
6263
6264 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6265 if (!Diff.isUsable())
6266 return std::make_pair(nullptr, nullptr);
6267
6268 // Convert to the original type or ptrdiff_t, if original type is pointer.
6269 if (!VarType->isAnyPointerType() &&
6270 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6271 Diff = SemaRef.PerformImplicitConversion(
6272 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6273 } else if (VarType->isAnyPointerType() &&
6274 !SemaRef.Context.hasSameType(
6275 Diff.get()->getType(),
6276 SemaRef.Context.getUnsignedPointerDiffType())) {
6277 Diff = SemaRef.PerformImplicitConversion(
6278 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6279 Sema::AA_Converting, /*AllowExplicit=*/true);
6280 }
6281 if (!Diff.isUsable())
6282 return std::make_pair(nullptr, nullptr);
6283
6284 // Parentheses (for dumping/debugging purposes only).
6285 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6286 if (!Diff.isUsable())
6287 return std::make_pair(nullptr, nullptr);
6288
6289 if (TestIsLessOp.getValue()) {
6290 // MinExpr = Lower;
6291 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6292 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6293 if (!Diff.isUsable())
6294 return std::make_pair(nullptr, nullptr);
6295 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6296 if (!Diff.isUsable())
6297 return std::make_pair(nullptr, nullptr);
6298 MaxExpr = Diff.get();
6299 } else {
6300 // MaxExpr = Upper;
6301 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6302 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6303 if (!Diff.isUsable())
6304 return std::make_pair(nullptr, nullptr);
6305 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6306 if (!Diff.isUsable())
6307 return std::make_pair(nullptr, nullptr);
6308 MinExpr = Diff.get();
6309 }
6310
6311 return std::make_pair(MinExpr, MaxExpr);
6312}
6313
6314Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6315 if (InitDependOnLC || CondDependOnLC)
6316 return Condition;
6317 return nullptr;
6318}
6319
Alexey Bataeve3727102018-04-18 15:57:46 +00006320Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006321 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006322 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006323 // Do not build a precondition when the condition/initialization is dependent
6324 // to prevent pessimistic early loop exit.
6325 // TODO: this can be improved by calculating min/max values but not sure that
6326 // it will be very effective.
6327 if (CondDependOnLC || InitDependOnLC)
6328 return SemaRef.PerformImplicitConversion(
6329 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6330 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6331 /*AllowExplicit=*/true).get();
6332
Alexey Bataev62dbb972015-04-22 11:59:37 +00006333 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006334 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006335
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006336 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6337 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006338 if (!NewLB.isUsable() || !NewUB.isUsable())
6339 return nullptr;
6340
Alexey Bataeve3727102018-04-18 15:57:46 +00006341 ExprResult CondExpr =
6342 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006343 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006344 (TestIsStrictOp ? BO_LT : BO_LE) :
6345 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006346 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006347 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006348 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6349 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006350 CondExpr = SemaRef.PerformImplicitConversion(
6351 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6352 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006353 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006354
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006355 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006356 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6357}
6358
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006359/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006360DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006361 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6362 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006363 auto *VD = dyn_cast<VarDecl>(LCDecl);
6364 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006365 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6366 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006367 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006368 const DSAStackTy::DSAVarData Data =
6369 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006370 // If the loop control decl is explicitly marked as private, do not mark it
6371 // as captured again.
6372 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6373 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006374 return Ref;
6375 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006376 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006377}
6378
Alexey Bataeve3727102018-04-18 15:57:46 +00006379Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006380 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006381 QualType Type = LCDecl->getType().getNonReferenceType();
6382 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006383 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6384 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6385 isa<VarDecl>(LCDecl)
6386 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6387 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006388 if (PrivateVar->isInvalidDecl())
6389 return nullptr;
6390 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6391 }
6392 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006393}
6394
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006395/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006396Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006397
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006398/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006399Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006400
Alexey Bataevf138fda2018-08-13 19:04:24 +00006401Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6402 Scope *S, Expr *Counter,
6403 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6404 Expr *Inc, OverloadedOperatorKind OOK) {
6405 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6406 if (!Cnt)
6407 return nullptr;
6408 if (Inc) {
6409 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6410 "Expected only + or - operations for depend clauses.");
6411 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6412 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6413 if (!Cnt)
6414 return nullptr;
6415 }
6416 ExprResult Diff;
6417 QualType VarType = LCDecl->getType().getNonReferenceType();
6418 if (VarType->isIntegerType() || VarType->isPointerType() ||
6419 SemaRef.getLangOpts().CPlusPlus) {
6420 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006421 Expr *Upper = TestIsLessOp.getValue()
6422 ? Cnt
6423 : tryBuildCapture(SemaRef, UB, Captures).get();
6424 Expr *Lower = TestIsLessOp.getValue()
6425 ? tryBuildCapture(SemaRef, LB, Captures).get()
6426 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006427 if (!Upper || !Lower)
6428 return nullptr;
6429
6430 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6431
6432 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6433 // BuildBinOp already emitted error, this one is to point user to upper
6434 // and lower bound, and to tell what is passed to 'operator-'.
6435 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6436 << Upper->getSourceRange() << Lower->getSourceRange();
6437 return nullptr;
6438 }
6439 }
6440
6441 if (!Diff.isUsable())
6442 return nullptr;
6443
6444 // Parentheses (for dumping/debugging purposes only).
6445 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6446 if (!Diff.isUsable())
6447 return nullptr;
6448
6449 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6450 if (!NewStep.isUsable())
6451 return nullptr;
6452 // (Upper - Lower) / Step
6453 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6454 if (!Diff.isUsable())
6455 return nullptr;
6456
6457 return Diff.get();
6458}
Alexey Bataev23b69422014-06-18 07:08:49 +00006459} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006460
Alexey Bataev9c821032015-04-30 04:23:23 +00006461void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6462 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6463 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006464 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6465 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006466 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006467 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006468 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006469 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6470 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006471 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006472 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006473 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006474 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006475 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006476 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006477 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6478 /*WithInit=*/false);
6479 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006480 }
6481 }
6482 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006483 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6484 if (LD != D->getCanonicalDecl()) {
6485 DSAStack->resetPossibleLoopCounter();
6486 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6487 MarkDeclarationsReferencedInExpr(
6488 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6489 Var->getType().getNonLValueExprType(Context),
6490 ForLoc, /*RefersToCapture=*/true));
6491 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006492 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6493 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6494 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6495 // associated for-loop of a simd construct with just one associated
6496 // for-loop may be listed in a linear clause with a constant-linear-step
6497 // that is the increment of the associated for-loop. The loop iteration
6498 // variable(s) in the associated for-loop(s) of a for or parallel for
6499 // construct may be listed in a private or lastprivate clause.
6500 DSAStackTy::DSAVarData DVar =
6501 DSAStack->getTopDSA(D, /*FromParent=*/false);
6502 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6503 // is declared in the loop and it is predetermined as a private.
6504 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6505 OpenMPClauseKind PredeterminedCKind =
6506 isOpenMPSimdDirective(DKind)
6507 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6508 : OMPC_private;
6509 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6510 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6511 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6512 DVar.CKind != OMPC_private))) ||
6513 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006514 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006515 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006516 isOpenMPDistributeDirective(DKind)) &&
6517 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6518 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6519 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6520 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6521 << getOpenMPClauseName(DVar.CKind)
6522 << getOpenMPDirectiveName(DKind)
6523 << getOpenMPClauseName(PredeterminedCKind);
6524 if (DVar.RefExpr == nullptr)
6525 DVar.CKind = PredeterminedCKind;
6526 reportOriginalDsa(*this, DSAStack, D, DVar,
6527 /*IsLoopIterVar=*/true);
6528 } else if (LoopDeclRefExpr) {
6529 // Make the loop iteration variable private (for worksharing
6530 // constructs), linear (for simd directives with the only one
6531 // associated loop) or lastprivate (for simd directives with several
6532 // collapsed or ordered loops).
6533 if (DVar.CKind == OMPC_unknown)
6534 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6535 PrivateRef);
6536 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006537 }
6538 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006539 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006540 }
6541}
6542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006543/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006544/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006545static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006546 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6547 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006548 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6549 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006550 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006551 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006552 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00006553 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006554 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00006555 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006556 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00006557 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
6558 // Ranged for is supported only in OpenMP 5.0.
6559 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006560 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006561 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006562 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006563 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006564 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006565 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6566 SemaRef.Diag(DSA.getConstructLoc(),
6567 diag::note_omp_collapse_ordered_expr)
6568 << 2 << CollapseLoopCountExpr->getSourceRange()
6569 << OrderedLoopCountExpr->getSourceRange();
6570 else if (CollapseLoopCountExpr)
6571 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6572 diag::note_omp_collapse_ordered_expr)
6573 << 0 << CollapseLoopCountExpr->getSourceRange();
6574 else
6575 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6576 diag::note_omp_collapse_ordered_expr)
6577 << 1 << OrderedLoopCountExpr->getSourceRange();
6578 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006579 return true;
6580 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00006581 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
6582 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006583
Alexey Bataevbef93a92019-10-07 18:54:57 +00006584 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
6585 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006586
6587 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006588 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00006589 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006590 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006591
6592 bool HasErrors = false;
6593
6594 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006595 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006596 // OpenMP [2.6, Canonical Loop Form]
6597 // Var is one of the following:
6598 // A variable of signed or unsigned integer type.
6599 // For C++, a variable of a random access iterator type.
6600 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006601 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006602 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6603 !VarType->isPointerType() &&
6604 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006605 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006606 << SemaRef.getLangOpts().CPlusPlus;
6607 HasErrors = true;
6608 }
6609
6610 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6611 // a Construct
6612 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6613 // parallel for construct is (are) private.
6614 // The loop iteration variable in the associated for-loop of a simd
6615 // construct with just one associated for-loop is linear with a
6616 // constant-linear-step that is the increment of the associated for-loop.
6617 // Exclude loop var from the list of variables with implicitly defined data
6618 // sharing attributes.
6619 VarsWithImplicitDSA.erase(LCDecl);
6620
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006621 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6622
6623 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006624 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006625
6626 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006627 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006628 }
6629
Alexey Bataeve3727102018-04-18 15:57:46 +00006630 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006631 return HasErrors;
6632
Alexander Musmana5f070a2014-10-01 06:03:56 +00006633 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006634 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
6635 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006636 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6637 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6638 (isOpenMPWorksharingDirective(DKind) ||
6639 isOpenMPTaskLoopDirective(DKind) ||
6640 isOpenMPDistributeDirective(DKind)),
6641 Captures);
6642 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6643 ISC.buildCounterVar(Captures, DSA);
6644 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6645 ISC.buildPrivateCounterVar();
6646 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6647 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6648 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6649 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6650 ISC.getConditionSrcRange();
6651 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6652 ISC.getIncrementSrcRange();
6653 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6654 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6655 ISC.isStrictTestOp();
6656 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6657 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6658 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6659 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6660 ISC.buildFinalCondition(DSA.getCurScope());
6661 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6662 ISC.doesInitDependOnLC();
6663 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6664 ISC.doesCondDependOnLC();
6665 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6666 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006667
Alexey Bataevf8be4762019-08-14 19:30:06 +00006668 HasErrors |=
6669 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6670 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6671 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6672 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6673 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6674 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006675 if (!HasErrors && DSA.isOrderedRegion()) {
6676 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6677 if (CurrentNestedLoopCount <
6678 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6679 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006680 CurrentNestedLoopCount,
6681 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006682 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006683 CurrentNestedLoopCount,
6684 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006685 }
6686 }
6687 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6688 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6689 // Erroneous case - clause has some problems.
6690 continue;
6691 }
6692 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6693 Pair.second.size() <= CurrentNestedLoopCount) {
6694 // Erroneous case - clause has some problems.
6695 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6696 continue;
6697 }
6698 Expr *CntValue;
6699 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6700 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006701 DSA.getCurScope(),
6702 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006703 Pair.first->getDependencyLoc());
6704 else
6705 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006706 DSA.getCurScope(),
6707 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006708 Pair.first->getDependencyLoc(),
6709 Pair.second[CurrentNestedLoopCount].first,
6710 Pair.second[CurrentNestedLoopCount].second);
6711 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6712 }
6713 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006714
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006715 return HasErrors;
6716}
6717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006718/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006719static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006720buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006721 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006722 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006723 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006724 ExprResult NewStart = IsNonRectangularLB
6725 ? Start.get()
6726 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006727 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006728 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006729 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006730 VarRef.get()->getType())) {
6731 NewStart = SemaRef.PerformImplicitConversion(
6732 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6733 /*AllowExplicit=*/true);
6734 if (!NewStart.isUsable())
6735 return ExprError();
6736 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006737
Alexey Bataeve3727102018-04-18 15:57:46 +00006738 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006739 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6740 return Init;
6741}
6742
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006743/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006744static ExprResult buildCounterUpdate(
6745 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6746 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006747 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006748 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006749 // Add parentheses (for debugging purposes only).
6750 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
6751 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
6752 !Step.isUsable())
6753 return ExprError();
6754
Alexey Bataev5a3af132016-03-29 08:58:54 +00006755 ExprResult NewStep = Step;
6756 if (Captures)
6757 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006758 if (NewStep.isInvalid())
6759 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006760 ExprResult Update =
6761 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006762 if (!Update.isUsable())
6763 return ExprError();
6764
Alexey Bataevc0214e02016-02-16 12:13:49 +00006765 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
6766 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006767 if (!Start.isUsable())
6768 return ExprError();
6769 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
6770 if (!NewStart.isUsable())
6771 return ExprError();
6772 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006773 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006774 if (NewStart.isInvalid())
6775 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006776
Alexey Bataevc0214e02016-02-16 12:13:49 +00006777 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
6778 ExprResult SavedUpdate = Update;
6779 ExprResult UpdateVal;
6780 if (VarRef.get()->getType()->isOverloadableType() ||
6781 NewStart.get()->getType()->isOverloadableType() ||
6782 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006783 Sema::TentativeAnalysisScope Trap(SemaRef);
6784
Alexey Bataevc0214e02016-02-16 12:13:49 +00006785 Update =
6786 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6787 if (Update.isUsable()) {
6788 UpdateVal =
6789 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
6790 VarRef.get(), SavedUpdate.get());
6791 if (UpdateVal.isUsable()) {
6792 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
6793 UpdateVal.get());
6794 }
6795 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006796 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006797
Alexey Bataevc0214e02016-02-16 12:13:49 +00006798 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
6799 if (!Update.isUsable() || !UpdateVal.isUsable()) {
6800 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
6801 NewStart.get(), SavedUpdate.get());
6802 if (!Update.isUsable())
6803 return ExprError();
6804
Alexey Bataev11481f52016-02-17 10:29:05 +00006805 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
6806 VarRef.get()->getType())) {
6807 Update = SemaRef.PerformImplicitConversion(
6808 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
6809 if (!Update.isUsable())
6810 return ExprError();
6811 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006812
6813 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
6814 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006815 return Update;
6816}
6817
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006818/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006819/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006820static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006821 if (E == nullptr)
6822 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006823 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006824 QualType OldType = E->getType();
6825 unsigned HasBits = C.getTypeSize(OldType);
6826 if (HasBits >= Bits)
6827 return ExprResult(E);
6828 // OK to convert to signed, because new type has more bits than old.
6829 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
6830 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
6831 true);
6832}
6833
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006834/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006835/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006836static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006837 if (E == nullptr)
6838 return false;
6839 llvm::APSInt Result;
6840 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
6841 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
6842 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006843}
6844
Alexey Bataev5a3af132016-03-29 08:58:54 +00006845/// Build preinits statement for the given declarations.
6846static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00006847 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006848 if (!PreInits.empty()) {
6849 return new (Context) DeclStmt(
6850 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
6851 SourceLocation(), SourceLocation());
6852 }
6853 return nullptr;
6854}
6855
6856/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00006857static Stmt *
6858buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00006859 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006860 if (!Captures.empty()) {
6861 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00006862 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006863 PreInits.push_back(Pair.second->getDecl());
6864 return buildPreInits(Context, PreInits);
6865 }
6866 return nullptr;
6867}
6868
6869/// Build postupdate expression for the given list of postupdates expressions.
6870static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
6871 Expr *PostUpdate = nullptr;
6872 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006873 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006874 Expr *ConvE = S.BuildCStyleCastExpr(
6875 E->getExprLoc(),
6876 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
6877 E->getExprLoc(), E)
6878 .get();
6879 PostUpdate = PostUpdate
6880 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
6881 PostUpdate, ConvE)
6882 .get()
6883 : ConvE;
6884 }
6885 }
6886 return PostUpdate;
6887}
6888
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006889/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00006890/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6891/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006892static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00006893checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00006894 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6895 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00006896 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00006897 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006898 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006899 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006900 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006901 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006902 if (!CollapseLoopCountExpr->isValueDependent() &&
6903 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006904 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006905 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006906 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006907 return 1;
6908 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00006909 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006910 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006911 if (OrderedLoopCountExpr) {
6912 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006913 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006914 if (!OrderedLoopCountExpr->isValueDependent() &&
6915 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6916 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006917 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006918 if (Result.getLimitedValue() < NestedLoopCount) {
6919 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6920 diag::err_omp_wrong_ordered_loop_count)
6921 << OrderedLoopCountExpr->getSourceRange();
6922 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6923 diag::note_collapse_loop_count)
6924 << CollapseLoopCountExpr->getSourceRange();
6925 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006926 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006927 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006928 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006929 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006930 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006931 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006932 // This is helper routine for loop directives (e.g., 'for', 'simd',
6933 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006934 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006935 SmallVector<LoopIterationSpace, 4> IterSpaces(
6936 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006937 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006938 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006939 if (checkOpenMPIterationSpace(
6940 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6941 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006942 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006943 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006944 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006945 // OpenMP [2.8.1, simd construct, Restrictions]
6946 // All loops associated with the construct must be perfectly nested; that
6947 // is, there must be no intervening code nor any OpenMP directive between
6948 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006949 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
6950 CurStmt = For->getBody();
6951 } else {
6952 assert(isa<CXXForRangeStmt>(CurStmt) &&
6953 "Expected canonical for or range-based for loops.");
6954 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
6955 }
6956 CurStmt = CurStmt->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006957 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006958 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6959 if (checkOpenMPIterationSpace(
6960 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6961 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006962 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00006963 return 0;
6964 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6965 // Handle initialization of captured loop iterator variables.
6966 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6967 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6968 Captures[DRE] = DRE;
6969 }
6970 }
6971 // Move on to the next nested for loop, or to the loop body.
6972 // OpenMP [2.8.1, simd construct, Restrictions]
6973 // All loops associated with the construct must be perfectly nested; that
6974 // is, there must be no intervening code nor any OpenMP directive between
6975 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00006976 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
6977 CurStmt = For->getBody();
6978 } else {
6979 assert(isa<CXXForRangeStmt>(CurStmt) &&
6980 "Expected canonical for or range-based for loops.");
6981 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
6982 }
6983 CurStmt = CurStmt->IgnoreContainers();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006984 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006985
Alexander Musmana5f070a2014-10-01 06:03:56 +00006986 Built.clear(/* size */ NestedLoopCount);
6987
6988 if (SemaRef.CurContext->isDependentContext())
6989 return NestedLoopCount;
6990
6991 // An example of what is generated for the following code:
6992 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006993 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006994 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006995 // for (k = 0; k < NK; ++k)
6996 // for (j = J0; j < NJ; j+=2) {
6997 // <loop body>
6998 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006999 //
7000 // We generate the code below.
7001 // Note: the loop body may be outlined in CodeGen.
7002 // Note: some counters may be C++ classes, operator- is used to find number of
7003 // iterations and operator+= to calculate counter value.
7004 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7005 // or i64 is currently supported).
7006 //
7007 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7008 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7009 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7010 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7011 // // similar updates for vars in clauses (e.g. 'linear')
7012 // <loop body (using local i and j)>
7013 // }
7014 // i = NI; // assign final values of counters
7015 // j = NJ;
7016 //
7017
7018 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7019 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007020 // Precondition tests if there is at least one iteration (all conditions are
7021 // true).
7022 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007023 Expr *N0 = IterSpaces[0].NumIterations;
7024 ExprResult LastIteration32 =
7025 widenIterationCount(/*Bits=*/32,
7026 SemaRef
7027 .PerformImplicitConversion(
7028 N0->IgnoreImpCasts(), N0->getType(),
7029 Sema::AA_Converting, /*AllowExplicit=*/true)
7030 .get(),
7031 SemaRef);
7032 ExprResult LastIteration64 = widenIterationCount(
7033 /*Bits=*/64,
7034 SemaRef
7035 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7036 Sema::AA_Converting,
7037 /*AllowExplicit=*/true)
7038 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007039 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007040
7041 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7042 return NestedLoopCount;
7043
Alexey Bataeve3727102018-04-18 15:57:46 +00007044 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007045 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7046
7047 Scope *CurScope = DSA.getCurScope();
7048 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007049 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007050 PreCond =
7051 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7052 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007053 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007054 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007055 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007056 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7057 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007058 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007059 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007060 SemaRef
7061 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7062 Sema::AA_Converting,
7063 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007064 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007065 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007066 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007067 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007068 SemaRef
7069 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7070 Sema::AA_Converting,
7071 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007072 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007073 }
7074
7075 // Choose either the 32-bit or 64-bit version.
7076 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007077 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7078 (LastIteration32.isUsable() &&
7079 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7080 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7081 fitsInto(
7082 /*Bits=*/32,
7083 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7084 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007085 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007086 QualType VType = LastIteration.get()->getType();
7087 QualType RealVType = VType;
7088 QualType StrideVType = VType;
7089 if (isOpenMPTaskLoopDirective(DKind)) {
7090 VType =
7091 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7092 StrideVType =
7093 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7094 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007095
7096 if (!LastIteration.isUsable())
7097 return 0;
7098
7099 // Save the number of iterations.
7100 ExprResult NumIterations = LastIteration;
7101 {
7102 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007103 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7104 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007105 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7106 if (!LastIteration.isUsable())
7107 return 0;
7108 }
7109
7110 // Calculate the last iteration number beforehand instead of doing this on
7111 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7112 llvm::APSInt Result;
7113 bool IsConstant =
7114 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7115 ExprResult CalcLastIteration;
7116 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007117 ExprResult SaveRef =
7118 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007119 LastIteration = SaveRef;
7120
7121 // Prepare SaveRef + 1.
7122 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007123 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007124 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7125 if (!NumIterations.isUsable())
7126 return 0;
7127 }
7128
7129 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7130
David Majnemer9d168222016-08-05 17:44:54 +00007131 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007132 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007133 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7134 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007135 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007136 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7137 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007138 SemaRef.AddInitializerToDecl(LBDecl,
7139 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7140 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007141
7142 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007143 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7144 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007145 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007146 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007147
7148 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7149 // This will be used to implement clause 'lastprivate'.
7150 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007151 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7152 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007153 SemaRef.AddInitializerToDecl(ILDecl,
7154 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7155 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007156
7157 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007158 VarDecl *STDecl =
7159 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7160 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007161 SemaRef.AddInitializerToDecl(STDecl,
7162 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7163 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007164
7165 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007166 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007167 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7168 UB.get(), LastIteration.get());
7169 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007170 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7171 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007172 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7173 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007174 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007175
7176 // If we have a combined directive that combines 'distribute', 'for' or
7177 // 'simd' we need to be able to access the bounds of the schedule of the
7178 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7179 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7180 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007181 // Lower bound variable, initialized with zero.
7182 VarDecl *CombLBDecl =
7183 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7184 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7185 SemaRef.AddInitializerToDecl(
7186 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7187 /*DirectInit*/ false);
7188
7189 // Upper bound variable, initialized with last iteration number.
7190 VarDecl *CombUBDecl =
7191 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7192 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7193 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7194 /*DirectInit*/ false);
7195
7196 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7197 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7198 ExprResult CombCondOp =
7199 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7200 LastIteration.get(), CombUB.get());
7201 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7202 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007203 CombEUB =
7204 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007205
Alexey Bataeve3727102018-04-18 15:57:46 +00007206 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007207 // We expect to have at least 2 more parameters than the 'parallel'
7208 // directive does - the lower and upper bounds of the previous schedule.
7209 assert(CD->getNumParams() >= 4 &&
7210 "Unexpected number of parameters in loop combined directive");
7211
7212 // Set the proper type for the bounds given what we learned from the
7213 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007214 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7215 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007216
7217 // Previous lower and upper bounds are obtained from the region
7218 // parameters.
7219 PrevLB =
7220 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7221 PrevUB =
7222 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7223 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007224 }
7225
7226 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007227 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007228 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007229 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007230 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7231 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007232 Expr *RHS =
7233 (isOpenMPWorksharingDirective(DKind) ||
7234 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7235 ? LB.get()
7236 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007237 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007238 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007239
7240 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7241 Expr *CombRHS =
7242 (isOpenMPWorksharingDirective(DKind) ||
7243 isOpenMPTaskLoopDirective(DKind) ||
7244 isOpenMPDistributeDirective(DKind))
7245 ? CombLB.get()
7246 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7247 CombInit =
7248 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007249 CombInit =
7250 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007251 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007252 }
7253
Alexey Bataev316ccf62019-01-29 18:51:58 +00007254 bool UseStrictCompare =
7255 RealVType->hasUnsignedIntegerRepresentation() &&
7256 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7257 return LIS.IsStrictCompare;
7258 });
7259 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7260 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007261 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007262 Expr *BoundUB = UB.get();
7263 if (UseStrictCompare) {
7264 BoundUB =
7265 SemaRef
7266 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7267 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7268 .get();
7269 BoundUB =
7270 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7271 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007272 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007273 (isOpenMPWorksharingDirective(DKind) ||
7274 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007275 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7276 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7277 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007278 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7279 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007280 ExprResult CombDistCond;
7281 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007282 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7283 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007284 }
7285
Carlo Bertolliffafe102017-04-20 00:39:39 +00007286 ExprResult CombCond;
7287 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007288 Expr *BoundCombUB = CombUB.get();
7289 if (UseStrictCompare) {
7290 BoundCombUB =
7291 SemaRef
7292 .BuildBinOp(
7293 CurScope, CondLoc, BO_Add, BoundCombUB,
7294 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7295 .get();
7296 BoundCombUB =
7297 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7298 .get();
7299 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007300 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007301 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7302 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007303 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007304 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007305 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007306 ExprResult Inc =
7307 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7308 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7309 if (!Inc.isUsable())
7310 return 0;
7311 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007312 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007313 if (!Inc.isUsable())
7314 return 0;
7315
7316 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7317 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007318 // In combined construct, add combined version that use CombLB and CombUB
7319 // base variables for the update
7320 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007321 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7322 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007323 // LB + ST
7324 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7325 if (!NextLB.isUsable())
7326 return 0;
7327 // LB = LB + ST
7328 NextLB =
7329 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007330 NextLB =
7331 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007332 if (!NextLB.isUsable())
7333 return 0;
7334 // UB + ST
7335 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7336 if (!NextUB.isUsable())
7337 return 0;
7338 // UB = UB + ST
7339 NextUB =
7340 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007341 NextUB =
7342 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007343 if (!NextUB.isUsable())
7344 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007345 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7346 CombNextLB =
7347 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7348 if (!NextLB.isUsable())
7349 return 0;
7350 // LB = LB + ST
7351 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7352 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007353 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7354 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007355 if (!CombNextLB.isUsable())
7356 return 0;
7357 // UB + ST
7358 CombNextUB =
7359 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7360 if (!CombNextUB.isUsable())
7361 return 0;
7362 // UB = UB + ST
7363 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7364 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007365 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7366 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007367 if (!CombNextUB.isUsable())
7368 return 0;
7369 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007370 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007371
Carlo Bertolliffafe102017-04-20 00:39:39 +00007372 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007373 // directive with for as IV = IV + ST; ensure upper bound expression based
7374 // on PrevUB instead of NumIterations - used to implement 'for' when found
7375 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007376 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007377 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007378 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007379 DistCond = SemaRef.BuildBinOp(
7380 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007381 assert(DistCond.isUsable() && "distribute cond expr was not built");
7382
7383 DistInc =
7384 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7385 assert(DistInc.isUsable() && "distribute inc expr was not built");
7386 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7387 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007388 DistInc =
7389 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007390 assert(DistInc.isUsable() && "distribute inc expr was not built");
7391
7392 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7393 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007394 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007395 ExprResult IsUBGreater =
7396 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7397 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7398 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7399 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7400 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007401 PrevEUB =
7402 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007403
Alexey Bataev316ccf62019-01-29 18:51:58 +00007404 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7405 // parallel for is in combination with a distribute directive with
7406 // schedule(static, 1)
7407 Expr *BoundPrevUB = PrevUB.get();
7408 if (UseStrictCompare) {
7409 BoundPrevUB =
7410 SemaRef
7411 .BuildBinOp(
7412 CurScope, CondLoc, BO_Add, BoundPrevUB,
7413 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7414 .get();
7415 BoundPrevUB =
7416 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7417 .get();
7418 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007419 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007420 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7421 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007422 }
7423
Alexander Musmana5f070a2014-10-01 06:03:56 +00007424 // Build updates and final values of the loop counters.
7425 bool HasErrors = false;
7426 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007427 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007428 Built.Updates.resize(NestedLoopCount);
7429 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007430 Built.DependentCounters.resize(NestedLoopCount);
7431 Built.DependentInits.resize(NestedLoopCount);
7432 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007433 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007434 // We implement the following algorithm for obtaining the
7435 // original loop iteration variable values based on the
7436 // value of the collapsed loop iteration variable IV.
7437 //
7438 // Let n+1 be the number of collapsed loops in the nest.
7439 // Iteration variables (I0, I1, .... In)
7440 // Iteration counts (N0, N1, ... Nn)
7441 //
7442 // Acc = IV;
7443 //
7444 // To compute Ik for loop k, 0 <= k <= n, generate:
7445 // Prod = N(k+1) * N(k+2) * ... * Nn;
7446 // Ik = Acc / Prod;
7447 // Acc -= Ik * Prod;
7448 //
7449 ExprResult Acc = IV;
7450 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007451 LoopIterationSpace &IS = IterSpaces[Cnt];
7452 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007453 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007454
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007455 // Compute prod
7456 ExprResult Prod =
7457 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7458 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7459 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7460 IterSpaces[K].NumIterations);
7461
7462 // Iter = Acc / Prod
7463 // If there is at least one more inner loop to avoid
7464 // multiplication by 1.
7465 if (Cnt + 1 < NestedLoopCount)
7466 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7467 Acc.get(), Prod.get());
7468 else
7469 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007470 if (!Iter.isUsable()) {
7471 HasErrors = true;
7472 break;
7473 }
7474
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007475 // Update Acc:
7476 // Acc -= Iter * Prod
7477 // Check if there is at least one more inner loop to avoid
7478 // multiplication by 1.
7479 if (Cnt + 1 < NestedLoopCount)
7480 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7481 Iter.get(), Prod.get());
7482 else
7483 Prod = Iter;
7484 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7485 Acc.get(), Prod.get());
7486
Alexey Bataev39f915b82015-05-08 10:41:21 +00007487 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007488 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007489 DeclRefExpr *CounterVar = buildDeclRefExpr(
7490 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7491 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007492 ExprResult Init =
7493 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7494 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007495 if (!Init.isUsable()) {
7496 HasErrors = true;
7497 break;
7498 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007499 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007500 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007501 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007502 if (!Update.isUsable()) {
7503 HasErrors = true;
7504 break;
7505 }
7506
7507 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007508 ExprResult Final =
7509 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7510 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7511 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007512 if (!Final.isUsable()) {
7513 HasErrors = true;
7514 break;
7515 }
7516
Alexander Musmana5f070a2014-10-01 06:03:56 +00007517 if (!Update.isUsable() || !Final.isUsable()) {
7518 HasErrors = true;
7519 break;
7520 }
7521 // Save results
7522 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007523 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007524 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007525 Built.Updates[Cnt] = Update.get();
7526 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007527 Built.DependentCounters[Cnt] = nullptr;
7528 Built.DependentInits[Cnt] = nullptr;
7529 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007530 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007531 Built.DependentCounters[Cnt] =
7532 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7533 Built.DependentInits[Cnt] =
7534 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7535 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7536 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007537 }
7538 }
7539
7540 if (HasErrors)
7541 return 0;
7542
7543 // Save results
7544 Built.IterationVarRef = IV.get();
7545 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007546 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007547 Built.CalcLastIteration = SemaRef
7548 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007549 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007550 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007551 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007552 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007553 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007554 Built.Init = Init.get();
7555 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007556 Built.LB = LB.get();
7557 Built.UB = UB.get();
7558 Built.IL = IL.get();
7559 Built.ST = ST.get();
7560 Built.EUB = EUB.get();
7561 Built.NLB = NextLB.get();
7562 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007563 Built.PrevLB = PrevLB.get();
7564 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007565 Built.DistInc = DistInc.get();
7566 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007567 Built.DistCombinedFields.LB = CombLB.get();
7568 Built.DistCombinedFields.UB = CombUB.get();
7569 Built.DistCombinedFields.EUB = CombEUB.get();
7570 Built.DistCombinedFields.Init = CombInit.get();
7571 Built.DistCombinedFields.Cond = CombCond.get();
7572 Built.DistCombinedFields.NLB = CombNextLB.get();
7573 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007574 Built.DistCombinedFields.DistCond = CombDistCond.get();
7575 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007576
Alexey Bataevabfc0692014-06-25 06:52:00 +00007577 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007578}
7579
Alexey Bataev10e775f2015-07-30 11:36:16 +00007580static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007581 auto CollapseClauses =
7582 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7583 if (CollapseClauses.begin() != CollapseClauses.end())
7584 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007585 return nullptr;
7586}
7587
Alexey Bataev10e775f2015-07-30 11:36:16 +00007588static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007589 auto OrderedClauses =
7590 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7591 if (OrderedClauses.begin() != OrderedClauses.end())
7592 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007593 return nullptr;
7594}
7595
Kelvin Lic5609492016-07-15 04:39:07 +00007596static bool checkSimdlenSafelenSpecified(Sema &S,
7597 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007598 const OMPSafelenClause *Safelen = nullptr;
7599 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007600
Alexey Bataeve3727102018-04-18 15:57:46 +00007601 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007602 if (Clause->getClauseKind() == OMPC_safelen)
7603 Safelen = cast<OMPSafelenClause>(Clause);
7604 else if (Clause->getClauseKind() == OMPC_simdlen)
7605 Simdlen = cast<OMPSimdlenClause>(Clause);
7606 if (Safelen && Simdlen)
7607 break;
7608 }
7609
7610 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007611 const Expr *SimdlenLength = Simdlen->getSimdlen();
7612 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007613 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7614 SimdlenLength->isInstantiationDependent() ||
7615 SimdlenLength->containsUnexpandedParameterPack())
7616 return false;
7617 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7618 SafelenLength->isInstantiationDependent() ||
7619 SafelenLength->containsUnexpandedParameterPack())
7620 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007621 Expr::EvalResult SimdlenResult, SafelenResult;
7622 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7623 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7624 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7625 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007626 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7627 // If both simdlen and safelen clauses are specified, the value of the
7628 // simdlen parameter must be less than or equal to the value of the safelen
7629 // parameter.
7630 if (SimdlenRes > SafelenRes) {
7631 S.Diag(SimdlenLength->getExprLoc(),
7632 diag::err_omp_wrong_simdlen_safelen_values)
7633 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7634 return true;
7635 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007636 }
7637 return false;
7638}
7639
Alexey Bataeve3727102018-04-18 15:57:46 +00007640StmtResult
7641Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7642 SourceLocation StartLoc, SourceLocation EndLoc,
7643 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007644 if (!AStmt)
7645 return StmtError();
7646
7647 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007648 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007649 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7650 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007651 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007652 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7653 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007654 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007655 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007656
Alexander Musmana5f070a2014-10-01 06:03:56 +00007657 assert((CurContext->isDependentContext() || B.builtAll()) &&
7658 "omp simd loop exprs were not built");
7659
Alexander Musman3276a272015-03-21 10:12:56 +00007660 if (!CurContext->isDependentContext()) {
7661 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007662 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007663 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007664 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007665 B.NumIterations, *this, CurScope,
7666 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007667 return StmtError();
7668 }
7669 }
7670
Kelvin Lic5609492016-07-15 04:39:07 +00007671 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007672 return StmtError();
7673
Reid Kleckner87a31802018-03-12 21:43:02 +00007674 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007675 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7676 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007677}
7678
Alexey Bataeve3727102018-04-18 15:57:46 +00007679StmtResult
7680Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7681 SourceLocation StartLoc, SourceLocation EndLoc,
7682 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007683 if (!AStmt)
7684 return StmtError();
7685
7686 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007687 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007688 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7689 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007690 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007691 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7692 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007693 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007694 return StmtError();
7695
Alexander Musmana5f070a2014-10-01 06:03:56 +00007696 assert((CurContext->isDependentContext() || B.builtAll()) &&
7697 "omp for loop exprs were not built");
7698
Alexey Bataev54acd402015-08-04 11:18:19 +00007699 if (!CurContext->isDependentContext()) {
7700 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007701 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007702 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007703 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007704 B.NumIterations, *this, CurScope,
7705 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007706 return StmtError();
7707 }
7708 }
7709
Reid Kleckner87a31802018-03-12 21:43:02 +00007710 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007711 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007712 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007713}
7714
Alexander Musmanf82886e2014-09-18 05:12:34 +00007715StmtResult Sema::ActOnOpenMPForSimdDirective(
7716 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007717 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007718 if (!AStmt)
7719 return StmtError();
7720
7721 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007722 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007723 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7724 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007725 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007726 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007727 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7728 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007729 if (NestedLoopCount == 0)
7730 return StmtError();
7731
Alexander Musmanc6388682014-12-15 07:07:06 +00007732 assert((CurContext->isDependentContext() || B.builtAll()) &&
7733 "omp for simd loop exprs were not built");
7734
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007735 if (!CurContext->isDependentContext()) {
7736 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007737 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007738 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007739 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007740 B.NumIterations, *this, CurScope,
7741 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007742 return StmtError();
7743 }
7744 }
7745
Kelvin Lic5609492016-07-15 04:39:07 +00007746 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007747 return StmtError();
7748
Reid Kleckner87a31802018-03-12 21:43:02 +00007749 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007750 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7751 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007752}
7753
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007754StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7755 Stmt *AStmt,
7756 SourceLocation StartLoc,
7757 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007758 if (!AStmt)
7759 return StmtError();
7760
7761 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007762 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007763 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007764 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007765 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007766 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007767 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007768 return StmtError();
7769 // All associated statements must be '#pragma omp section' except for
7770 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007771 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007772 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7773 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007774 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007775 diag::err_omp_sections_substmt_not_section);
7776 return StmtError();
7777 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007778 cast<OMPSectionDirective>(SectionStmt)
7779 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007780 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007781 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007782 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007783 return StmtError();
7784 }
7785
Reid Kleckner87a31802018-03-12 21:43:02 +00007786 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007787
Alexey Bataev25e5b442015-09-15 12:52:43 +00007788 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7789 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007790}
7791
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007792StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
7793 SourceLocation StartLoc,
7794 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007795 if (!AStmt)
7796 return StmtError();
7797
7798 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007799
Reid Kleckner87a31802018-03-12 21:43:02 +00007800 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00007801 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007802
Alexey Bataev25e5b442015-09-15 12:52:43 +00007803 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
7804 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007805}
7806
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007807StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7808 Stmt *AStmt,
7809 SourceLocation StartLoc,
7810 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007811 if (!AStmt)
7812 return StmtError();
7813
7814 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00007815
Reid Kleckner87a31802018-03-12 21:43:02 +00007816 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00007817
Alexey Bataev3255bf32015-01-19 05:20:46 +00007818 // OpenMP [2.7.3, single Construct, Restrictions]
7819 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00007820 const OMPClause *Nowait = nullptr;
7821 const OMPClause *Copyprivate = nullptr;
7822 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00007823 if (Clause->getClauseKind() == OMPC_nowait)
7824 Nowait = Clause;
7825 else if (Clause->getClauseKind() == OMPC_copyprivate)
7826 Copyprivate = Clause;
7827 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007828 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00007829 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007830 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00007831 return StmtError();
7832 }
7833 }
7834
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007835 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7836}
7837
Alexander Musman80c22892014-07-17 08:54:58 +00007838StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
7839 SourceLocation StartLoc,
7840 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007841 if (!AStmt)
7842 return StmtError();
7843
7844 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00007845
Reid Kleckner87a31802018-03-12 21:43:02 +00007846 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00007847
7848 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
7849}
7850
Alexey Bataev28c75412015-12-15 08:19:24 +00007851StmtResult Sema::ActOnOpenMPCriticalDirective(
7852 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
7853 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007854 if (!AStmt)
7855 return StmtError();
7856
7857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007858
Alexey Bataev28c75412015-12-15 08:19:24 +00007859 bool ErrorFound = false;
7860 llvm::APSInt Hint;
7861 SourceLocation HintLoc;
7862 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007863 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007864 if (C->getClauseKind() == OMPC_hint) {
7865 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007866 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00007867 ErrorFound = true;
7868 }
7869 Expr *E = cast<OMPHintClause>(C)->getHint();
7870 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00007871 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007872 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007873 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00007874 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007875 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00007876 }
7877 }
7878 }
7879 if (ErrorFound)
7880 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007881 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00007882 if (Pair.first && DirName.getName() && !DependentHint) {
7883 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
7884 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00007885 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00007886 Diag(HintLoc, diag::note_omp_critical_hint_here)
7887 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007888 else
Alexey Bataev28c75412015-12-15 08:19:24 +00007889 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00007890 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007891 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00007892 << 1
7893 << C->getHint()->EvaluateKnownConstInt(Context).toString(
7894 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007895 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007896 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00007897 }
Alexey Bataev28c75412015-12-15 08:19:24 +00007898 }
7899 }
7900
Reid Kleckner87a31802018-03-12 21:43:02 +00007901 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007902
Alexey Bataev28c75412015-12-15 08:19:24 +00007903 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
7904 Clauses, AStmt);
7905 if (!Pair.first && DirName.getName() && !DependentHint)
7906 DSAStack->addCriticalWithHint(Dir, Hint);
7907 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007908}
7909
Alexey Bataev4acb8592014-07-07 13:01:15 +00007910StmtResult Sema::ActOnOpenMPParallelForDirective(
7911 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007912 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007913 if (!AStmt)
7914 return StmtError();
7915
Alexey Bataeve3727102018-04-18 15:57:46 +00007916 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007917 // 1.2.2 OpenMP Language Terminology
7918 // Structured block - An executable statement with a single entry at the
7919 // top and a single exit at the bottom.
7920 // The point of exit cannot be a branch out of the structured block.
7921 // longjmp() and throw() must not violate the entry/exit criteria.
7922 CS->getCapturedDecl()->setNothrow();
7923
Alexander Musmanc6388682014-12-15 07:07:06 +00007924 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007925 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7926 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007927 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007928 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007929 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7930 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007931 if (NestedLoopCount == 0)
7932 return StmtError();
7933
Alexander Musmana5f070a2014-10-01 06:03:56 +00007934 assert((CurContext->isDependentContext() || B.builtAll()) &&
7935 "omp parallel for loop exprs were not built");
7936
Alexey Bataev54acd402015-08-04 11:18:19 +00007937 if (!CurContext->isDependentContext()) {
7938 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007939 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007940 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007941 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007942 B.NumIterations, *this, CurScope,
7943 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007944 return StmtError();
7945 }
7946 }
7947
Reid Kleckner87a31802018-03-12 21:43:02 +00007948 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007949 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007950 NestedLoopCount, Clauses, AStmt, B,
7951 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00007952}
7953
Alexander Musmane4e893b2014-09-23 09:33:00 +00007954StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
7955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007956 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007957 if (!AStmt)
7958 return StmtError();
7959
Alexey Bataeve3727102018-04-18 15:57:46 +00007960 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007961 // 1.2.2 OpenMP Language Terminology
7962 // Structured block - An executable statement with a single entry at the
7963 // top and a single exit at the bottom.
7964 // The point of exit cannot be a branch out of the structured block.
7965 // longjmp() and throw() must not violate the entry/exit criteria.
7966 CS->getCapturedDecl()->setNothrow();
7967
Alexander Musmanc6388682014-12-15 07:07:06 +00007968 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007969 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7970 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007971 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007972 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007973 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7974 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007975 if (NestedLoopCount == 0)
7976 return StmtError();
7977
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007978 if (!CurContext->isDependentContext()) {
7979 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007980 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007981 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007982 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007983 B.NumIterations, *this, CurScope,
7984 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007985 return StmtError();
7986 }
7987 }
7988
Kelvin Lic5609492016-07-15 04:39:07 +00007989 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007990 return StmtError();
7991
Reid Kleckner87a31802018-03-12 21:43:02 +00007992 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007993 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007994 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007995}
7996
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007997StmtResult
7998Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7999 Stmt *AStmt, SourceLocation StartLoc,
8000 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008001 if (!AStmt)
8002 return StmtError();
8003
8004 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008005 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008006 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008007 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008008 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008009 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008010 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008011 return StmtError();
8012 // All associated statements must be '#pragma omp section' except for
8013 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008014 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008015 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8016 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008017 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008018 diag::err_omp_parallel_sections_substmt_not_section);
8019 return StmtError();
8020 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008021 cast<OMPSectionDirective>(SectionStmt)
8022 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008023 }
8024 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008025 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008026 diag::err_omp_parallel_sections_not_compound_stmt);
8027 return StmtError();
8028 }
8029
Reid Kleckner87a31802018-03-12 21:43:02 +00008030 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008031
Alexey Bataev25e5b442015-09-15 12:52:43 +00008032 return OMPParallelSectionsDirective::Create(
8033 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008034}
8035
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008036StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8037 Stmt *AStmt, SourceLocation StartLoc,
8038 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008039 if (!AStmt)
8040 return StmtError();
8041
David Majnemer9d168222016-08-05 17:44:54 +00008042 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008043 // 1.2.2 OpenMP Language Terminology
8044 // Structured block - An executable statement with a single entry at the
8045 // top and a single exit at the bottom.
8046 // The point of exit cannot be a branch out of the structured block.
8047 // longjmp() and throw() must not violate the entry/exit criteria.
8048 CS->getCapturedDecl()->setNothrow();
8049
Reid Kleckner87a31802018-03-12 21:43:02 +00008050 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008051
Alexey Bataev25e5b442015-09-15 12:52:43 +00008052 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8053 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008054}
8055
Alexey Bataev68446b72014-07-18 07:47:19 +00008056StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8057 SourceLocation EndLoc) {
8058 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8059}
8060
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008061StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8062 SourceLocation EndLoc) {
8063 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8064}
8065
Alexey Bataev2df347a2014-07-18 10:17:07 +00008066StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8067 SourceLocation EndLoc) {
8068 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8069}
8070
Alexey Bataev169d96a2017-07-18 20:17:46 +00008071StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8072 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008073 SourceLocation StartLoc,
8074 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008075 if (!AStmt)
8076 return StmtError();
8077
8078 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008079
Reid Kleckner87a31802018-03-12 21:43:02 +00008080 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008081
Alexey Bataev169d96a2017-07-18 20:17:46 +00008082 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008083 AStmt,
8084 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008085}
8086
Alexey Bataev6125da92014-07-21 11:26:11 +00008087StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8088 SourceLocation StartLoc,
8089 SourceLocation EndLoc) {
8090 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8091 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8092}
8093
Alexey Bataev346265e2015-09-25 10:37:12 +00008094StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8095 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008096 SourceLocation StartLoc,
8097 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008098 const OMPClause *DependFound = nullptr;
8099 const OMPClause *DependSourceClause = nullptr;
8100 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008101 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008102 const OMPThreadsClause *TC = nullptr;
8103 const OMPSIMDClause *SC = nullptr;
8104 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008105 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8106 DependFound = C;
8107 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8108 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008109 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008110 << getOpenMPDirectiveName(OMPD_ordered)
8111 << getOpenMPClauseName(OMPC_depend) << 2;
8112 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008113 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008114 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008115 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008116 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008117 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008118 << 0;
8119 ErrorFound = true;
8120 }
8121 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8122 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008123 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008124 << 1;
8125 ErrorFound = true;
8126 }
8127 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008128 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008129 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008130 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008131 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008132 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008133 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008134 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008135 if (!ErrorFound && !SC &&
8136 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008137 // OpenMP [2.8.1,simd Construct, Restrictions]
8138 // An ordered construct with the simd clause is the only OpenMP construct
8139 // that can appear in the simd region.
8140 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00008141 ErrorFound = true;
8142 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008143 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008144 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8145 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008146 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008147 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008148 diag::err_omp_ordered_directive_without_param);
8149 ErrorFound = true;
8150 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008151 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008152 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008153 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8154 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008155 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008156 ErrorFound = true;
8157 }
8158 }
8159 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008160 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008161
8162 if (AStmt) {
8163 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8164
Reid Kleckner87a31802018-03-12 21:43:02 +00008165 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008166 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008167
8168 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008169}
8170
Alexey Bataev1d160b12015-03-13 12:27:31 +00008171namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008172/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008173/// construct.
8174class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008175 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008176 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008177 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008178 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008179 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008180 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008181 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008182 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008183 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008184 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008185 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008186 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008187 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008188 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008189 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008190 /// expression.
8191 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008192 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008193 /// part.
8194 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008195 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008196 NoError
8197 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008198 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008199 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008200 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008201 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008202 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008203 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008204 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008205 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008206 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008207 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8208 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8209 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008210 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008211 /// important for non-associative operations.
8212 bool IsXLHSInRHSPart;
8213 BinaryOperatorKind Op;
8214 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008215 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008216 /// if it is a prefix unary operation.
8217 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008218
8219public:
8220 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008221 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008222 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008223 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008224 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008225 /// expression. If DiagId and NoteId == 0, then only check is performed
8226 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008227 /// \param DiagId Diagnostic which should be emitted if error is found.
8228 /// \param NoteId Diagnostic note for the main error message.
8229 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008230 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008231 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008232 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008233 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008234 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008235 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008236 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8237 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8238 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008239 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008240 /// false otherwise.
8241 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8242
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008243 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008244 /// if it is a prefix unary operation.
8245 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8246
Alexey Bataev1d160b12015-03-13 12:27:31 +00008247private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008248 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8249 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008250};
8251} // namespace
8252
8253bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8254 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8255 ExprAnalysisErrorCode ErrorFound = NoError;
8256 SourceLocation ErrorLoc, NoteLoc;
8257 SourceRange ErrorRange, NoteRange;
8258 // Allowed constructs are:
8259 // x = x binop expr;
8260 // x = expr binop x;
8261 if (AtomicBinOp->getOpcode() == BO_Assign) {
8262 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008263 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008264 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8265 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8266 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8267 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008268 Op = AtomicInnerBinOp->getOpcode();
8269 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008270 Expr *LHS = AtomicInnerBinOp->getLHS();
8271 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008272 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8273 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8274 /*Canonical=*/true);
8275 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8276 /*Canonical=*/true);
8277 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8278 /*Canonical=*/true);
8279 if (XId == LHSId) {
8280 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008281 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008282 } else if (XId == RHSId) {
8283 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008284 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008285 } else {
8286 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8287 ErrorRange = AtomicInnerBinOp->getSourceRange();
8288 NoteLoc = X->getExprLoc();
8289 NoteRange = X->getSourceRange();
8290 ErrorFound = NotAnUpdateExpression;
8291 }
8292 } else {
8293 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8294 ErrorRange = AtomicInnerBinOp->getSourceRange();
8295 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8296 NoteRange = SourceRange(NoteLoc, NoteLoc);
8297 ErrorFound = NotABinaryOperator;
8298 }
8299 } else {
8300 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8301 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8302 ErrorFound = NotABinaryExpression;
8303 }
8304 } else {
8305 ErrorLoc = AtomicBinOp->getExprLoc();
8306 ErrorRange = AtomicBinOp->getSourceRange();
8307 NoteLoc = AtomicBinOp->getOperatorLoc();
8308 NoteRange = SourceRange(NoteLoc, NoteLoc);
8309 ErrorFound = NotAnAssignmentOp;
8310 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008311 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008312 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8313 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8314 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008315 }
8316 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008317 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008318 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008319}
8320
8321bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8322 unsigned NoteId) {
8323 ExprAnalysisErrorCode ErrorFound = NoError;
8324 SourceLocation ErrorLoc, NoteLoc;
8325 SourceRange ErrorRange, NoteRange;
8326 // Allowed constructs are:
8327 // x++;
8328 // x--;
8329 // ++x;
8330 // --x;
8331 // x binop= expr;
8332 // x = x binop expr;
8333 // x = expr binop x;
8334 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8335 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8336 if (AtomicBody->getType()->isScalarType() ||
8337 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008338 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008339 AtomicBody->IgnoreParenImpCasts())) {
8340 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008341 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008342 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008343 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008344 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008345 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008346 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008347 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8348 AtomicBody->IgnoreParenImpCasts())) {
8349 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008350 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008351 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008352 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008353 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008354 // Check for Unary Operation
8355 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008356 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008357 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8358 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008359 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008360 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8361 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008362 } else {
8363 ErrorFound = NotAnUnaryIncDecExpression;
8364 ErrorLoc = AtomicUnaryOp->getExprLoc();
8365 ErrorRange = AtomicUnaryOp->getSourceRange();
8366 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8367 NoteRange = SourceRange(NoteLoc, NoteLoc);
8368 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008369 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008370 ErrorFound = NotABinaryOrUnaryExpression;
8371 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8372 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8373 }
8374 } else {
8375 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008376 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008377 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8378 }
8379 } else {
8380 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008381 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008382 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8383 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008384 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008385 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8386 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8387 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008388 }
8389 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008390 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008391 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008392 // Build an update expression of form 'OpaqueValueExpr(x) binop
8393 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8394 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8395 auto *OVEX = new (SemaRef.getASTContext())
8396 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8397 auto *OVEExpr = new (SemaRef.getASTContext())
8398 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008399 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008400 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8401 IsXLHSInRHSPart ? OVEExpr : OVEX);
8402 if (Update.isInvalid())
8403 return true;
8404 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8405 Sema::AA_Casting);
8406 if (Update.isInvalid())
8407 return true;
8408 UpdateExpr = Update.get();
8409 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008410 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008411}
8412
Alexey Bataev0162e452014-07-22 10:10:35 +00008413StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8414 Stmt *AStmt,
8415 SourceLocation StartLoc,
8416 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008417 if (!AStmt)
8418 return StmtError();
8419
David Majnemer9d168222016-08-05 17:44:54 +00008420 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008421 // 1.2.2 OpenMP Language Terminology
8422 // Structured block - An executable statement with a single entry at the
8423 // top and a single exit at the bottom.
8424 // The point of exit cannot be a branch out of the structured block.
8425 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008426 OpenMPClauseKind AtomicKind = OMPC_unknown;
8427 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008428 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008429 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008430 C->getClauseKind() == OMPC_update ||
8431 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008432 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008433 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008434 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008435 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8436 << getOpenMPClauseName(AtomicKind);
8437 } else {
8438 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008439 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008440 }
8441 }
8442 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008443
Alexey Bataeve3727102018-04-18 15:57:46 +00008444 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008445 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8446 Body = EWC->getSubExpr();
8447
Alexey Bataev62cec442014-11-18 10:14:22 +00008448 Expr *X = nullptr;
8449 Expr *V = nullptr;
8450 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008451 Expr *UE = nullptr;
8452 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008453 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008454 // OpenMP [2.12.6, atomic Construct]
8455 // In the next expressions:
8456 // * x and v (as applicable) are both l-value expressions with scalar type.
8457 // * During the execution of an atomic region, multiple syntactic
8458 // occurrences of x must designate the same storage location.
8459 // * Neither of v and expr (as applicable) may access the storage location
8460 // designated by x.
8461 // * Neither of x and expr (as applicable) may access the storage location
8462 // designated by v.
8463 // * expr is an expression with scalar type.
8464 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8465 // * binop, binop=, ++, and -- are not overloaded operators.
8466 // * The expression x binop expr must be numerically equivalent to x binop
8467 // (expr). This requirement is satisfied if the operators in expr have
8468 // precedence greater than binop, or by using parentheses around expr or
8469 // subexpressions of expr.
8470 // * The expression expr binop x must be numerically equivalent to (expr)
8471 // binop x. This requirement is satisfied if the operators in expr have
8472 // precedence equal to or greater than binop, or by using parentheses around
8473 // expr or subexpressions of expr.
8474 // * For forms that allow multiple occurrences of x, the number of times
8475 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008476 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008477 enum {
8478 NotAnExpression,
8479 NotAnAssignmentOp,
8480 NotAScalarType,
8481 NotAnLValue,
8482 NoError
8483 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008484 SourceLocation ErrorLoc, NoteLoc;
8485 SourceRange ErrorRange, NoteRange;
8486 // If clause is read:
8487 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008488 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8489 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008490 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8491 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8492 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8493 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8494 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8495 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8496 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008497 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008498 ErrorFound = NotAnLValue;
8499 ErrorLoc = AtomicBinOp->getExprLoc();
8500 ErrorRange = AtomicBinOp->getSourceRange();
8501 NoteLoc = NotLValueExpr->getExprLoc();
8502 NoteRange = NotLValueExpr->getSourceRange();
8503 }
8504 } else if (!X->isInstantiationDependent() ||
8505 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008506 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008507 (X->isInstantiationDependent() || X->getType()->isScalarType())
8508 ? V
8509 : X;
8510 ErrorFound = NotAScalarType;
8511 ErrorLoc = AtomicBinOp->getExprLoc();
8512 ErrorRange = AtomicBinOp->getSourceRange();
8513 NoteLoc = NotScalarExpr->getExprLoc();
8514 NoteRange = NotScalarExpr->getSourceRange();
8515 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008516 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008517 ErrorFound = NotAnAssignmentOp;
8518 ErrorLoc = AtomicBody->getExprLoc();
8519 ErrorRange = AtomicBody->getSourceRange();
8520 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8521 : AtomicBody->getExprLoc();
8522 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8523 : AtomicBody->getSourceRange();
8524 }
8525 } else {
8526 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008527 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008528 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008529 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008530 if (ErrorFound != NoError) {
8531 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8532 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008533 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8534 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008535 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008536 }
8537 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008538 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008539 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008540 enum {
8541 NotAnExpression,
8542 NotAnAssignmentOp,
8543 NotAScalarType,
8544 NotAnLValue,
8545 NoError
8546 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008547 SourceLocation ErrorLoc, NoteLoc;
8548 SourceRange ErrorRange, NoteRange;
8549 // If clause is write:
8550 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008551 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8552 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008553 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8554 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008555 X = AtomicBinOp->getLHS();
8556 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008557 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8558 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8559 if (!X->isLValue()) {
8560 ErrorFound = NotAnLValue;
8561 ErrorLoc = AtomicBinOp->getExprLoc();
8562 ErrorRange = AtomicBinOp->getSourceRange();
8563 NoteLoc = X->getExprLoc();
8564 NoteRange = X->getSourceRange();
8565 }
8566 } else if (!X->isInstantiationDependent() ||
8567 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008568 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008569 (X->isInstantiationDependent() || X->getType()->isScalarType())
8570 ? E
8571 : X;
8572 ErrorFound = NotAScalarType;
8573 ErrorLoc = AtomicBinOp->getExprLoc();
8574 ErrorRange = AtomicBinOp->getSourceRange();
8575 NoteLoc = NotScalarExpr->getExprLoc();
8576 NoteRange = NotScalarExpr->getSourceRange();
8577 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008578 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008579 ErrorFound = NotAnAssignmentOp;
8580 ErrorLoc = AtomicBody->getExprLoc();
8581 ErrorRange = AtomicBody->getSourceRange();
8582 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8583 : AtomicBody->getExprLoc();
8584 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8585 : AtomicBody->getSourceRange();
8586 }
8587 } else {
8588 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008589 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008590 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008591 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008592 if (ErrorFound != NoError) {
8593 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8594 << ErrorRange;
8595 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8596 << NoteRange;
8597 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008598 }
8599 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008600 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008601 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008602 // If clause is update:
8603 // x++;
8604 // x--;
8605 // ++x;
8606 // --x;
8607 // x binop= expr;
8608 // x = x binop expr;
8609 // x = expr binop x;
8610 OpenMPAtomicUpdateChecker Checker(*this);
8611 if (Checker.checkStatement(
8612 Body, (AtomicKind == OMPC_update)
8613 ? diag::err_omp_atomic_update_not_expression_statement
8614 : diag::err_omp_atomic_not_expression_statement,
8615 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008616 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008617 if (!CurContext->isDependentContext()) {
8618 E = Checker.getExpr();
8619 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008620 UE = Checker.getUpdateExpr();
8621 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008622 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008623 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008624 enum {
8625 NotAnAssignmentOp,
8626 NotACompoundStatement,
8627 NotTwoSubstatements,
8628 NotASpecificExpression,
8629 NoError
8630 } ErrorFound = NoError;
8631 SourceLocation ErrorLoc, NoteLoc;
8632 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008633 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008634 // If clause is a capture:
8635 // v = x++;
8636 // v = x--;
8637 // v = ++x;
8638 // v = --x;
8639 // v = x binop= expr;
8640 // v = x = x binop expr;
8641 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008642 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008643 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8644 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8645 V = AtomicBinOp->getLHS();
8646 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8647 OpenMPAtomicUpdateChecker Checker(*this);
8648 if (Checker.checkStatement(
8649 Body, diag::err_omp_atomic_capture_not_expression_statement,
8650 diag::note_omp_atomic_update))
8651 return StmtError();
8652 E = Checker.getExpr();
8653 X = Checker.getX();
8654 UE = Checker.getUpdateExpr();
8655 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8656 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008657 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008658 ErrorLoc = AtomicBody->getExprLoc();
8659 ErrorRange = AtomicBody->getSourceRange();
8660 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8661 : AtomicBody->getExprLoc();
8662 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8663 : AtomicBody->getSourceRange();
8664 ErrorFound = NotAnAssignmentOp;
8665 }
8666 if (ErrorFound != NoError) {
8667 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8668 << ErrorRange;
8669 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8670 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008671 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008672 if (CurContext->isDependentContext())
8673 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008674 } else {
8675 // If clause is a capture:
8676 // { v = x; x = expr; }
8677 // { v = x; x++; }
8678 // { v = x; x--; }
8679 // { v = x; ++x; }
8680 // { v = x; --x; }
8681 // { v = x; x binop= expr; }
8682 // { v = x; x = x binop expr; }
8683 // { v = x; x = expr binop x; }
8684 // { x++; v = x; }
8685 // { x--; v = x; }
8686 // { ++x; v = x; }
8687 // { --x; v = x; }
8688 // { x binop= expr; v = x; }
8689 // { x = x binop expr; v = x; }
8690 // { x = expr binop x; v = x; }
8691 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8692 // Check that this is { expr1; expr2; }
8693 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008694 Stmt *First = CS->body_front();
8695 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008696 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8697 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8698 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8699 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8700 // Need to find what subexpression is 'v' and what is 'x'.
8701 OpenMPAtomicUpdateChecker Checker(*this);
8702 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8703 BinaryOperator *BinOp = nullptr;
8704 if (IsUpdateExprFound) {
8705 BinOp = dyn_cast<BinaryOperator>(First);
8706 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8707 }
8708 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8709 // { v = x; x++; }
8710 // { v = x; x--; }
8711 // { v = x; ++x; }
8712 // { v = x; --x; }
8713 // { v = x; x binop= expr; }
8714 // { v = x; x = x binop expr; }
8715 // { v = x; x = expr binop x; }
8716 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008717 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008718 llvm::FoldingSetNodeID XId, PossibleXId;
8719 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8720 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8721 IsUpdateExprFound = XId == PossibleXId;
8722 if (IsUpdateExprFound) {
8723 V = BinOp->getLHS();
8724 X = Checker.getX();
8725 E = Checker.getExpr();
8726 UE = Checker.getUpdateExpr();
8727 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008728 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008729 }
8730 }
8731 if (!IsUpdateExprFound) {
8732 IsUpdateExprFound = !Checker.checkStatement(First);
8733 BinOp = nullptr;
8734 if (IsUpdateExprFound) {
8735 BinOp = dyn_cast<BinaryOperator>(Second);
8736 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8737 }
8738 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8739 // { x++; v = x; }
8740 // { x--; v = x; }
8741 // { ++x; v = x; }
8742 // { --x; v = x; }
8743 // { x binop= expr; v = x; }
8744 // { x = x binop expr; v = x; }
8745 // { x = expr binop x; v = x; }
8746 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008747 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008748 llvm::FoldingSetNodeID XId, PossibleXId;
8749 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8750 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8751 IsUpdateExprFound = XId == PossibleXId;
8752 if (IsUpdateExprFound) {
8753 V = BinOp->getLHS();
8754 X = Checker.getX();
8755 E = Checker.getExpr();
8756 UE = Checker.getUpdateExpr();
8757 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008758 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008759 }
8760 }
8761 }
8762 if (!IsUpdateExprFound) {
8763 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00008764 auto *FirstExpr = dyn_cast<Expr>(First);
8765 auto *SecondExpr = dyn_cast<Expr>(Second);
8766 if (!FirstExpr || !SecondExpr ||
8767 !(FirstExpr->isInstantiationDependent() ||
8768 SecondExpr->isInstantiationDependent())) {
8769 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
8770 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008771 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00008772 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008773 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008774 NoteRange = ErrorRange = FirstBinOp
8775 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00008776 : SourceRange(ErrorLoc, ErrorLoc);
8777 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00008778 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
8779 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
8780 ErrorFound = NotAnAssignmentOp;
8781 NoteLoc = ErrorLoc = SecondBinOp
8782 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008783 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008784 NoteRange = ErrorRange =
8785 SecondBinOp ? SecondBinOp->getSourceRange()
8786 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00008787 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008788 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00008789 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00008790 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00008791 SecondBinOp->getLHS()->IgnoreParenImpCasts();
8792 llvm::FoldingSetNodeID X1Id, X2Id;
8793 PossibleXRHSInFirst->Profile(X1Id, Context,
8794 /*Canonical=*/true);
8795 PossibleXLHSInSecond->Profile(X2Id, Context,
8796 /*Canonical=*/true);
8797 IsUpdateExprFound = X1Id == X2Id;
8798 if (IsUpdateExprFound) {
8799 V = FirstBinOp->getLHS();
8800 X = SecondBinOp->getLHS();
8801 E = SecondBinOp->getRHS();
8802 UE = nullptr;
8803 IsXLHSInRHSPart = false;
8804 IsPostfixUpdate = true;
8805 } else {
8806 ErrorFound = NotASpecificExpression;
8807 ErrorLoc = FirstBinOp->getExprLoc();
8808 ErrorRange = FirstBinOp->getSourceRange();
8809 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
8810 NoteRange = SecondBinOp->getRHS()->getSourceRange();
8811 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008812 }
8813 }
8814 }
8815 }
8816 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008817 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008818 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008819 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008820 ErrorFound = NotTwoSubstatements;
8821 }
8822 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008823 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008824 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008825 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008826 ErrorFound = NotACompoundStatement;
8827 }
8828 if (ErrorFound != NoError) {
8829 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
8830 << ErrorRange;
8831 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8832 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008833 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008834 if (CurContext->isDependentContext())
8835 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00008836 }
Alexey Bataevdea47612014-07-23 07:46:59 +00008837 }
Alexey Bataev0162e452014-07-22 10:10:35 +00008838
Reid Kleckner87a31802018-03-12 21:43:02 +00008839 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00008840
Alexey Bataev62cec442014-11-18 10:14:22 +00008841 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00008842 X, V, E, UE, IsXLHSInRHSPart,
8843 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00008844}
8845
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008846StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8847 Stmt *AStmt,
8848 SourceLocation StartLoc,
8849 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008850 if (!AStmt)
8851 return StmtError();
8852
Alexey Bataeve3727102018-04-18 15:57:46 +00008853 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00008854 // 1.2.2 OpenMP Language Terminology
8855 // Structured block - An executable statement with a single entry at the
8856 // top and a single exit at the bottom.
8857 // The point of exit cannot be a branch out of the structured block.
8858 // longjmp() and throw() must not violate the entry/exit criteria.
8859 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008860 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
8861 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8862 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8863 // 1.2.2 OpenMP Language Terminology
8864 // Structured block - An executable statement with a single entry at the
8865 // top and a single exit at the bottom.
8866 // The point of exit cannot be a branch out of the structured block.
8867 // longjmp() and throw() must not violate the entry/exit criteria.
8868 CS->getCapturedDecl()->setNothrow();
8869 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008870
Alexey Bataev13314bf2014-10-09 04:18:56 +00008871 // OpenMP [2.16, Nesting of Regions]
8872 // If specified, a teams construct must be contained within a target
8873 // construct. That target construct must contain no statements or directives
8874 // outside of the teams construct.
8875 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008876 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008877 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008878 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00008879 auto I = CS->body_begin();
8880 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008881 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00008882 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
8883 OMPTeamsFound) {
8884
Alexey Bataev13314bf2014-10-09 04:18:56 +00008885 OMPTeamsFound = false;
8886 break;
8887 }
8888 ++I;
8889 }
8890 assert(I != CS->body_end() && "Not found statement");
8891 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00008892 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008893 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00008894 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00008895 }
8896 if (!OMPTeamsFound) {
8897 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
8898 Diag(DSAStack->getInnerTeamsRegionLoc(),
8899 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008900 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00008901 << isa<OMPExecutableDirective>(S);
8902 return StmtError();
8903 }
8904 }
8905
Reid Kleckner87a31802018-03-12 21:43:02 +00008906 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008907
8908 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8909}
8910
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008911StmtResult
8912Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8913 Stmt *AStmt, SourceLocation StartLoc,
8914 SourceLocation EndLoc) {
8915 if (!AStmt)
8916 return StmtError();
8917
Alexey Bataeve3727102018-04-18 15:57:46 +00008918 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008919 // 1.2.2 OpenMP Language Terminology
8920 // Structured block - An executable statement with a single entry at the
8921 // top and a single exit at the bottom.
8922 // The point of exit cannot be a branch out of the structured block.
8923 // longjmp() and throw() must not violate the entry/exit criteria.
8924 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008925 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8926 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8927 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8928 // 1.2.2 OpenMP Language Terminology
8929 // Structured block - An executable statement with a single entry at the
8930 // top and a single exit at the bottom.
8931 // The point of exit cannot be a branch out of the structured block.
8932 // longjmp() and throw() must not violate the entry/exit criteria.
8933 CS->getCapturedDecl()->setNothrow();
8934 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008935
Reid Kleckner87a31802018-03-12 21:43:02 +00008936 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008937
8938 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8939 AStmt);
8940}
8941
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008942StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
8943 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008944 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008945 if (!AStmt)
8946 return StmtError();
8947
Alexey Bataeve3727102018-04-18 15:57:46 +00008948 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008949 // 1.2.2 OpenMP Language Terminology
8950 // Structured block - An executable statement with a single entry at the
8951 // top and a single exit at the bottom.
8952 // The point of exit cannot be a branch out of the structured block.
8953 // longjmp() and throw() must not violate the entry/exit criteria.
8954 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008955 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8956 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8957 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8958 // 1.2.2 OpenMP Language Terminology
8959 // Structured block - An executable statement with a single entry at the
8960 // top and a single exit at the bottom.
8961 // The point of exit cannot be a branch out of the structured block.
8962 // longjmp() and throw() must not violate the entry/exit criteria.
8963 CS->getCapturedDecl()->setNothrow();
8964 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008965
8966 OMPLoopDirective::HelperExprs B;
8967 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8968 // define the nested loops number.
8969 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008970 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008971 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008972 VarsWithImplicitDSA, B);
8973 if (NestedLoopCount == 0)
8974 return StmtError();
8975
8976 assert((CurContext->isDependentContext() || B.builtAll()) &&
8977 "omp target parallel for loop exprs were not built");
8978
8979 if (!CurContext->isDependentContext()) {
8980 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008981 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008982 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008983 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008984 B.NumIterations, *this, CurScope,
8985 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008986 return StmtError();
8987 }
8988 }
8989
Reid Kleckner87a31802018-03-12 21:43:02 +00008990 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008991 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8992 NestedLoopCount, Clauses, AStmt,
8993 B, DSAStack->isCancelRegion());
8994}
8995
Alexey Bataev95b64a92017-05-30 16:00:04 +00008996/// Check for existence of a map clause in the list of clauses.
8997static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8998 const OpenMPClauseKind K) {
8999 return llvm::any_of(
9000 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9001}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009002
Alexey Bataev95b64a92017-05-30 16:00:04 +00009003template <typename... Params>
9004static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9005 const Params... ClauseTypes) {
9006 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009007}
9008
Michael Wong65f367f2015-07-21 13:44:28 +00009009StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9010 Stmt *AStmt,
9011 SourceLocation StartLoc,
9012 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009013 if (!AStmt)
9014 return StmtError();
9015
9016 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9017
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009018 // OpenMP [2.10.1, Restrictions, p. 97]
9019 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009020 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9021 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9022 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009023 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009024 return StmtError();
9025 }
9026
Reid Kleckner87a31802018-03-12 21:43:02 +00009027 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009028
9029 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9030 AStmt);
9031}
9032
Samuel Antaodf67fc42016-01-19 19:15:56 +00009033StmtResult
9034Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9035 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009036 SourceLocation EndLoc, Stmt *AStmt) {
9037 if (!AStmt)
9038 return StmtError();
9039
Alexey Bataeve3727102018-04-18 15:57:46 +00009040 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009041 // 1.2.2 OpenMP Language Terminology
9042 // Structured block - An executable statement with a single entry at the
9043 // top and a single exit at the bottom.
9044 // The point of exit cannot be a branch out of the structured block.
9045 // longjmp() and throw() must not violate the entry/exit criteria.
9046 CS->getCapturedDecl()->setNothrow();
9047 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9048 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9049 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9050 // 1.2.2 OpenMP Language Terminology
9051 // Structured block - An executable statement with a single entry at the
9052 // top and a single exit at the bottom.
9053 // The point of exit cannot be a branch out of the structured block.
9054 // longjmp() and throw() must not violate the entry/exit criteria.
9055 CS->getCapturedDecl()->setNothrow();
9056 }
9057
Samuel Antaodf67fc42016-01-19 19:15:56 +00009058 // OpenMP [2.10.2, Restrictions, p. 99]
9059 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009060 if (!hasClauses(Clauses, OMPC_map)) {
9061 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9062 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009063 return StmtError();
9064 }
9065
Alexey Bataev7828b252017-11-21 17:08:48 +00009066 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9067 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009068}
9069
Samuel Antao72590762016-01-19 20:04:50 +00009070StmtResult
9071Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9072 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009073 SourceLocation EndLoc, Stmt *AStmt) {
9074 if (!AStmt)
9075 return StmtError();
9076
Alexey Bataeve3727102018-04-18 15:57:46 +00009077 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009078 // 1.2.2 OpenMP Language Terminology
9079 // Structured block - An executable statement with a single entry at the
9080 // top and a single exit at the bottom.
9081 // The point of exit cannot be a branch out of the structured block.
9082 // longjmp() and throw() must not violate the entry/exit criteria.
9083 CS->getCapturedDecl()->setNothrow();
9084 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9085 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9086 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9087 // 1.2.2 OpenMP Language Terminology
9088 // Structured block - An executable statement with a single entry at the
9089 // top and a single exit at the bottom.
9090 // The point of exit cannot be a branch out of the structured block.
9091 // longjmp() and throw() must not violate the entry/exit criteria.
9092 CS->getCapturedDecl()->setNothrow();
9093 }
9094
Samuel Antao72590762016-01-19 20:04:50 +00009095 // OpenMP [2.10.3, Restrictions, p. 102]
9096 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009097 if (!hasClauses(Clauses, OMPC_map)) {
9098 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9099 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009100 return StmtError();
9101 }
9102
Alexey Bataev7828b252017-11-21 17:08:48 +00009103 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9104 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009105}
9106
Samuel Antao686c70c2016-05-26 17:30:50 +00009107StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9108 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009109 SourceLocation EndLoc,
9110 Stmt *AStmt) {
9111 if (!AStmt)
9112 return StmtError();
9113
Alexey Bataeve3727102018-04-18 15:57:46 +00009114 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009115 // 1.2.2 OpenMP Language Terminology
9116 // Structured block - An executable statement with a single entry at the
9117 // top and a single exit at the bottom.
9118 // The point of exit cannot be a branch out of the structured block.
9119 // longjmp() and throw() must not violate the entry/exit criteria.
9120 CS->getCapturedDecl()->setNothrow();
9121 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9122 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9123 CS = cast<CapturedStmt>(CS->getCapturedStmt());
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();
9130 }
9131
Alexey Bataev95b64a92017-05-30 16:00:04 +00009132 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009133 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9134 return StmtError();
9135 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009136 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9137 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009138}
9139
Alexey Bataev13314bf2014-10-09 04:18:56 +00009140StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9141 Stmt *AStmt, SourceLocation StartLoc,
9142 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009143 if (!AStmt)
9144 return StmtError();
9145
Alexey Bataeve3727102018-04-18 15:57:46 +00009146 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009147 // 1.2.2 OpenMP Language Terminology
9148 // Structured block - An executable statement with a single entry at the
9149 // top and a single exit at the bottom.
9150 // The point of exit cannot be a branch out of the structured block.
9151 // longjmp() and throw() must not violate the entry/exit criteria.
9152 CS->getCapturedDecl()->setNothrow();
9153
Reid Kleckner87a31802018-03-12 21:43:02 +00009154 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009155
Alexey Bataevceabd412017-11-30 18:01:54 +00009156 DSAStack->setParentTeamsRegionLoc(StartLoc);
9157
Alexey Bataev13314bf2014-10-09 04:18:56 +00009158 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9159}
9160
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009161StmtResult
9162Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9163 SourceLocation EndLoc,
9164 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009165 if (DSAStack->isParentNowaitRegion()) {
9166 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9167 return StmtError();
9168 }
9169 if (DSAStack->isParentOrderedRegion()) {
9170 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9171 return StmtError();
9172 }
9173 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9174 CancelRegion);
9175}
9176
Alexey Bataev87933c72015-09-18 08:07:34 +00009177StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9178 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009179 SourceLocation EndLoc,
9180 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009181 if (DSAStack->isParentNowaitRegion()) {
9182 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9183 return StmtError();
9184 }
9185 if (DSAStack->isParentOrderedRegion()) {
9186 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9187 return StmtError();
9188 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009189 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009190 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9191 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009192}
9193
Alexey Bataev382967a2015-12-08 12:06:20 +00009194static bool checkGrainsizeNumTasksClauses(Sema &S,
9195 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009196 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009197 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009198 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009199 if (C->getClauseKind() == OMPC_grainsize ||
9200 C->getClauseKind() == OMPC_num_tasks) {
9201 if (!PrevClause)
9202 PrevClause = C;
9203 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009204 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009205 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9206 << getOpenMPClauseName(C->getClauseKind())
9207 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009208 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009209 diag::note_omp_previous_grainsize_num_tasks)
9210 << getOpenMPClauseName(PrevClause->getClauseKind());
9211 ErrorFound = true;
9212 }
9213 }
9214 }
9215 return ErrorFound;
9216}
9217
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009218static bool checkReductionClauseWithNogroup(Sema &S,
9219 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009220 const OMPClause *ReductionClause = nullptr;
9221 const OMPClause *NogroupClause = nullptr;
9222 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009223 if (C->getClauseKind() == OMPC_reduction) {
9224 ReductionClause = C;
9225 if (NogroupClause)
9226 break;
9227 continue;
9228 }
9229 if (C->getClauseKind() == OMPC_nogroup) {
9230 NogroupClause = C;
9231 if (ReductionClause)
9232 break;
9233 continue;
9234 }
9235 }
9236 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009237 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9238 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009239 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009240 return true;
9241 }
9242 return false;
9243}
9244
Alexey Bataev49f6e782015-12-01 04:18:41 +00009245StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9246 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009247 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009248 if (!AStmt)
9249 return StmtError();
9250
9251 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9252 OMPLoopDirective::HelperExprs B;
9253 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9254 // define the nested loops number.
9255 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009256 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009257 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009258 VarsWithImplicitDSA, B);
9259 if (NestedLoopCount == 0)
9260 return StmtError();
9261
9262 assert((CurContext->isDependentContext() || B.builtAll()) &&
9263 "omp for loop exprs were not built");
9264
Alexey Bataev382967a2015-12-08 12:06:20 +00009265 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9266 // The grainsize clause and num_tasks clause are mutually exclusive and may
9267 // not appear on the same taskloop directive.
9268 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9269 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009270 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9271 // If a reduction clause is present on the taskloop directive, the nogroup
9272 // clause must not be specified.
9273 if (checkReductionClauseWithNogroup(*this, Clauses))
9274 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009275
Reid Kleckner87a31802018-03-12 21:43:02 +00009276 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009277 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9278 NestedLoopCount, Clauses, AStmt, B);
9279}
9280
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009281StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9282 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009283 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009284 if (!AStmt)
9285 return StmtError();
9286
9287 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9288 OMPLoopDirective::HelperExprs B;
9289 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9290 // define the nested loops number.
9291 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009292 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009293 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9294 VarsWithImplicitDSA, B);
9295 if (NestedLoopCount == 0)
9296 return StmtError();
9297
9298 assert((CurContext->isDependentContext() || B.builtAll()) &&
9299 "omp for loop exprs were not built");
9300
Alexey Bataev5a3af132016-03-29 08:58:54 +00009301 if (!CurContext->isDependentContext()) {
9302 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009303 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009304 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009305 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009306 B.NumIterations, *this, CurScope,
9307 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009308 return StmtError();
9309 }
9310 }
9311
Alexey Bataev382967a2015-12-08 12:06:20 +00009312 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9313 // The grainsize clause and num_tasks clause are mutually exclusive and may
9314 // not appear on the same taskloop directive.
9315 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9316 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009317 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9318 // If a reduction clause is present on the taskloop directive, the nogroup
9319 // clause must not be specified.
9320 if (checkReductionClauseWithNogroup(*this, Clauses))
9321 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009322 if (checkSimdlenSafelenSpecified(*this, Clauses))
9323 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009324
Reid Kleckner87a31802018-03-12 21:43:02 +00009325 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009326 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9327 NestedLoopCount, Clauses, AStmt, B);
9328}
9329
Alexey Bataev60e51c42019-10-10 20:13:02 +00009330StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9331 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9332 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9333 if (!AStmt)
9334 return StmtError();
9335
9336 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9337 OMPLoopDirective::HelperExprs B;
9338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9339 // define the nested loops number.
9340 unsigned NestedLoopCount =
9341 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9342 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9343 VarsWithImplicitDSA, B);
9344 if (NestedLoopCount == 0)
9345 return StmtError();
9346
9347 assert((CurContext->isDependentContext() || B.builtAll()) &&
9348 "omp for loop exprs were not built");
9349
9350 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9351 // The grainsize clause and num_tasks clause are mutually exclusive and may
9352 // not appear on the same taskloop directive.
9353 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9354 return StmtError();
9355 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9356 // If a reduction clause is present on the taskloop directive, the nogroup
9357 // clause must not be specified.
9358 if (checkReductionClauseWithNogroup(*this, Clauses))
9359 return StmtError();
9360
9361 setFunctionHasBranchProtectedScope();
9362 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9363 NestedLoopCount, Clauses, AStmt, B);
9364}
9365
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009366StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9367 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9368 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9369 if (!AStmt)
9370 return StmtError();
9371
9372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9373 OMPLoopDirective::HelperExprs B;
9374 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9375 // define the nested loops number.
9376 unsigned NestedLoopCount =
9377 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9378 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9379 VarsWithImplicitDSA, B);
9380 if (NestedLoopCount == 0)
9381 return StmtError();
9382
9383 assert((CurContext->isDependentContext() || B.builtAll()) &&
9384 "omp for loop exprs were not built");
9385
9386 if (!CurContext->isDependentContext()) {
9387 // Finalize the clauses that need pre-built expressions for CodeGen.
9388 for (OMPClause *C : Clauses) {
9389 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9390 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9391 B.NumIterations, *this, CurScope,
9392 DSAStack))
9393 return StmtError();
9394 }
9395 }
9396
9397 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9398 // The grainsize clause and num_tasks clause are mutually exclusive and may
9399 // not appear on the same taskloop directive.
9400 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9401 return StmtError();
9402 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9403 // If a reduction clause is present on the taskloop directive, the nogroup
9404 // clause must not be specified.
9405 if (checkReductionClauseWithNogroup(*this, Clauses))
9406 return StmtError();
9407 if (checkSimdlenSafelenSpecified(*this, Clauses))
9408 return StmtError();
9409
9410 setFunctionHasBranchProtectedScope();
9411 return OMPMasterTaskLoopSimdDirective::Create(
9412 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9413}
9414
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009415StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9416 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9417 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9418 if (!AStmt)
9419 return StmtError();
9420
9421 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9422 auto *CS = cast<CapturedStmt>(AStmt);
9423 // 1.2.2 OpenMP Language Terminology
9424 // Structured block - An executable statement with a single entry at the
9425 // top and a single exit at the bottom.
9426 // The point of exit cannot be a branch out of the structured block.
9427 // longjmp() and throw() must not violate the entry/exit criteria.
9428 CS->getCapturedDecl()->setNothrow();
9429 for (int ThisCaptureLevel =
9430 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9431 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9432 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9433 // 1.2.2 OpenMP Language Terminology
9434 // Structured block - An executable statement with a single entry at the
9435 // top and a single exit at the bottom.
9436 // The point of exit cannot be a branch out of the structured block.
9437 // longjmp() and throw() must not violate the entry/exit criteria.
9438 CS->getCapturedDecl()->setNothrow();
9439 }
9440
9441 OMPLoopDirective::HelperExprs B;
9442 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9443 // define the nested loops number.
9444 unsigned NestedLoopCount = checkOpenMPLoop(
9445 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9446 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9447 VarsWithImplicitDSA, B);
9448 if (NestedLoopCount == 0)
9449 return StmtError();
9450
9451 assert((CurContext->isDependentContext() || B.builtAll()) &&
9452 "omp for loop exprs were not built");
9453
9454 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9455 // The grainsize clause and num_tasks clause are mutually exclusive and may
9456 // not appear on the same taskloop directive.
9457 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9458 return StmtError();
9459 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9460 // If a reduction clause is present on the taskloop directive, the nogroup
9461 // clause must not be specified.
9462 if (checkReductionClauseWithNogroup(*this, Clauses))
9463 return StmtError();
9464
9465 setFunctionHasBranchProtectedScope();
9466 return OMPParallelMasterTaskLoopDirective::Create(
9467 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9468}
9469
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009470StmtResult Sema::ActOnOpenMPDistributeDirective(
9471 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009472 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009473 if (!AStmt)
9474 return StmtError();
9475
9476 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9477 OMPLoopDirective::HelperExprs B;
9478 // In presence of clause 'collapse' with number of loops, it will
9479 // define the nested loops number.
9480 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009481 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009482 nullptr /*ordered not a clause on distribute*/, AStmt,
9483 *this, *DSAStack, VarsWithImplicitDSA, B);
9484 if (NestedLoopCount == 0)
9485 return StmtError();
9486
9487 assert((CurContext->isDependentContext() || B.builtAll()) &&
9488 "omp for loop exprs were not built");
9489
Reid Kleckner87a31802018-03-12 21:43:02 +00009490 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009491 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9492 NestedLoopCount, Clauses, AStmt, B);
9493}
9494
Carlo Bertolli9925f152016-06-27 14:55:37 +00009495StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9496 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009497 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009498 if (!AStmt)
9499 return StmtError();
9500
Alexey Bataeve3727102018-04-18 15:57:46 +00009501 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009502 // 1.2.2 OpenMP Language Terminology
9503 // Structured block - An executable statement with a single entry at the
9504 // top and a single exit at the bottom.
9505 // The point of exit cannot be a branch out of the structured block.
9506 // longjmp() and throw() must not violate the entry/exit criteria.
9507 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009508 for (int ThisCaptureLevel =
9509 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9510 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9511 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9512 // 1.2.2 OpenMP Language Terminology
9513 // Structured block - An executable statement with a single entry at the
9514 // top and a single exit at the bottom.
9515 // The point of exit cannot be a branch out of the structured block.
9516 // longjmp() and throw() must not violate the entry/exit criteria.
9517 CS->getCapturedDecl()->setNothrow();
9518 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009519
9520 OMPLoopDirective::HelperExprs B;
9521 // In presence of clause 'collapse' with number of loops, it will
9522 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009523 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009524 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009525 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009526 VarsWithImplicitDSA, B);
9527 if (NestedLoopCount == 0)
9528 return StmtError();
9529
9530 assert((CurContext->isDependentContext() || B.builtAll()) &&
9531 "omp for loop exprs were not built");
9532
Reid Kleckner87a31802018-03-12 21:43:02 +00009533 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009534 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009535 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9536 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009537}
9538
Kelvin Li4a39add2016-07-05 05:00:15 +00009539StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9540 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009541 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009542 if (!AStmt)
9543 return StmtError();
9544
Alexey Bataeve3727102018-04-18 15:57:46 +00009545 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009546 // 1.2.2 OpenMP Language Terminology
9547 // Structured block - An executable statement with a single entry at the
9548 // top and a single exit at the bottom.
9549 // The point of exit cannot be a branch out of the structured block.
9550 // longjmp() and throw() must not violate the entry/exit criteria.
9551 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009552 for (int ThisCaptureLevel =
9553 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9554 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9555 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9556 // 1.2.2 OpenMP Language Terminology
9557 // Structured block - An executable statement with a single entry at the
9558 // top and a single exit at the bottom.
9559 // The point of exit cannot be a branch out of the structured block.
9560 // longjmp() and throw() must not violate the entry/exit criteria.
9561 CS->getCapturedDecl()->setNothrow();
9562 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009563
9564 OMPLoopDirective::HelperExprs B;
9565 // In presence of clause 'collapse' with number of loops, it will
9566 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009567 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009568 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009569 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009570 VarsWithImplicitDSA, B);
9571 if (NestedLoopCount == 0)
9572 return StmtError();
9573
9574 assert((CurContext->isDependentContext() || B.builtAll()) &&
9575 "omp for loop exprs were not built");
9576
Alexey Bataev438388c2017-11-22 18:34:02 +00009577 if (!CurContext->isDependentContext()) {
9578 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009579 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009580 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9581 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9582 B.NumIterations, *this, CurScope,
9583 DSAStack))
9584 return StmtError();
9585 }
9586 }
9587
Kelvin Lic5609492016-07-15 04:39:07 +00009588 if (checkSimdlenSafelenSpecified(*this, Clauses))
9589 return StmtError();
9590
Reid Kleckner87a31802018-03-12 21:43:02 +00009591 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009592 return OMPDistributeParallelForSimdDirective::Create(
9593 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9594}
9595
Kelvin Li787f3fc2016-07-06 04:45:38 +00009596StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9597 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009598 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009599 if (!AStmt)
9600 return StmtError();
9601
Alexey Bataeve3727102018-04-18 15:57:46 +00009602 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009603 // 1.2.2 OpenMP Language Terminology
9604 // Structured block - An executable statement with a single entry at the
9605 // top and a single exit at the bottom.
9606 // The point of exit cannot be a branch out of the structured block.
9607 // longjmp() and throw() must not violate the entry/exit criteria.
9608 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009609 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9610 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9611 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9612 // 1.2.2 OpenMP Language Terminology
9613 // Structured block - An executable statement with a single entry at the
9614 // top and a single exit at the bottom.
9615 // The point of exit cannot be a branch out of the structured block.
9616 // longjmp() and throw() must not violate the entry/exit criteria.
9617 CS->getCapturedDecl()->setNothrow();
9618 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009619
9620 OMPLoopDirective::HelperExprs B;
9621 // In presence of clause 'collapse' with number of loops, it will
9622 // define the nested loops number.
9623 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009624 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009625 nullptr /*ordered not a clause on distribute*/, CS, *this,
9626 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009627 if (NestedLoopCount == 0)
9628 return StmtError();
9629
9630 assert((CurContext->isDependentContext() || B.builtAll()) &&
9631 "omp for loop exprs were not built");
9632
Alexey Bataev438388c2017-11-22 18:34:02 +00009633 if (!CurContext->isDependentContext()) {
9634 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009635 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009636 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9637 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9638 B.NumIterations, *this, CurScope,
9639 DSAStack))
9640 return StmtError();
9641 }
9642 }
9643
Kelvin Lic5609492016-07-15 04:39:07 +00009644 if (checkSimdlenSafelenSpecified(*this, Clauses))
9645 return StmtError();
9646
Reid Kleckner87a31802018-03-12 21:43:02 +00009647 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009648 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9649 NestedLoopCount, Clauses, AStmt, B);
9650}
9651
Kelvin Lia579b912016-07-14 02:54:56 +00009652StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9653 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009654 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009655 if (!AStmt)
9656 return StmtError();
9657
Alexey Bataeve3727102018-04-18 15:57:46 +00009658 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009659 // 1.2.2 OpenMP Language Terminology
9660 // Structured block - An executable statement with a single entry at the
9661 // top and a single exit at the bottom.
9662 // The point of exit cannot be a branch out of the structured block.
9663 // longjmp() and throw() must not violate the entry/exit criteria.
9664 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009665 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9666 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9667 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9668 // 1.2.2 OpenMP Language Terminology
9669 // Structured block - An executable statement with a single entry at the
9670 // top and a single exit at the bottom.
9671 // The point of exit cannot be a branch out of the structured block.
9672 // longjmp() and throw() must not violate the entry/exit criteria.
9673 CS->getCapturedDecl()->setNothrow();
9674 }
Kelvin Lia579b912016-07-14 02:54:56 +00009675
9676 OMPLoopDirective::HelperExprs B;
9677 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9678 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009679 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00009680 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009681 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00009682 VarsWithImplicitDSA, B);
9683 if (NestedLoopCount == 0)
9684 return StmtError();
9685
9686 assert((CurContext->isDependentContext() || B.builtAll()) &&
9687 "omp target parallel for simd loop exprs were not built");
9688
9689 if (!CurContext->isDependentContext()) {
9690 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009691 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009692 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00009693 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9694 B.NumIterations, *this, CurScope,
9695 DSAStack))
9696 return StmtError();
9697 }
9698 }
Kelvin Lic5609492016-07-15 04:39:07 +00009699 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00009700 return StmtError();
9701
Reid Kleckner87a31802018-03-12 21:43:02 +00009702 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00009703 return OMPTargetParallelForSimdDirective::Create(
9704 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9705}
9706
Kelvin Li986330c2016-07-20 22:57:10 +00009707StmtResult Sema::ActOnOpenMPTargetSimdDirective(
9708 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009709 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00009710 if (!AStmt)
9711 return StmtError();
9712
Alexey Bataeve3727102018-04-18 15:57:46 +00009713 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00009714 // 1.2.2 OpenMP Language Terminology
9715 // Structured block - An executable statement with a single entry at the
9716 // top and a single exit at the bottom.
9717 // The point of exit cannot be a branch out of the structured block.
9718 // longjmp() and throw() must not violate the entry/exit criteria.
9719 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00009720 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
9721 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9722 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9723 // 1.2.2 OpenMP Language Terminology
9724 // Structured block - An executable statement with a single entry at the
9725 // top and a single exit at the bottom.
9726 // The point of exit cannot be a branch out of the structured block.
9727 // longjmp() and throw() must not violate the entry/exit criteria.
9728 CS->getCapturedDecl()->setNothrow();
9729 }
9730
Kelvin Li986330c2016-07-20 22:57:10 +00009731 OMPLoopDirective::HelperExprs B;
9732 // In presence of clause 'collapse' with number of loops, it will define the
9733 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00009734 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009735 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00009736 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00009737 VarsWithImplicitDSA, B);
9738 if (NestedLoopCount == 0)
9739 return StmtError();
9740
9741 assert((CurContext->isDependentContext() || B.builtAll()) &&
9742 "omp target simd loop exprs were not built");
9743
9744 if (!CurContext->isDependentContext()) {
9745 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009746 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009747 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00009748 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9749 B.NumIterations, *this, CurScope,
9750 DSAStack))
9751 return StmtError();
9752 }
9753 }
9754
9755 if (checkSimdlenSafelenSpecified(*this, Clauses))
9756 return StmtError();
9757
Reid Kleckner87a31802018-03-12 21:43:02 +00009758 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00009759 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
9760 NestedLoopCount, Clauses, AStmt, B);
9761}
9762
Kelvin Li02532872016-08-05 14:37:37 +00009763StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
9764 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009765 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00009766 if (!AStmt)
9767 return StmtError();
9768
Alexey Bataeve3727102018-04-18 15:57:46 +00009769 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00009770 // 1.2.2 OpenMP Language Terminology
9771 // Structured block - An executable statement with a single entry at the
9772 // top and a single exit at the bottom.
9773 // The point of exit cannot be a branch out of the structured block.
9774 // longjmp() and throw() must not violate the entry/exit criteria.
9775 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009776 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
9777 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9778 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9779 // 1.2.2 OpenMP Language Terminology
9780 // Structured block - An executable statement with a single entry at the
9781 // top and a single exit at the bottom.
9782 // The point of exit cannot be a branch out of the structured block.
9783 // longjmp() and throw() must not violate the entry/exit criteria.
9784 CS->getCapturedDecl()->setNothrow();
9785 }
Kelvin Li02532872016-08-05 14:37:37 +00009786
9787 OMPLoopDirective::HelperExprs B;
9788 // In presence of clause 'collapse' with number of loops, it will
9789 // define the nested loops number.
9790 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009791 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009792 nullptr /*ordered not a clause on distribute*/, CS, *this,
9793 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00009794 if (NestedLoopCount == 0)
9795 return StmtError();
9796
9797 assert((CurContext->isDependentContext() || B.builtAll()) &&
9798 "omp teams distribute loop exprs were not built");
9799
Reid Kleckner87a31802018-03-12 21:43:02 +00009800 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009801
9802 DSAStack->setParentTeamsRegionLoc(StartLoc);
9803
David Majnemer9d168222016-08-05 17:44:54 +00009804 return OMPTeamsDistributeDirective::Create(
9805 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00009806}
9807
Kelvin Li4e325f72016-10-25 12:50:55 +00009808StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
9809 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009810 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009811 if (!AStmt)
9812 return StmtError();
9813
Alexey Bataeve3727102018-04-18 15:57:46 +00009814 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00009815 // 1.2.2 OpenMP Language Terminology
9816 // Structured block - An executable statement with a single entry at the
9817 // top and a single exit at the bottom.
9818 // The point of exit cannot be a branch out of the structured block.
9819 // longjmp() and throw() must not violate the entry/exit criteria.
9820 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00009821 for (int ThisCaptureLevel =
9822 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
9823 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9824 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9825 // 1.2.2 OpenMP Language Terminology
9826 // Structured block - An executable statement with a single entry at the
9827 // top and a single exit at the bottom.
9828 // The point of exit cannot be a branch out of the structured block.
9829 // longjmp() and throw() must not violate the entry/exit criteria.
9830 CS->getCapturedDecl()->setNothrow();
9831 }
9832
Kelvin Li4e325f72016-10-25 12:50:55 +00009833
9834 OMPLoopDirective::HelperExprs B;
9835 // In presence of clause 'collapse' with number of loops, it will
9836 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009837 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00009838 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00009839 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00009840 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00009841
9842 if (NestedLoopCount == 0)
9843 return StmtError();
9844
9845 assert((CurContext->isDependentContext() || B.builtAll()) &&
9846 "omp teams distribute simd loop exprs were not built");
9847
9848 if (!CurContext->isDependentContext()) {
9849 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009850 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009851 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9852 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9853 B.NumIterations, *this, CurScope,
9854 DSAStack))
9855 return StmtError();
9856 }
9857 }
9858
9859 if (checkSimdlenSafelenSpecified(*this, Clauses))
9860 return StmtError();
9861
Reid Kleckner87a31802018-03-12 21:43:02 +00009862 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009863
9864 DSAStack->setParentTeamsRegionLoc(StartLoc);
9865
Kelvin Li4e325f72016-10-25 12:50:55 +00009866 return OMPTeamsDistributeSimdDirective::Create(
9867 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9868}
9869
Kelvin Li579e41c2016-11-30 23:51:03 +00009870StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9871 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009872 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009873 if (!AStmt)
9874 return StmtError();
9875
Alexey Bataeve3727102018-04-18 15:57:46 +00009876 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00009877 // 1.2.2 OpenMP Language Terminology
9878 // Structured block - An executable statement with a single entry at the
9879 // top and a single exit at the bottom.
9880 // The point of exit cannot be a branch out of the structured block.
9881 // longjmp() and throw() must not violate the entry/exit criteria.
9882 CS->getCapturedDecl()->setNothrow();
9883
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009884 for (int ThisCaptureLevel =
9885 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
9886 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9887 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9888 // 1.2.2 OpenMP Language Terminology
9889 // Structured block - An executable statement with a single entry at the
9890 // top and a single exit at the bottom.
9891 // The point of exit cannot be a branch out of the structured block.
9892 // longjmp() and throw() must not violate the entry/exit criteria.
9893 CS->getCapturedDecl()->setNothrow();
9894 }
9895
Kelvin Li579e41c2016-11-30 23:51:03 +00009896 OMPLoopDirective::HelperExprs B;
9897 // In presence of clause 'collapse' with number of loops, it will
9898 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009899 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00009900 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009901 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00009902 VarsWithImplicitDSA, B);
9903
9904 if (NestedLoopCount == 0)
9905 return StmtError();
9906
9907 assert((CurContext->isDependentContext() || B.builtAll()) &&
9908 "omp for loop exprs were not built");
9909
9910 if (!CurContext->isDependentContext()) {
9911 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009912 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009913 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9914 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9915 B.NumIterations, *this, CurScope,
9916 DSAStack))
9917 return StmtError();
9918 }
9919 }
9920
9921 if (checkSimdlenSafelenSpecified(*this, Clauses))
9922 return StmtError();
9923
Reid Kleckner87a31802018-03-12 21:43:02 +00009924 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009925
9926 DSAStack->setParentTeamsRegionLoc(StartLoc);
9927
Kelvin Li579e41c2016-11-30 23:51:03 +00009928 return OMPTeamsDistributeParallelForSimdDirective::Create(
9929 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9930}
9931
Kelvin Li7ade93f2016-12-09 03:24:30 +00009932StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
9933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009934 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00009935 if (!AStmt)
9936 return StmtError();
9937
Alexey Bataeve3727102018-04-18 15:57:46 +00009938 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00009939 // 1.2.2 OpenMP Language Terminology
9940 // Structured block - An executable statement with a single entry at the
9941 // top and a single exit at the bottom.
9942 // The point of exit cannot be a branch out of the structured block.
9943 // longjmp() and throw() must not violate the entry/exit criteria.
9944 CS->getCapturedDecl()->setNothrow();
9945
Carlo Bertolli62fae152017-11-20 20:46:39 +00009946 for (int ThisCaptureLevel =
9947 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
9948 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9949 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9950 // 1.2.2 OpenMP Language Terminology
9951 // Structured block - An executable statement with a single entry at the
9952 // top and a single exit at the bottom.
9953 // The point of exit cannot be a branch out of the structured block.
9954 // longjmp() and throw() must not violate the entry/exit criteria.
9955 CS->getCapturedDecl()->setNothrow();
9956 }
9957
Kelvin Li7ade93f2016-12-09 03:24:30 +00009958 OMPLoopDirective::HelperExprs B;
9959 // In presence of clause 'collapse' with number of loops, it will
9960 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009961 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00009962 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00009963 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00009964 VarsWithImplicitDSA, B);
9965
9966 if (NestedLoopCount == 0)
9967 return StmtError();
9968
9969 assert((CurContext->isDependentContext() || B.builtAll()) &&
9970 "omp for loop exprs were not built");
9971
Reid Kleckner87a31802018-03-12 21:43:02 +00009972 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009973
9974 DSAStack->setParentTeamsRegionLoc(StartLoc);
9975
Kelvin Li7ade93f2016-12-09 03:24:30 +00009976 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009977 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9978 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00009979}
9980
Kelvin Libf594a52016-12-17 05:48:59 +00009981StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9982 Stmt *AStmt,
9983 SourceLocation StartLoc,
9984 SourceLocation EndLoc) {
9985 if (!AStmt)
9986 return StmtError();
9987
Alexey Bataeve3727102018-04-18 15:57:46 +00009988 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00009989 // 1.2.2 OpenMP Language Terminology
9990 // Structured block - An executable statement with a single entry at the
9991 // top and a single exit at the bottom.
9992 // The point of exit cannot be a branch out of the structured block.
9993 // longjmp() and throw() must not violate the entry/exit criteria.
9994 CS->getCapturedDecl()->setNothrow();
9995
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00009996 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
9997 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9998 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9999 // 1.2.2 OpenMP Language Terminology
10000 // Structured block - An executable statement with a single entry at the
10001 // top and a single exit at the bottom.
10002 // The point of exit cannot be a branch out of the structured block.
10003 // longjmp() and throw() must not violate the entry/exit criteria.
10004 CS->getCapturedDecl()->setNothrow();
10005 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010006 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010007
10008 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10009 AStmt);
10010}
10011
Kelvin Li83c451e2016-12-25 04:52:54 +000010012StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010014 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010015 if (!AStmt)
10016 return StmtError();
10017
Alexey Bataeve3727102018-04-18 15:57:46 +000010018 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010019 // 1.2.2 OpenMP Language Terminology
10020 // Structured block - An executable statement with a single entry at the
10021 // top and a single exit at the bottom.
10022 // The point of exit cannot be a branch out of the structured block.
10023 // longjmp() and throw() must not violate the entry/exit criteria.
10024 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010025 for (int ThisCaptureLevel =
10026 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10027 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10028 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10029 // 1.2.2 OpenMP Language Terminology
10030 // Structured block - An executable statement with a single entry at the
10031 // top and a single exit at the bottom.
10032 // The point of exit cannot be a branch out of the structured block.
10033 // longjmp() and throw() must not violate the entry/exit criteria.
10034 CS->getCapturedDecl()->setNothrow();
10035 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010036
10037 OMPLoopDirective::HelperExprs B;
10038 // In presence of clause 'collapse' with number of loops, it will
10039 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010040 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010041 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10042 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010043 VarsWithImplicitDSA, B);
10044 if (NestedLoopCount == 0)
10045 return StmtError();
10046
10047 assert((CurContext->isDependentContext() || B.builtAll()) &&
10048 "omp target teams distribute loop exprs were not built");
10049
Reid Kleckner87a31802018-03-12 21:43:02 +000010050 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010051 return OMPTargetTeamsDistributeDirective::Create(
10052 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10053}
10054
Kelvin Li80e8f562016-12-29 22:16:30 +000010055StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10056 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010057 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010058 if (!AStmt)
10059 return StmtError();
10060
Alexey Bataeve3727102018-04-18 15:57:46 +000010061 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010062 // 1.2.2 OpenMP Language Terminology
10063 // Structured block - An executable statement with a single entry at the
10064 // top and a single exit at the bottom.
10065 // The point of exit cannot be a branch out of the structured block.
10066 // longjmp() and throw() must not violate the entry/exit criteria.
10067 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010068 for (int ThisCaptureLevel =
10069 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10070 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10071 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10072 // 1.2.2 OpenMP Language Terminology
10073 // Structured block - An executable statement with a single entry at the
10074 // top and a single exit at the bottom.
10075 // The point of exit cannot be a branch out of the structured block.
10076 // longjmp() and throw() must not violate the entry/exit criteria.
10077 CS->getCapturedDecl()->setNothrow();
10078 }
10079
Kelvin Li80e8f562016-12-29 22:16:30 +000010080 OMPLoopDirective::HelperExprs B;
10081 // In presence of clause 'collapse' with number of loops, it will
10082 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010083 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010084 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10085 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010086 VarsWithImplicitDSA, B);
10087 if (NestedLoopCount == 0)
10088 return StmtError();
10089
10090 assert((CurContext->isDependentContext() || B.builtAll()) &&
10091 "omp target teams distribute parallel for loop exprs were not built");
10092
Alexey Bataev647dd842018-01-15 20:59:40 +000010093 if (!CurContext->isDependentContext()) {
10094 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010095 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010096 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10097 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10098 B.NumIterations, *this, CurScope,
10099 DSAStack))
10100 return StmtError();
10101 }
10102 }
10103
Reid Kleckner87a31802018-03-12 21:43:02 +000010104 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010105 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010106 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10107 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010108}
10109
Kelvin Li1851df52017-01-03 05:23:48 +000010110StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10111 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010112 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010113 if (!AStmt)
10114 return StmtError();
10115
Alexey Bataeve3727102018-04-18 15:57:46 +000010116 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010117 // 1.2.2 OpenMP Language Terminology
10118 // Structured block - An executable statement with a single entry at the
10119 // top and a single exit at the bottom.
10120 // The point of exit cannot be a branch out of the structured block.
10121 // longjmp() and throw() must not violate the entry/exit criteria.
10122 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010123 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10124 OMPD_target_teams_distribute_parallel_for_simd);
10125 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10126 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10127 // 1.2.2 OpenMP Language Terminology
10128 // Structured block - An executable statement with a single entry at the
10129 // top and a single exit at the bottom.
10130 // The point of exit cannot be a branch out of the structured block.
10131 // longjmp() and throw() must not violate the entry/exit criteria.
10132 CS->getCapturedDecl()->setNothrow();
10133 }
Kelvin Li1851df52017-01-03 05:23:48 +000010134
10135 OMPLoopDirective::HelperExprs B;
10136 // In presence of clause 'collapse' with number of loops, it will
10137 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010138 unsigned NestedLoopCount =
10139 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010140 getCollapseNumberExpr(Clauses),
10141 nullptr /*ordered not a clause on distribute*/, CS, *this,
10142 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010143 if (NestedLoopCount == 0)
10144 return StmtError();
10145
10146 assert((CurContext->isDependentContext() || B.builtAll()) &&
10147 "omp target teams distribute parallel for simd loop exprs were not "
10148 "built");
10149
10150 if (!CurContext->isDependentContext()) {
10151 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010152 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010153 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10154 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10155 B.NumIterations, *this, CurScope,
10156 DSAStack))
10157 return StmtError();
10158 }
10159 }
10160
Alexey Bataev438388c2017-11-22 18:34:02 +000010161 if (checkSimdlenSafelenSpecified(*this, Clauses))
10162 return StmtError();
10163
Reid Kleckner87a31802018-03-12 21:43:02 +000010164 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010165 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10166 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10167}
10168
Kelvin Lida681182017-01-10 18:08:18 +000010169StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10170 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010171 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010172 if (!AStmt)
10173 return StmtError();
10174
10175 auto *CS = cast<CapturedStmt>(AStmt);
10176 // 1.2.2 OpenMP Language Terminology
10177 // Structured block - An executable statement with a single entry at the
10178 // top and a single exit at the bottom.
10179 // The point of exit cannot be a branch out of the structured block.
10180 // longjmp() and throw() must not violate the entry/exit criteria.
10181 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010182 for (int ThisCaptureLevel =
10183 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10184 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10185 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10186 // 1.2.2 OpenMP Language Terminology
10187 // Structured block - An executable statement with a single entry at the
10188 // top and a single exit at the bottom.
10189 // The point of exit cannot be a branch out of the structured block.
10190 // longjmp() and throw() must not violate the entry/exit criteria.
10191 CS->getCapturedDecl()->setNothrow();
10192 }
Kelvin Lida681182017-01-10 18:08:18 +000010193
10194 OMPLoopDirective::HelperExprs B;
10195 // In presence of clause 'collapse' with number of loops, it will
10196 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010197 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010198 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010199 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010200 VarsWithImplicitDSA, B);
10201 if (NestedLoopCount == 0)
10202 return StmtError();
10203
10204 assert((CurContext->isDependentContext() || B.builtAll()) &&
10205 "omp target teams distribute simd loop exprs were not built");
10206
Alexey Bataev438388c2017-11-22 18:34:02 +000010207 if (!CurContext->isDependentContext()) {
10208 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010209 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010210 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10211 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10212 B.NumIterations, *this, CurScope,
10213 DSAStack))
10214 return StmtError();
10215 }
10216 }
10217
10218 if (checkSimdlenSafelenSpecified(*this, Clauses))
10219 return StmtError();
10220
Reid Kleckner87a31802018-03-12 21:43:02 +000010221 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010222 return OMPTargetTeamsDistributeSimdDirective::Create(
10223 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10224}
10225
Alexey Bataeved09d242014-05-28 05:53:51 +000010226OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010227 SourceLocation StartLoc,
10228 SourceLocation LParenLoc,
10229 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010230 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010231 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010232 case OMPC_final:
10233 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10234 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010235 case OMPC_num_threads:
10236 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10237 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010238 case OMPC_safelen:
10239 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10240 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010241 case OMPC_simdlen:
10242 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10243 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010244 case OMPC_allocator:
10245 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10246 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010247 case OMPC_collapse:
10248 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10249 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010250 case OMPC_ordered:
10251 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10252 break;
Michael Wonge710d542015-08-07 16:16:36 +000010253 case OMPC_device:
10254 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10255 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010256 case OMPC_num_teams:
10257 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10258 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010259 case OMPC_thread_limit:
10260 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10261 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010262 case OMPC_priority:
10263 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10264 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010265 case OMPC_grainsize:
10266 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10267 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010268 case OMPC_num_tasks:
10269 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10270 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010271 case OMPC_hint:
10272 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10273 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010274 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010275 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010276 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010277 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010278 case OMPC_private:
10279 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010280 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010281 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010282 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010283 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010284 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010285 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010286 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010287 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010288 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010289 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010290 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010291 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010292 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010293 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010294 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010295 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010296 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010297 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010298 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010299 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010300 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010301 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010302 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010303 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010304 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010305 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010306 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010307 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010308 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010309 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010310 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010311 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010312 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010313 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010314 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010315 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010316 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010317 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010318 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010319 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010320 llvm_unreachable("Clause is not allowed.");
10321 }
10322 return Res;
10323}
10324
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010325// An OpenMP directive such as 'target parallel' has two captured regions:
10326// for the 'target' and 'parallel' respectively. This function returns
10327// the region in which to capture expressions associated with a clause.
10328// A return value of OMPD_unknown signifies that the expression should not
10329// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010330static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10331 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10332 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010333 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010334 switch (CKind) {
10335 case OMPC_if:
10336 switch (DKind) {
10337 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010338 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010339 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010340 // If this clause applies to the nested 'parallel' region, capture within
10341 // the 'target' region, otherwise do not capture.
10342 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10343 CaptureRegion = OMPD_target;
10344 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010345 case OMPD_target_teams_distribute_parallel_for:
10346 case OMPD_target_teams_distribute_parallel_for_simd:
10347 // If this clause applies to the nested 'parallel' region, capture within
10348 // the 'teams' region, otherwise do not capture.
10349 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10350 CaptureRegion = OMPD_teams;
10351 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010352 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010353 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010354 CaptureRegion = OMPD_teams;
10355 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010356 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010357 case OMPD_target_enter_data:
10358 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010359 CaptureRegion = OMPD_task;
10360 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010361 case OMPD_parallel_master_taskloop:
10362 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10363 CaptureRegion = OMPD_parallel;
10364 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010365 case OMPD_cancel:
10366 case OMPD_parallel:
10367 case OMPD_parallel_sections:
10368 case OMPD_parallel_for:
10369 case OMPD_parallel_for_simd:
10370 case OMPD_target:
10371 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010372 case OMPD_target_teams:
10373 case OMPD_target_teams_distribute:
10374 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010375 case OMPD_distribute_parallel_for:
10376 case OMPD_distribute_parallel_for_simd:
10377 case OMPD_task:
10378 case OMPD_taskloop:
10379 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010380 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010381 case OMPD_master_taskloop_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010382 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010383 // Do not capture if-clause expressions.
10384 break;
10385 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010386 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010387 case OMPD_taskyield:
10388 case OMPD_barrier:
10389 case OMPD_taskwait:
10390 case OMPD_cancellation_point:
10391 case OMPD_flush:
10392 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010393 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010394 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010395 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010396 case OMPD_declare_target:
10397 case OMPD_end_declare_target:
10398 case OMPD_teams:
10399 case OMPD_simd:
10400 case OMPD_for:
10401 case OMPD_for_simd:
10402 case OMPD_sections:
10403 case OMPD_section:
10404 case OMPD_single:
10405 case OMPD_master:
10406 case OMPD_critical:
10407 case OMPD_taskgroup:
10408 case OMPD_distribute:
10409 case OMPD_ordered:
10410 case OMPD_atomic:
10411 case OMPD_distribute_simd:
10412 case OMPD_teams_distribute:
10413 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010414 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010415 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10416 case OMPD_unknown:
10417 llvm_unreachable("Unknown OpenMP directive");
10418 }
10419 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010420 case OMPC_num_threads:
10421 switch (DKind) {
10422 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010423 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010424 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010425 CaptureRegion = OMPD_target;
10426 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010427 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010428 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010429 case OMPD_target_teams_distribute_parallel_for:
10430 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010431 CaptureRegion = OMPD_teams;
10432 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010433 case OMPD_parallel:
10434 case OMPD_parallel_sections:
10435 case OMPD_parallel_for:
10436 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010437 case OMPD_distribute_parallel_for:
10438 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010439 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010440 // Do not capture num_threads-clause expressions.
10441 break;
10442 case OMPD_target_data:
10443 case OMPD_target_enter_data:
10444 case OMPD_target_exit_data:
10445 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010446 case OMPD_target:
10447 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010448 case OMPD_target_teams:
10449 case OMPD_target_teams_distribute:
10450 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010451 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010452 case OMPD_task:
10453 case OMPD_taskloop:
10454 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010455 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010456 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010457 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010458 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010459 case OMPD_taskyield:
10460 case OMPD_barrier:
10461 case OMPD_taskwait:
10462 case OMPD_cancellation_point:
10463 case OMPD_flush:
10464 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010465 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010466 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010467 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010468 case OMPD_declare_target:
10469 case OMPD_end_declare_target:
10470 case OMPD_teams:
10471 case OMPD_simd:
10472 case OMPD_for:
10473 case OMPD_for_simd:
10474 case OMPD_sections:
10475 case OMPD_section:
10476 case OMPD_single:
10477 case OMPD_master:
10478 case OMPD_critical:
10479 case OMPD_taskgroup:
10480 case OMPD_distribute:
10481 case OMPD_ordered:
10482 case OMPD_atomic:
10483 case OMPD_distribute_simd:
10484 case OMPD_teams_distribute:
10485 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010486 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010487 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10488 case OMPD_unknown:
10489 llvm_unreachable("Unknown OpenMP directive");
10490 }
10491 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010492 case OMPC_num_teams:
10493 switch (DKind) {
10494 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010495 case OMPD_target_teams_distribute:
10496 case OMPD_target_teams_distribute_simd:
10497 case OMPD_target_teams_distribute_parallel_for:
10498 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010499 CaptureRegion = OMPD_target;
10500 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010501 case OMPD_teams_distribute_parallel_for:
10502 case OMPD_teams_distribute_parallel_for_simd:
10503 case OMPD_teams:
10504 case OMPD_teams_distribute:
10505 case OMPD_teams_distribute_simd:
10506 // Do not capture num_teams-clause expressions.
10507 break;
10508 case OMPD_distribute_parallel_for:
10509 case OMPD_distribute_parallel_for_simd:
10510 case OMPD_task:
10511 case OMPD_taskloop:
10512 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010513 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010514 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010515 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010516 case OMPD_target_data:
10517 case OMPD_target_enter_data:
10518 case OMPD_target_exit_data:
10519 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010520 case OMPD_cancel:
10521 case OMPD_parallel:
10522 case OMPD_parallel_sections:
10523 case OMPD_parallel_for:
10524 case OMPD_parallel_for_simd:
10525 case OMPD_target:
10526 case OMPD_target_simd:
10527 case OMPD_target_parallel:
10528 case OMPD_target_parallel_for:
10529 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010530 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010531 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010532 case OMPD_taskyield:
10533 case OMPD_barrier:
10534 case OMPD_taskwait:
10535 case OMPD_cancellation_point:
10536 case OMPD_flush:
10537 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010538 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010539 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010540 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010541 case OMPD_declare_target:
10542 case OMPD_end_declare_target:
10543 case OMPD_simd:
10544 case OMPD_for:
10545 case OMPD_for_simd:
10546 case OMPD_sections:
10547 case OMPD_section:
10548 case OMPD_single:
10549 case OMPD_master:
10550 case OMPD_critical:
10551 case OMPD_taskgroup:
10552 case OMPD_distribute:
10553 case OMPD_ordered:
10554 case OMPD_atomic:
10555 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010556 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010557 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10558 case OMPD_unknown:
10559 llvm_unreachable("Unknown OpenMP directive");
10560 }
10561 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010562 case OMPC_thread_limit:
10563 switch (DKind) {
10564 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010565 case OMPD_target_teams_distribute:
10566 case OMPD_target_teams_distribute_simd:
10567 case OMPD_target_teams_distribute_parallel_for:
10568 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010569 CaptureRegion = OMPD_target;
10570 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010571 case OMPD_teams_distribute_parallel_for:
10572 case OMPD_teams_distribute_parallel_for_simd:
10573 case OMPD_teams:
10574 case OMPD_teams_distribute:
10575 case OMPD_teams_distribute_simd:
10576 // Do not capture thread_limit-clause expressions.
10577 break;
10578 case OMPD_distribute_parallel_for:
10579 case OMPD_distribute_parallel_for_simd:
10580 case OMPD_task:
10581 case OMPD_taskloop:
10582 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010583 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010584 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010585 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010586 case OMPD_target_data:
10587 case OMPD_target_enter_data:
10588 case OMPD_target_exit_data:
10589 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010590 case OMPD_cancel:
10591 case OMPD_parallel:
10592 case OMPD_parallel_sections:
10593 case OMPD_parallel_for:
10594 case OMPD_parallel_for_simd:
10595 case OMPD_target:
10596 case OMPD_target_simd:
10597 case OMPD_target_parallel:
10598 case OMPD_target_parallel_for:
10599 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010600 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010601 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010602 case OMPD_taskyield:
10603 case OMPD_barrier:
10604 case OMPD_taskwait:
10605 case OMPD_cancellation_point:
10606 case OMPD_flush:
10607 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010608 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010609 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010610 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010611 case OMPD_declare_target:
10612 case OMPD_end_declare_target:
10613 case OMPD_simd:
10614 case OMPD_for:
10615 case OMPD_for_simd:
10616 case OMPD_sections:
10617 case OMPD_section:
10618 case OMPD_single:
10619 case OMPD_master:
10620 case OMPD_critical:
10621 case OMPD_taskgroup:
10622 case OMPD_distribute:
10623 case OMPD_ordered:
10624 case OMPD_atomic:
10625 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010626 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010627 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10628 case OMPD_unknown:
10629 llvm_unreachable("Unknown OpenMP directive");
10630 }
10631 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010632 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010633 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010634 case OMPD_parallel_for:
10635 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010636 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010637 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010638 case OMPD_teams_distribute_parallel_for:
10639 case OMPD_teams_distribute_parallel_for_simd:
10640 case OMPD_target_parallel_for:
10641 case OMPD_target_parallel_for_simd:
10642 case OMPD_target_teams_distribute_parallel_for:
10643 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010644 CaptureRegion = OMPD_parallel;
10645 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010646 case OMPD_for:
10647 case OMPD_for_simd:
10648 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010649 break;
10650 case OMPD_task:
10651 case OMPD_taskloop:
10652 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010653 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010654 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010655 case OMPD_parallel_master_taskloop:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010656 case OMPD_target_data:
10657 case OMPD_target_enter_data:
10658 case OMPD_target_exit_data:
10659 case OMPD_target_update:
10660 case OMPD_teams:
10661 case OMPD_teams_distribute:
10662 case OMPD_teams_distribute_simd:
10663 case OMPD_target_teams_distribute:
10664 case OMPD_target_teams_distribute_simd:
10665 case OMPD_target:
10666 case OMPD_target_simd:
10667 case OMPD_target_parallel:
10668 case OMPD_cancel:
10669 case OMPD_parallel:
10670 case OMPD_parallel_sections:
10671 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010672 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010673 case OMPD_taskyield:
10674 case OMPD_barrier:
10675 case OMPD_taskwait:
10676 case OMPD_cancellation_point:
10677 case OMPD_flush:
10678 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010679 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010680 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010681 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010682 case OMPD_declare_target:
10683 case OMPD_end_declare_target:
10684 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010685 case OMPD_sections:
10686 case OMPD_section:
10687 case OMPD_single:
10688 case OMPD_master:
10689 case OMPD_critical:
10690 case OMPD_taskgroup:
10691 case OMPD_distribute:
10692 case OMPD_ordered:
10693 case OMPD_atomic:
10694 case OMPD_distribute_simd:
10695 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010696 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010697 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10698 case OMPD_unknown:
10699 llvm_unreachable("Unknown OpenMP directive");
10700 }
10701 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010702 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010703 switch (DKind) {
10704 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010705 case OMPD_teams_distribute_parallel_for_simd:
10706 case OMPD_teams_distribute:
10707 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010708 case OMPD_target_teams_distribute_parallel_for:
10709 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010710 case OMPD_target_teams_distribute:
10711 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010712 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010713 break;
10714 case OMPD_distribute_parallel_for:
10715 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010716 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010717 case OMPD_distribute_simd:
10718 // Do not capture thread_limit-clause expressions.
10719 break;
10720 case OMPD_parallel_for:
10721 case OMPD_parallel_for_simd:
10722 case OMPD_target_parallel_for_simd:
10723 case OMPD_target_parallel_for:
10724 case OMPD_task:
10725 case OMPD_taskloop:
10726 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010727 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010728 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010729 case OMPD_parallel_master_taskloop:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010730 case OMPD_target_data:
10731 case OMPD_target_enter_data:
10732 case OMPD_target_exit_data:
10733 case OMPD_target_update:
10734 case OMPD_teams:
10735 case OMPD_target:
10736 case OMPD_target_simd:
10737 case OMPD_target_parallel:
10738 case OMPD_cancel:
10739 case OMPD_parallel:
10740 case OMPD_parallel_sections:
10741 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010742 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010743 case OMPD_taskyield:
10744 case OMPD_barrier:
10745 case OMPD_taskwait:
10746 case OMPD_cancellation_point:
10747 case OMPD_flush:
10748 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010749 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010750 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010751 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010752 case OMPD_declare_target:
10753 case OMPD_end_declare_target:
10754 case OMPD_simd:
10755 case OMPD_for:
10756 case OMPD_for_simd:
10757 case OMPD_sections:
10758 case OMPD_section:
10759 case OMPD_single:
10760 case OMPD_master:
10761 case OMPD_critical:
10762 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010763 case OMPD_ordered:
10764 case OMPD_atomic:
10765 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010766 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010767 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10768 case OMPD_unknown:
10769 llvm_unreachable("Unknown OpenMP directive");
10770 }
10771 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010772 case OMPC_device:
10773 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010774 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010775 case OMPD_target_enter_data:
10776 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000010777 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000010778 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000010779 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000010780 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000010781 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000010782 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000010783 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000010784 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000010785 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000010786 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010787 CaptureRegion = OMPD_task;
10788 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010789 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010790 // Do not capture device-clause expressions.
10791 break;
10792 case OMPD_teams_distribute_parallel_for:
10793 case OMPD_teams_distribute_parallel_for_simd:
10794 case OMPD_teams:
10795 case OMPD_teams_distribute:
10796 case OMPD_teams_distribute_simd:
10797 case OMPD_distribute_parallel_for:
10798 case OMPD_distribute_parallel_for_simd:
10799 case OMPD_task:
10800 case OMPD_taskloop:
10801 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010802 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010803 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010804 case OMPD_parallel_master_taskloop:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010805 case OMPD_cancel:
10806 case OMPD_parallel:
10807 case OMPD_parallel_sections:
10808 case OMPD_parallel_for:
10809 case OMPD_parallel_for_simd:
10810 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010811 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010812 case OMPD_taskyield:
10813 case OMPD_barrier:
10814 case OMPD_taskwait:
10815 case OMPD_cancellation_point:
10816 case OMPD_flush:
10817 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010818 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010819 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010820 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010821 case OMPD_declare_target:
10822 case OMPD_end_declare_target:
10823 case OMPD_simd:
10824 case OMPD_for:
10825 case OMPD_for_simd:
10826 case OMPD_sections:
10827 case OMPD_section:
10828 case OMPD_single:
10829 case OMPD_master:
10830 case OMPD_critical:
10831 case OMPD_taskgroup:
10832 case OMPD_distribute:
10833 case OMPD_ordered:
10834 case OMPD_atomic:
10835 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010836 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010837 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10838 case OMPD_unknown:
10839 llvm_unreachable("Unknown OpenMP directive");
10840 }
10841 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010842 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000010843 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000010844 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000010845 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010846 switch (DKind) {
10847 case OMPD_task:
10848 case OMPD_taskloop:
10849 case OMPD_taskloop_simd:
10850 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000010851 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000010852 break;
10853 case OMPD_parallel_master_taskloop:
10854 CaptureRegion = OMPD_parallel;
10855 break;
10856 case OMPD_target_update:
10857 case OMPD_target_enter_data:
10858 case OMPD_target_exit_data:
10859 case OMPD_target:
10860 case OMPD_target_simd:
10861 case OMPD_target_teams:
10862 case OMPD_target_parallel:
10863 case OMPD_target_teams_distribute:
10864 case OMPD_target_teams_distribute_simd:
10865 case OMPD_target_parallel_for:
10866 case OMPD_target_parallel_for_simd:
10867 case OMPD_target_teams_distribute_parallel_for:
10868 case OMPD_target_teams_distribute_parallel_for_simd:
10869 case OMPD_target_data:
10870 case OMPD_teams_distribute_parallel_for:
10871 case OMPD_teams_distribute_parallel_for_simd:
10872 case OMPD_teams:
10873 case OMPD_teams_distribute:
10874 case OMPD_teams_distribute_simd:
10875 case OMPD_distribute_parallel_for:
10876 case OMPD_distribute_parallel_for_simd:
10877 case OMPD_cancel:
10878 case OMPD_parallel:
10879 case OMPD_parallel_sections:
10880 case OMPD_parallel_for:
10881 case OMPD_parallel_for_simd:
10882 case OMPD_threadprivate:
10883 case OMPD_allocate:
10884 case OMPD_taskyield:
10885 case OMPD_barrier:
10886 case OMPD_taskwait:
10887 case OMPD_cancellation_point:
10888 case OMPD_flush:
10889 case OMPD_declare_reduction:
10890 case OMPD_declare_mapper:
10891 case OMPD_declare_simd:
10892 case OMPD_declare_variant:
10893 case OMPD_declare_target:
10894 case OMPD_end_declare_target:
10895 case OMPD_simd:
10896 case OMPD_for:
10897 case OMPD_for_simd:
10898 case OMPD_sections:
10899 case OMPD_section:
10900 case OMPD_single:
10901 case OMPD_master:
10902 case OMPD_critical:
10903 case OMPD_taskgroup:
10904 case OMPD_distribute:
10905 case OMPD_ordered:
10906 case OMPD_atomic:
10907 case OMPD_distribute_simd:
10908 case OMPD_requires:
10909 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
10910 case OMPD_unknown:
10911 llvm_unreachable("Unknown OpenMP directive");
10912 }
10913 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010914 case OMPC_firstprivate:
10915 case OMPC_lastprivate:
10916 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010917 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010918 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010919 case OMPC_linear:
10920 case OMPC_default:
10921 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010922 case OMPC_safelen:
10923 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010924 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010925 case OMPC_collapse:
10926 case OMPC_private:
10927 case OMPC_shared:
10928 case OMPC_aligned:
10929 case OMPC_copyin:
10930 case OMPC_copyprivate:
10931 case OMPC_ordered:
10932 case OMPC_nowait:
10933 case OMPC_untied:
10934 case OMPC_mergeable:
10935 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010936 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010937 case OMPC_flush:
10938 case OMPC_read:
10939 case OMPC_write:
10940 case OMPC_update:
10941 case OMPC_capture:
10942 case OMPC_seq_cst:
10943 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010944 case OMPC_threads:
10945 case OMPC_simd:
10946 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010947 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010948 case OMPC_hint:
10949 case OMPC_defaultmap:
10950 case OMPC_unknown:
10951 case OMPC_uniform:
10952 case OMPC_to:
10953 case OMPC_from:
10954 case OMPC_use_device_ptr:
10955 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010956 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010957 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010958 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010959 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010960 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010961 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010962 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010963 llvm_unreachable("Unexpected OpenMP clause.");
10964 }
10965 return CaptureRegion;
10966}
10967
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010968OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10969 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010970 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010971 SourceLocation NameModifierLoc,
10972 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010973 SourceLocation EndLoc) {
10974 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010975 Stmt *HelperValStmt = nullptr;
10976 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010977 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10978 !Condition->isInstantiationDependent() &&
10979 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010980 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010981 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010982 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010983
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010984 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010985
10986 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10987 CaptureRegion =
10988 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000010989 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010990 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010991 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010992 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10993 HelperValStmt = buildPreInits(Context, Captures);
10994 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010995 }
10996
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010997 return new (Context)
10998 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
10999 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011000}
11001
Alexey Bataev3778b602014-07-17 07:32:53 +000011002OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11003 SourceLocation StartLoc,
11004 SourceLocation LParenLoc,
11005 SourceLocation EndLoc) {
11006 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011007 Stmt *HelperValStmt = nullptr;
11008 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011009 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11010 !Condition->isInstantiationDependent() &&
11011 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011012 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011013 if (Val.isInvalid())
11014 return nullptr;
11015
Richard Smith03a4aa32016-06-23 19:02:52 +000011016 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011017
11018 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
11019 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_final);
11020 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11021 ValExpr = MakeFullExpr(ValExpr).get();
11022 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11023 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11024 HelperValStmt = buildPreInits(Context, Captures);
11025 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011026 }
11027
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011028 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11029 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011030}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011031
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011032ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11033 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011034 if (!Op)
11035 return ExprError();
11036
11037 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11038 public:
11039 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011040 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011041 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11042 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011043 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11044 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011045 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11046 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011047 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11048 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011049 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11050 QualType T,
11051 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011052 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11053 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011054 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11055 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011056 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011057 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011058 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011059 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11060 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011061 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11062 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011063 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11064 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011065 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011066 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011067 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011068 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11069 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011070 llvm_unreachable("conversion functions are permitted");
11071 }
11072 } ConvertDiagnoser;
11073 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11074}
11075
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011076static bool
11077isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11078 bool StrictlyPositive, bool BuildCapture = false,
11079 OpenMPDirectiveKind DKind = OMPD_unknown,
11080 OpenMPDirectiveKind *CaptureRegion = nullptr,
11081 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011082 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11083 !ValExpr->isInstantiationDependent()) {
11084 SourceLocation Loc = ValExpr->getExprLoc();
11085 ExprResult Value =
11086 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11087 if (Value.isInvalid())
11088 return false;
11089
11090 ValExpr = Value.get();
11091 // The expression must evaluate to a non-negative integer value.
11092 llvm::APSInt Result;
11093 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011094 Result.isSigned() &&
11095 !((!StrictlyPositive && Result.isNonNegative()) ||
11096 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011097 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011098 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11099 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011100 return false;
11101 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011102 if (!BuildCapture)
11103 return true;
11104 *CaptureRegion = getOpenMPCaptureRegionForClause(DKind, CKind);
11105 if (*CaptureRegion != OMPD_unknown &&
11106 !SemaRef.CurContext->isDependentContext()) {
11107 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11108 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11109 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11110 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11111 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011112 }
11113 return true;
11114}
11115
Alexey Bataev568a8332014-03-06 06:15:19 +000011116OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11117 SourceLocation StartLoc,
11118 SourceLocation LParenLoc,
11119 SourceLocation EndLoc) {
11120 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011121 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011122
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011123 // OpenMP [2.5, Restrictions]
11124 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011125 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011126 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011127 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011128
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011129 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011130 OpenMPDirectiveKind CaptureRegion =
11131 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
11132 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011133 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011134 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011135 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11136 HelperValStmt = buildPreInits(Context, Captures);
11137 }
11138
11139 return new (Context) OMPNumThreadsClause(
11140 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011141}
11142
Alexey Bataev62c87d22014-03-21 04:51:18 +000011143ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011144 OpenMPClauseKind CKind,
11145 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011146 if (!E)
11147 return ExprError();
11148 if (E->isValueDependent() || E->isTypeDependent() ||
11149 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011150 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011151 llvm::APSInt Result;
11152 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11153 if (ICE.isInvalid())
11154 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011155 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11156 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011157 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011158 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11159 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011160 return ExprError();
11161 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011162 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11163 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11164 << E->getSourceRange();
11165 return ExprError();
11166 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011167 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11168 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011169 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011170 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011171 return ICE;
11172}
11173
11174OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11175 SourceLocation LParenLoc,
11176 SourceLocation EndLoc) {
11177 // OpenMP [2.8.1, simd construct, Description]
11178 // The parameter of the safelen clause must be a constant
11179 // positive integer expression.
11180 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11181 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011182 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011183 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011184 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011185}
11186
Alexey Bataev66b15b52015-08-21 11:14:16 +000011187OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11188 SourceLocation LParenLoc,
11189 SourceLocation EndLoc) {
11190 // OpenMP [2.8.1, simd construct, Description]
11191 // The parameter of the simdlen clause must be a constant
11192 // positive integer expression.
11193 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11194 if (Simdlen.isInvalid())
11195 return nullptr;
11196 return new (Context)
11197 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11198}
11199
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011200/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011201static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11202 DSAStackTy *Stack) {
11203 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011204 if (!OMPAllocatorHandleT.isNull())
11205 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011206 // Build the predefined allocator expressions.
11207 bool ErrorFound = false;
11208 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11209 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11210 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11211 StringRef Allocator =
11212 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11213 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11214 auto *VD = dyn_cast_or_null<ValueDecl>(
11215 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11216 if (!VD) {
11217 ErrorFound = true;
11218 break;
11219 }
11220 QualType AllocatorType =
11221 VD->getType().getNonLValueExprType(S.getASTContext());
11222 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11223 if (!Res.isUsable()) {
11224 ErrorFound = true;
11225 break;
11226 }
11227 if (OMPAllocatorHandleT.isNull())
11228 OMPAllocatorHandleT = AllocatorType;
11229 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11230 ErrorFound = true;
11231 break;
11232 }
11233 Stack->setAllocator(AllocatorKind, Res.get());
11234 }
11235 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011236 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11237 return false;
11238 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011239 OMPAllocatorHandleT.addConst();
11240 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011241 return true;
11242}
11243
11244OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11245 SourceLocation LParenLoc,
11246 SourceLocation EndLoc) {
11247 // OpenMP [2.11.3, allocate Directive, Description]
11248 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011249 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011250 return nullptr;
11251
11252 ExprResult Allocator = DefaultLvalueConversion(A);
11253 if (Allocator.isInvalid())
11254 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011255 Allocator = PerformImplicitConversion(Allocator.get(),
11256 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011257 Sema::AA_Initializing,
11258 /*AllowExplicit=*/true);
11259 if (Allocator.isInvalid())
11260 return nullptr;
11261 return new (Context)
11262 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11263}
11264
Alexander Musman64d33f12014-06-04 07:53:32 +000011265OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11266 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011267 SourceLocation LParenLoc,
11268 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011269 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011270 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011271 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011272 // The parameter of the collapse clause must be a constant
11273 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011274 ExprResult NumForLoopsResult =
11275 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11276 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011277 return nullptr;
11278 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011279 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011280}
11281
Alexey Bataev10e775f2015-07-30 11:36:16 +000011282OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11283 SourceLocation EndLoc,
11284 SourceLocation LParenLoc,
11285 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011286 // OpenMP [2.7.1, loop construct, Description]
11287 // OpenMP [2.8.1, simd construct, Description]
11288 // OpenMP [2.9.6, distribute construct, Description]
11289 // The parameter of the ordered clause must be a constant
11290 // positive integer expression if any.
11291 if (NumForLoops && LParenLoc.isValid()) {
11292 ExprResult NumForLoopsResult =
11293 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11294 if (NumForLoopsResult.isInvalid())
11295 return nullptr;
11296 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011297 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011298 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011299 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011300 auto *Clause = OMPOrderedClause::Create(
11301 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11302 StartLoc, LParenLoc, EndLoc);
11303 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11304 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011305}
11306
Alexey Bataeved09d242014-05-28 05:53:51 +000011307OMPClause *Sema::ActOnOpenMPSimpleClause(
11308 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11309 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011310 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011311 switch (Kind) {
11312 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011313 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011314 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11315 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011316 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011317 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000011318 Res = ActOnOpenMPProcBindClause(
11319 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
11320 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011321 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011322 case OMPC_atomic_default_mem_order:
11323 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11324 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11325 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11326 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011327 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011328 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011329 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011330 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011331 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011332 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011333 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011334 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011335 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011336 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011337 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011338 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011339 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011340 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011341 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011342 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011343 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011344 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011345 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011346 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011347 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011348 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011349 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011350 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011351 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011352 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011353 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011354 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011355 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011356 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011357 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011358 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011359 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011360 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011361 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011362 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011363 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011364 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011365 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011366 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011367 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011368 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011369 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011370 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011371 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011372 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011373 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011374 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011375 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011376 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011377 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011378 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011379 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011380 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011381 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011382 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011383 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011384 llvm_unreachable("Clause is not allowed.");
11385 }
11386 return Res;
11387}
11388
Alexey Bataev6402bca2015-12-28 07:25:51 +000011389static std::string
11390getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11391 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011392 SmallString<256> Buffer;
11393 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011394 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11395 unsigned Skipped = Exclude.size();
11396 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011397 for (unsigned I = First; I < Last; ++I) {
11398 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011399 --Skipped;
11400 continue;
11401 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011402 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11403 if (I == Bound - Skipped)
11404 Out << " or ";
11405 else if (I != Bound + 1 - Skipped)
11406 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011407 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011408 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011409}
11410
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011411OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11412 SourceLocation KindKwLoc,
11413 SourceLocation StartLoc,
11414 SourceLocation LParenLoc,
11415 SourceLocation EndLoc) {
11416 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011417 static_assert(OMPC_DEFAULT_unknown > 0,
11418 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011419 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011420 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11421 /*Last=*/OMPC_DEFAULT_unknown)
11422 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011423 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011424 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011425 switch (Kind) {
11426 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011427 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011428 break;
11429 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011430 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011431 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011432 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011433 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011434 break;
11435 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011436 return new (Context)
11437 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011438}
11439
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011440OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11441 SourceLocation KindKwLoc,
11442 SourceLocation StartLoc,
11443 SourceLocation LParenLoc,
11444 SourceLocation EndLoc) {
11445 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011446 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011447 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11448 /*Last=*/OMPC_PROC_BIND_unknown)
11449 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011450 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011451 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011452 return new (Context)
11453 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011454}
11455
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011456OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11457 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11458 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11459 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11460 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11461 << getListOfPossibleValues(
11462 OMPC_atomic_default_mem_order, /*First=*/0,
11463 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11464 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11465 return nullptr;
11466 }
11467 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11468 LParenLoc, EndLoc);
11469}
11470
Alexey Bataev56dafe82014-06-20 07:16:17 +000011471OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011472 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011473 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011474 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011475 SourceLocation EndLoc) {
11476 OMPClause *Res = nullptr;
11477 switch (Kind) {
11478 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011479 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11480 assert(Argument.size() == NumberOfElements &&
11481 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011482 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011483 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11484 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11485 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11486 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11487 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011488 break;
11489 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011490 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11491 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11492 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11493 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011494 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011495 case OMPC_dist_schedule:
11496 Res = ActOnOpenMPDistScheduleClause(
11497 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11498 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11499 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011500 case OMPC_defaultmap:
11501 enum { Modifier, DefaultmapKind };
11502 Res = ActOnOpenMPDefaultmapClause(
11503 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11504 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011505 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11506 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011507 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011508 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011509 case OMPC_num_threads:
11510 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011511 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011512 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011513 case OMPC_collapse:
11514 case OMPC_default:
11515 case OMPC_proc_bind:
11516 case OMPC_private:
11517 case OMPC_firstprivate:
11518 case OMPC_lastprivate:
11519 case OMPC_shared:
11520 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011521 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011522 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011523 case OMPC_linear:
11524 case OMPC_aligned:
11525 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011526 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011527 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011528 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011529 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011530 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011531 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011532 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011533 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011534 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011535 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011536 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011537 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011538 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011539 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011540 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011541 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011542 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011543 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011544 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011545 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011546 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011547 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011548 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011549 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011550 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011551 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011552 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011553 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011554 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011555 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011556 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011557 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011558 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011559 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011560 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011561 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011562 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011563 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011564 llvm_unreachable("Clause is not allowed.");
11565 }
11566 return Res;
11567}
11568
Alexey Bataev6402bca2015-12-28 07:25:51 +000011569static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11570 OpenMPScheduleClauseModifier M2,
11571 SourceLocation M1Loc, SourceLocation M2Loc) {
11572 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11573 SmallVector<unsigned, 2> Excluded;
11574 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11575 Excluded.push_back(M2);
11576 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11577 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11578 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11579 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11580 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11581 << getListOfPossibleValues(OMPC_schedule,
11582 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11583 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11584 Excluded)
11585 << getOpenMPClauseName(OMPC_schedule);
11586 return true;
11587 }
11588 return false;
11589}
11590
Alexey Bataev56dafe82014-06-20 07:16:17 +000011591OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011592 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011593 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011594 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11595 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11596 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11597 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11598 return nullptr;
11599 // OpenMP, 2.7.1, Loop Construct, Restrictions
11600 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11601 // but not both.
11602 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11603 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11604 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11605 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11606 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11607 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11608 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11609 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11610 return nullptr;
11611 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011612 if (Kind == OMPC_SCHEDULE_unknown) {
11613 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011614 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11615 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11616 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11617 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11618 Exclude);
11619 } else {
11620 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11621 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011622 }
11623 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11624 << Values << getOpenMPClauseName(OMPC_schedule);
11625 return nullptr;
11626 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011627 // OpenMP, 2.7.1, Loop Construct, Restrictions
11628 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11629 // schedule(guided).
11630 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11631 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11632 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11633 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11634 diag::err_omp_schedule_nonmonotonic_static);
11635 return nullptr;
11636 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011637 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011638 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011639 if (ChunkSize) {
11640 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11641 !ChunkSize->isInstantiationDependent() &&
11642 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011643 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011644 ExprResult Val =
11645 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11646 if (Val.isInvalid())
11647 return nullptr;
11648
11649 ValExpr = Val.get();
11650
11651 // OpenMP [2.7.1, Restrictions]
11652 // chunk_size must be a loop invariant integer expression with a positive
11653 // value.
11654 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000011655 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11656 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11657 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011658 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000011659 return nullptr;
11660 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000011661 } else if (getOpenMPCaptureRegionForClause(
11662 DSAStack->getCurrentDirective(), OMPC_schedule) !=
11663 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011664 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011665 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011666 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000011667 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11668 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011669 }
11670 }
11671 }
11672
Alexey Bataev6402bca2015-12-28 07:25:51 +000011673 return new (Context)
11674 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000011675 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011676}
11677
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011678OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
11679 SourceLocation StartLoc,
11680 SourceLocation EndLoc) {
11681 OMPClause *Res = nullptr;
11682 switch (Kind) {
11683 case OMPC_ordered:
11684 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
11685 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000011686 case OMPC_nowait:
11687 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
11688 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011689 case OMPC_untied:
11690 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
11691 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011692 case OMPC_mergeable:
11693 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
11694 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011695 case OMPC_read:
11696 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
11697 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000011698 case OMPC_write:
11699 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
11700 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000011701 case OMPC_update:
11702 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
11703 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000011704 case OMPC_capture:
11705 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
11706 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011707 case OMPC_seq_cst:
11708 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
11709 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000011710 case OMPC_threads:
11711 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
11712 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011713 case OMPC_simd:
11714 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
11715 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000011716 case OMPC_nogroup:
11717 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
11718 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011719 case OMPC_unified_address:
11720 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
11721 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011722 case OMPC_unified_shared_memory:
11723 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11724 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011725 case OMPC_reverse_offload:
11726 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
11727 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011728 case OMPC_dynamic_allocators:
11729 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
11730 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011731 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011732 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011733 case OMPC_num_threads:
11734 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011735 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011736 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011737 case OMPC_collapse:
11738 case OMPC_schedule:
11739 case OMPC_private:
11740 case OMPC_firstprivate:
11741 case OMPC_lastprivate:
11742 case OMPC_shared:
11743 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011744 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011745 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011746 case OMPC_linear:
11747 case OMPC_aligned:
11748 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011749 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011750 case OMPC_default:
11751 case OMPC_proc_bind:
11752 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011753 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011754 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011755 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011756 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011757 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011758 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011759 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011760 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011761 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000011762 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011763 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011764 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011765 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011766 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011767 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011768 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011769 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011770 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011771 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011772 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011773 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011774 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011775 llvm_unreachable("Clause is not allowed.");
11776 }
11777 return Res;
11778}
11779
Alexey Bataev236070f2014-06-20 11:19:47 +000011780OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11781 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000011782 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000011783 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
11784}
11785
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011786OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11787 SourceLocation EndLoc) {
11788 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
11789}
11790
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011791OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11792 SourceLocation EndLoc) {
11793 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
11794}
11795
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011796OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
11797 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011798 return new (Context) OMPReadClause(StartLoc, EndLoc);
11799}
11800
Alexey Bataevdea47612014-07-23 07:46:59 +000011801OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
11802 SourceLocation EndLoc) {
11803 return new (Context) OMPWriteClause(StartLoc, EndLoc);
11804}
11805
Alexey Bataev67a4f222014-07-23 10:25:33 +000011806OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11807 SourceLocation EndLoc) {
11808 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
11809}
11810
Alexey Bataev459dec02014-07-24 06:46:57 +000011811OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11812 SourceLocation EndLoc) {
11813 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
11814}
11815
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011816OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11817 SourceLocation EndLoc) {
11818 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
11819}
11820
Alexey Bataev346265e2015-09-25 10:37:12 +000011821OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11822 SourceLocation EndLoc) {
11823 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
11824}
11825
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011826OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11827 SourceLocation EndLoc) {
11828 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
11829}
11830
Alexey Bataevb825de12015-12-07 10:51:44 +000011831OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11832 SourceLocation EndLoc) {
11833 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
11834}
11835
Kelvin Li1408f912018-09-26 04:28:39 +000011836OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11837 SourceLocation EndLoc) {
11838 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
11839}
11840
Patrick Lyster4a370b92018-10-01 13:47:43 +000011841OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11842 SourceLocation EndLoc) {
11843 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11844}
11845
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011846OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11847 SourceLocation EndLoc) {
11848 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
11849}
11850
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011851OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11852 SourceLocation EndLoc) {
11853 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
11854}
11855
Alexey Bataevc5e02582014-06-16 07:08:35 +000011856OMPClause *Sema::ActOnOpenMPVarListClause(
11857 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011858 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11859 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11860 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000011861 OpenMPLinearClauseKind LinKind,
11862 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011863 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
11864 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
11865 SourceLocation StartLoc = Locs.StartLoc;
11866 SourceLocation LParenLoc = Locs.LParenLoc;
11867 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011868 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011869 switch (Kind) {
11870 case OMPC_private:
11871 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11872 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011873 case OMPC_firstprivate:
11874 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11875 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011876 case OMPC_lastprivate:
11877 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11878 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011879 case OMPC_shared:
11880 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
11881 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011882 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000011883 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011884 EndLoc, ReductionOrMapperIdScopeSpec,
11885 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011886 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000011887 case OMPC_task_reduction:
11888 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011889 EndLoc, ReductionOrMapperIdScopeSpec,
11890 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000011891 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000011892 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011893 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11894 EndLoc, ReductionOrMapperIdScopeSpec,
11895 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000011896 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000011897 case OMPC_linear:
11898 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011899 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000011900 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011901 case OMPC_aligned:
11902 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
11903 ColonLoc, EndLoc);
11904 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011905 case OMPC_copyin:
11906 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
11907 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011908 case OMPC_copyprivate:
11909 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11910 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000011911 case OMPC_flush:
11912 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
11913 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011914 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000011915 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011916 StartLoc, LParenLoc, EndLoc);
11917 break;
11918 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011919 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
11920 ReductionOrMapperIdScopeSpec,
11921 ReductionOrMapperId, MapType, IsMapTypeImplicit,
11922 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011923 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011924 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000011925 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
11926 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000011927 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000011928 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000011929 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
11930 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000011931 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000011932 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011933 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011934 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000011935 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011936 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011937 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000011938 case OMPC_allocate:
11939 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
11940 ColonLoc, EndLoc);
11941 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011942 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011943 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011944 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011945 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011946 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011947 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011948 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011949 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011950 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011951 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011952 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011953 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011954 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011955 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011956 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011957 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011958 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011959 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011960 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011961 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000011962 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011963 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011964 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011965 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011966 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011967 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011968 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011969 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011970 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011971 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011972 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011973 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011974 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011975 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000011976 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011977 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011978 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011979 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011980 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011981 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011982 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011983 llvm_unreachable("Clause is not allowed.");
11984 }
11985 return Res;
11986}
11987
Alexey Bataev90c228f2016-02-08 09:29:13 +000011988ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000011989 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000011990 ExprResult Res = BuildDeclRefExpr(
11991 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
11992 if (!Res.isUsable())
11993 return ExprError();
11994 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
11995 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
11996 if (!Res.isUsable())
11997 return ExprError();
11998 }
11999 if (VK != VK_LValue && Res.get()->isGLValue()) {
12000 Res = DefaultLvalueConversion(Res.get());
12001 if (!Res.isUsable())
12002 return ExprError();
12003 }
12004 return Res;
12005}
12006
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012007OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12008 SourceLocation StartLoc,
12009 SourceLocation LParenLoc,
12010 SourceLocation EndLoc) {
12011 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012012 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012013 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012014 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012015 SourceLocation ELoc;
12016 SourceRange ERange;
12017 Expr *SimpleRefExpr = RefExpr;
12018 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012019 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012020 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012021 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012022 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012023 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012024 ValueDecl *D = Res.first;
12025 if (!D)
12026 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012027
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012028 QualType Type = D->getType();
12029 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012030
12031 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12032 // A variable that appears in a private clause must not have an incomplete
12033 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012034 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012035 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012036 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012037
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012038 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12039 // A variable that is privatized must not have a const-qualified type
12040 // unless it is of class type with a mutable member. This restriction does
12041 // not apply to the firstprivate clause.
12042 //
12043 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12044 // A variable that appears in a private clause must not have a
12045 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012046 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012047 continue;
12048
Alexey Bataev758e55e2013-09-06 18:03:48 +000012049 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12050 // in a Construct]
12051 // Variables with the predetermined data-sharing attributes may not be
12052 // listed in data-sharing attributes clauses, except for the cases
12053 // listed below. For these exceptions only, listing a predetermined
12054 // variable in a data-sharing attribute clause is allowed and overrides
12055 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012056 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012057 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012058 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12059 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012060 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012061 continue;
12062 }
12063
Alexey Bataeve3727102018-04-18 15:57:46 +000012064 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012065 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012066 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012067 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012068 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12069 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012070 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012071 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012072 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012073 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012074 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012075 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012076 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012077 continue;
12078 }
12079
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012080 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12081 // A list item cannot appear in both a map clause and a data-sharing
12082 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012083 //
12084 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12085 // A list item cannot appear in both a map clause and a data-sharing
12086 // attribute clause on the same construct unless the construct is a
12087 // combined construct.
12088 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12089 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012090 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012091 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012092 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012093 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12094 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12095 ConflictKind = WhereFoundClauseKind;
12096 return true;
12097 })) {
12098 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012099 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012100 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012101 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012102 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012103 continue;
12104 }
12105 }
12106
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012107 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12108 // A variable of class type (or array thereof) that appears in a private
12109 // clause requires an accessible, unambiguous default constructor for the
12110 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012111 // Generate helper private variable and initialize it with the default
12112 // value. The address of the original variable is replaced by the address of
12113 // the new private variable in CodeGen. This new variable is not added to
12114 // IdResolver, so the code in the OpenMP region uses original variable for
12115 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012116 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012117 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012118 buildVarDecl(*this, ELoc, Type, D->getName(),
12119 D->hasAttrs() ? &D->getAttrs() : nullptr,
12120 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012121 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012122 if (VDPrivate->isInvalidDecl())
12123 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012124 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012125 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012126
Alexey Bataev90c228f2016-02-08 09:29:13 +000012127 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012128 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012129 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012130 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012131 Vars.push_back((VD || CurContext->isDependentContext())
12132 ? RefExpr->IgnoreParens()
12133 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012134 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012135 }
12136
Alexey Bataeved09d242014-05-28 05:53:51 +000012137 if (Vars.empty())
12138 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012139
Alexey Bataev03b340a2014-10-21 03:16:40 +000012140 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12141 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012142}
12143
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012144namespace {
12145class DiagsUninitializedSeveretyRAII {
12146private:
12147 DiagnosticsEngine &Diags;
12148 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012149 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012150
12151public:
12152 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12153 bool IsIgnored)
12154 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12155 if (!IsIgnored) {
12156 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12157 /*Map*/ diag::Severity::Ignored, Loc);
12158 }
12159 }
12160 ~DiagsUninitializedSeveretyRAII() {
12161 if (!IsIgnored)
12162 Diags.popMappings(SavedLoc);
12163 }
12164};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012165}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012166
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012167OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12168 SourceLocation StartLoc,
12169 SourceLocation LParenLoc,
12170 SourceLocation EndLoc) {
12171 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012172 SmallVector<Expr *, 8> PrivateCopies;
12173 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012174 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012175 bool IsImplicitClause =
12176 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012177 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012178
Alexey Bataeve3727102018-04-18 15:57:46 +000012179 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012180 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012181 SourceLocation ELoc;
12182 SourceRange ERange;
12183 Expr *SimpleRefExpr = RefExpr;
12184 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012185 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012186 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012187 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012188 PrivateCopies.push_back(nullptr);
12189 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012190 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012191 ValueDecl *D = Res.first;
12192 if (!D)
12193 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012194
Alexey Bataev60da77e2016-02-29 05:54:20 +000012195 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012196 QualType Type = D->getType();
12197 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012198
12199 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12200 // A variable that appears in a private clause must not have an incomplete
12201 // type or a reference type.
12202 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012203 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012204 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012205 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012206
12207 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12208 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012209 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012210 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012211 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012212
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012213 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012214 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012215 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012216 DSAStackTy::DSAVarData DVar =
12217 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012218 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012219 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012220 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012221 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12222 // A list item that specifies a given variable may not appear in more
12223 // than one clause on the same directive, except that a variable may be
12224 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012225 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12226 // A list item may appear in a firstprivate or lastprivate clause but not
12227 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012228 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012229 (isOpenMPDistributeDirective(CurrDir) ||
12230 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012231 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012232 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012233 << getOpenMPClauseName(DVar.CKind)
12234 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012235 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012236 continue;
12237 }
12238
12239 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12240 // in a Construct]
12241 // Variables with the predetermined data-sharing attributes may not be
12242 // listed in data-sharing attributes clauses, except for the cases
12243 // listed below. For these exceptions only, listing a predetermined
12244 // variable in a data-sharing attribute clause is allowed and overrides
12245 // the variable's predetermined data-sharing attributes.
12246 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12247 // in a Construct, C/C++, p.2]
12248 // Variables with const-qualified type having no mutable member may be
12249 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012250 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012251 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12252 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012253 << getOpenMPClauseName(DVar.CKind)
12254 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012255 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012256 continue;
12257 }
12258
12259 // OpenMP [2.9.3.4, Restrictions, p.2]
12260 // A list item that is private within a parallel region must not appear
12261 // in a firstprivate clause on a worksharing construct if any of the
12262 // worksharing regions arising from the worksharing construct ever bind
12263 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012264 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12265 // A list item that is private within a teams region must not appear in a
12266 // firstprivate clause on a distribute construct if any of the distribute
12267 // regions arising from the distribute construct ever bind to any of the
12268 // teams regions arising from the teams construct.
12269 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12270 // A list item that appears in a reduction clause of a teams construct
12271 // must not appear in a firstprivate clause on a distribute construct if
12272 // any of the distribute regions arising from the distribute construct
12273 // ever bind to any of the teams regions arising from the teams construct.
12274 if ((isOpenMPWorksharingDirective(CurrDir) ||
12275 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012276 !isOpenMPParallelDirective(CurrDir) &&
12277 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012278 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012279 if (DVar.CKind != OMPC_shared &&
12280 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012281 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012282 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012283 Diag(ELoc, diag::err_omp_required_access)
12284 << getOpenMPClauseName(OMPC_firstprivate)
12285 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012286 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012287 continue;
12288 }
12289 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012290 // OpenMP [2.9.3.4, Restrictions, p.3]
12291 // A list item that appears in a reduction clause of a parallel construct
12292 // must not appear in a firstprivate clause on a worksharing or task
12293 // construct if any of the worksharing or task regions arising from the
12294 // worksharing or task construct ever bind to any of the parallel regions
12295 // arising from the parallel construct.
12296 // OpenMP [2.9.3.4, Restrictions, p.4]
12297 // A list item that appears in a reduction clause in worksharing
12298 // construct must not appear in a firstprivate clause in a task construct
12299 // encountered during execution of any of the worksharing regions arising
12300 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012301 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012302 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012303 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12304 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012305 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012306 isOpenMPWorksharingDirective(K) ||
12307 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012308 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012309 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012310 if (DVar.CKind == OMPC_reduction &&
12311 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012312 isOpenMPWorksharingDirective(DVar.DKind) ||
12313 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012314 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12315 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012316 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012317 continue;
12318 }
12319 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012320
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012321 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12322 // A list item cannot appear in both a map clause and a data-sharing
12323 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012324 //
12325 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12326 // A list item cannot appear in both a map clause and a data-sharing
12327 // attribute clause on the same construct unless the construct is a
12328 // combined construct.
12329 if ((LangOpts.OpenMP <= 45 &&
12330 isOpenMPTargetExecutionDirective(CurrDir)) ||
12331 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012332 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012333 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012334 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012335 [&ConflictKind](
12336 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12337 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012338 ConflictKind = WhereFoundClauseKind;
12339 return true;
12340 })) {
12341 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012342 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000012343 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012344 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000012345 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012346 continue;
12347 }
12348 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012349 }
12350
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012351 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012352 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000012353 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012354 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12355 << getOpenMPClauseName(OMPC_firstprivate) << Type
12356 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
12357 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012358 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012359 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012360 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012361 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012362 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012363 continue;
12364 }
12365
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012366 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012367 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012368 buildVarDecl(*this, ELoc, Type, D->getName(),
12369 D->hasAttrs() ? &D->getAttrs() : nullptr,
12370 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012371 // Generate helper private variable and initialize it with the value of the
12372 // original variable. The address of the original variable is replaced by
12373 // the address of the new private variable in the CodeGen. This new variable
12374 // is not added to IdResolver, so the code in the OpenMP region uses
12375 // original variable for proper diagnostics and variable capturing.
12376 Expr *VDInitRefExpr = nullptr;
12377 // For arrays generate initializer for single element and replace it by the
12378 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012379 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012380 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012381 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012382 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012383 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012384 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012385 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12386 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012387 InitializedEntity Entity =
12388 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012389 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12390
12391 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12392 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12393 if (Result.isInvalid())
12394 VDPrivate->setInvalidDecl();
12395 else
12396 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012397 // Remove temp variable declaration.
12398 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012399 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012400 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12401 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012402 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12403 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012404 AddInitializerToDecl(VDPrivate,
12405 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012406 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012407 }
12408 if (VDPrivate->isInvalidDecl()) {
12409 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012410 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012411 diag::note_omp_task_predetermined_firstprivate_here);
12412 }
12413 continue;
12414 }
12415 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012416 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012417 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12418 RefExpr->getExprLoc());
12419 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012420 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012421 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012422 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012423 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012424 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012425 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012426 ExprCaptures.push_back(Ref->getDecl());
12427 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012428 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012429 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012430 Vars.push_back((VD || CurContext->isDependentContext())
12431 ? RefExpr->IgnoreParens()
12432 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012433 PrivateCopies.push_back(VDPrivateRefExpr);
12434 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012435 }
12436
Alexey Bataeved09d242014-05-28 05:53:51 +000012437 if (Vars.empty())
12438 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012439
12440 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012441 Vars, PrivateCopies, Inits,
12442 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012443}
12444
Alexander Musman1bb328c2014-06-04 13:06:39 +000012445OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12446 SourceLocation StartLoc,
12447 SourceLocation LParenLoc,
12448 SourceLocation EndLoc) {
12449 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012450 SmallVector<Expr *, 8> SrcExprs;
12451 SmallVector<Expr *, 8> DstExprs;
12452 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012453 SmallVector<Decl *, 4> ExprCaptures;
12454 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012455 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012456 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012457 SourceLocation ELoc;
12458 SourceRange ERange;
12459 Expr *SimpleRefExpr = RefExpr;
12460 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012461 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012462 // It will be analyzed later.
12463 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012464 SrcExprs.push_back(nullptr);
12465 DstExprs.push_back(nullptr);
12466 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012467 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012468 ValueDecl *D = Res.first;
12469 if (!D)
12470 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012471
Alexey Bataev74caaf22016-02-20 04:09:36 +000012472 QualType Type = D->getType();
12473 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012474
12475 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12476 // A variable that appears in a lastprivate clause must not have an
12477 // incomplete type or a reference type.
12478 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012479 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012480 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012481 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012482
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012483 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12484 // A variable that is privatized must not have a const-qualified type
12485 // unless it is of class type with a mutable member. This restriction does
12486 // not apply to the firstprivate clause.
12487 //
12488 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12489 // A variable that appears in a lastprivate clause must not have a
12490 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012491 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012492 continue;
12493
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012494 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012495 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12496 // in a Construct]
12497 // Variables with the predetermined data-sharing attributes may not be
12498 // listed in data-sharing attributes clauses, except for the cases
12499 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012500 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12501 // A list item may appear in a firstprivate or lastprivate clause but not
12502 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012503 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012504 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012505 (isOpenMPDistributeDirective(CurrDir) ||
12506 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012507 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12508 Diag(ELoc, diag::err_omp_wrong_dsa)
12509 << getOpenMPClauseName(DVar.CKind)
12510 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012511 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012512 continue;
12513 }
12514
Alexey Bataevf29276e2014-06-18 04:14:57 +000012515 // OpenMP [2.14.3.5, Restrictions, p.2]
12516 // A list item that is private within a parallel region, or that appears in
12517 // the reduction clause of a parallel construct, must not appear in a
12518 // lastprivate clause on a worksharing construct if any of the corresponding
12519 // worksharing regions ever binds to any of the corresponding parallel
12520 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012521 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012522 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012523 !isOpenMPParallelDirective(CurrDir) &&
12524 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012525 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012526 if (DVar.CKind != OMPC_shared) {
12527 Diag(ELoc, diag::err_omp_required_access)
12528 << getOpenMPClauseName(OMPC_lastprivate)
12529 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012530 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012531 continue;
12532 }
12533 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012534
Alexander Musman1bb328c2014-06-04 13:06:39 +000012535 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012536 // A variable of class type (or array thereof) that appears in a
12537 // lastprivate clause requires an accessible, unambiguous default
12538 // constructor for the class type, unless the list item is also specified
12539 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012540 // A variable of class type (or array thereof) that appears in a
12541 // lastprivate clause requires an accessible, unambiguous copy assignment
12542 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012543 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012544 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12545 Type.getUnqualifiedType(), ".lastprivate.src",
12546 D->hasAttrs() ? &D->getAttrs() : nullptr);
12547 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012548 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012549 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012550 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012551 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012552 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012553 // For arrays generate assignment operation for single element and replace
12554 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012555 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12556 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012557 if (AssignmentOp.isInvalid())
12558 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012559 AssignmentOp =
12560 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012561 if (AssignmentOp.isInvalid())
12562 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012563
Alexey Bataev74caaf22016-02-20 04:09:36 +000012564 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012565 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012566 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012567 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012568 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012569 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012570 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012571 ExprCaptures.push_back(Ref->getDecl());
12572 }
12573 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012574 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012575 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012576 ExprResult RefRes = DefaultLvalueConversion(Ref);
12577 if (!RefRes.isUsable())
12578 continue;
12579 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012580 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12581 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012582 if (!PostUpdateRes.isUsable())
12583 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012584 ExprPostUpdates.push_back(
12585 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012586 }
12587 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012588 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012589 Vars.push_back((VD || CurContext->isDependentContext())
12590 ? RefExpr->IgnoreParens()
12591 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012592 SrcExprs.push_back(PseudoSrcExpr);
12593 DstExprs.push_back(PseudoDstExpr);
12594 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012595 }
12596
12597 if (Vars.empty())
12598 return nullptr;
12599
12600 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012601 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012602 buildPreInits(Context, ExprCaptures),
12603 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012604}
12605
Alexey Bataev758e55e2013-09-06 18:03:48 +000012606OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12607 SourceLocation StartLoc,
12608 SourceLocation LParenLoc,
12609 SourceLocation EndLoc) {
12610 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012611 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012612 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012613 SourceLocation ELoc;
12614 SourceRange ERange;
12615 Expr *SimpleRefExpr = RefExpr;
12616 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012617 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012618 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012619 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012620 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012621 ValueDecl *D = Res.first;
12622 if (!D)
12623 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012624
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012625 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12627 // in a Construct]
12628 // Variables with the predetermined data-sharing attributes may not be
12629 // listed in data-sharing attributes clauses, except for the cases
12630 // listed below. For these exceptions only, listing a predetermined
12631 // variable in a data-sharing attribute clause is allowed and overrides
12632 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012633 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012634 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12635 DVar.RefExpr) {
12636 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12637 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012638 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012639 continue;
12640 }
12641
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012642 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012643 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012644 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012645 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012646 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12647 ? RefExpr->IgnoreParens()
12648 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012649 }
12650
Alexey Bataeved09d242014-05-28 05:53:51 +000012651 if (Vars.empty())
12652 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012653
12654 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12655}
12656
Alexey Bataevc5e02582014-06-16 07:08:35 +000012657namespace {
12658class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12659 DSAStackTy *Stack;
12660
12661public:
12662 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012663 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12664 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012665 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12666 return false;
12667 if (DVar.CKind != OMPC_unknown)
12668 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012669 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012670 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012671 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012672 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012673 }
12674 return false;
12675 }
12676 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012677 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012678 if (Child && Visit(Child))
12679 return true;
12680 }
12681 return false;
12682 }
Alexey Bataev23b69422014-06-18 07:08:49 +000012683 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012684};
Alexey Bataev23b69422014-06-18 07:08:49 +000012685} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000012686
Alexey Bataev60da77e2016-02-29 05:54:20 +000012687namespace {
12688// Transform MemberExpression for specified FieldDecl of current class to
12689// DeclRefExpr to specified OMPCapturedExprDecl.
12690class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
12691 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000012692 ValueDecl *Field = nullptr;
12693 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012694
12695public:
12696 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
12697 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
12698
12699 ExprResult TransformMemberExpr(MemberExpr *E) {
12700 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
12701 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000012702 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012703 return CapturedExpr;
12704 }
12705 return BaseTransform::TransformMemberExpr(E);
12706 }
12707 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
12708};
12709} // namespace
12710
Alexey Bataev97d18bf2018-04-11 19:21:00 +000012711template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000012712static T filterLookupForUDReductionAndMapper(
12713 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012714 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012715 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012716 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012717 return Res;
12718 }
12719 }
12720 return T();
12721}
12722
Alexey Bataev43b90b72018-09-12 16:31:59 +000012723static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
12724 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
12725
12726 for (auto RD : D->redecls()) {
12727 // Don't bother with extra checks if we already know this one isn't visible.
12728 if (RD == D)
12729 continue;
12730
12731 auto ND = cast<NamedDecl>(RD);
12732 if (LookupResult::isVisible(SemaRef, ND))
12733 return ND;
12734 }
12735
12736 return nullptr;
12737}
12738
12739static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000012740argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000012741 SourceLocation Loc, QualType Ty,
12742 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
12743 // Find all of the associated namespaces and classes based on the
12744 // arguments we have.
12745 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12746 Sema::AssociatedClassSet AssociatedClasses;
12747 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
12748 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
12749 AssociatedClasses);
12750
12751 // C++ [basic.lookup.argdep]p3:
12752 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12753 // and let Y be the lookup set produced by argument dependent
12754 // lookup (defined as follows). If X contains [...] then Y is
12755 // empty. Otherwise Y is the set of declarations found in the
12756 // namespaces associated with the argument types as described
12757 // below. The set of declarations found by the lookup of the name
12758 // is the union of X and Y.
12759 //
12760 // Here, we compute Y and add its members to the overloaded
12761 // candidate set.
12762 for (auto *NS : AssociatedNamespaces) {
12763 // When considering an associated namespace, the lookup is the
12764 // same as the lookup performed when the associated namespace is
12765 // used as a qualifier (3.4.3.2) except that:
12766 //
12767 // -- Any using-directives in the associated namespace are
12768 // ignored.
12769 //
12770 // -- Any namespace-scope friend functions declared in
12771 // associated classes are visible within their respective
12772 // namespaces even if they are not visible during an ordinary
12773 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000012774 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000012775 for (auto *D : R) {
12776 auto *Underlying = D;
12777 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12778 Underlying = USD->getTargetDecl();
12779
Michael Kruse4304e9d2019-02-19 16:38:20 +000012780 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
12781 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000012782 continue;
12783
12784 if (!SemaRef.isVisible(D)) {
12785 D = findAcceptableDecl(SemaRef, D);
12786 if (!D)
12787 continue;
12788 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12789 Underlying = USD->getTargetDecl();
12790 }
12791 Lookups.emplace_back();
12792 Lookups.back().addDecl(Underlying);
12793 }
12794 }
12795}
12796
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012797static ExprResult
12798buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
12799 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
12800 const DeclarationNameInfo &ReductionId, QualType Ty,
12801 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
12802 if (ReductionIdScopeSpec.isInvalid())
12803 return ExprError();
12804 SmallVector<UnresolvedSet<8>, 4> Lookups;
12805 if (S) {
12806 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12807 Lookup.suppressDiagnostics();
12808 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012809 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012810 do {
12811 S = S->getParent();
12812 } while (S && !S->isDeclScope(D));
12813 if (S)
12814 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000012815 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012816 Lookups.back().append(Lookup.begin(), Lookup.end());
12817 Lookup.clear();
12818 }
12819 } else if (auto *ULE =
12820 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
12821 Lookups.push_back(UnresolvedSet<8>());
12822 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012823 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012824 if (D == PrevD)
12825 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000012826 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012827 Lookups.back().addDecl(DRD);
12828 PrevD = D;
12829 }
12830 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000012831 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
12832 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012833 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000012834 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012835 return !D->isInvalidDecl() &&
12836 (D->getType()->isDependentType() ||
12837 D->getType()->isInstantiationDependentType() ||
12838 D->getType()->containsUnexpandedParameterPack());
12839 })) {
12840 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000012841 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000012842 if (Set.empty())
12843 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012844 ResSet.append(Set.begin(), Set.end());
12845 // The last item marks the end of all declarations at the specified scope.
12846 ResSet.addDecl(Set[Set.size() - 1]);
12847 }
12848 return UnresolvedLookupExpr::Create(
12849 SemaRef.Context, /*NamingClass=*/nullptr,
12850 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
12851 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
12852 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000012853 // Lookup inside the classes.
12854 // C++ [over.match.oper]p3:
12855 // For a unary operator @ with an operand of a type whose
12856 // cv-unqualified version is T1, and for a binary operator @ with
12857 // a left operand of a type whose cv-unqualified version is T1 and
12858 // a right operand of a type whose cv-unqualified version is T2,
12859 // three sets of candidate functions, designated member
12860 // candidates, non-member candidates and built-in candidates, are
12861 // constructed as follows:
12862 // -- If T1 is a complete class type or a class currently being
12863 // defined, the set of member candidates is the result of the
12864 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
12865 // the set of member candidates is empty.
12866 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12867 Lookup.suppressDiagnostics();
12868 if (const auto *TyRec = Ty->getAs<RecordType>()) {
12869 // Complete the type if it can be completed.
12870 // If the type is neither complete nor being defined, bail out now.
12871 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
12872 TyRec->getDecl()->getDefinition()) {
12873 Lookup.clear();
12874 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
12875 if (Lookup.empty()) {
12876 Lookups.emplace_back();
12877 Lookups.back().append(Lookup.begin(), Lookup.end());
12878 }
12879 }
12880 }
12881 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000012882 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000012883 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000012884 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12885 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
12886 if (!D->isInvalidDecl() &&
12887 SemaRef.Context.hasSameType(D->getType(), Ty))
12888 return D;
12889 return nullptr;
12890 }))
12891 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
12892 VK_LValue, Loc);
12893 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000012894 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12895 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
12896 if (!D->isInvalidDecl() &&
12897 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
12898 !Ty.isMoreQualifiedThan(D->getType()))
12899 return D;
12900 return nullptr;
12901 })) {
12902 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
12903 /*DetectVirtual=*/false);
12904 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
12905 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
12906 VD->getType().getUnqualifiedType()))) {
12907 if (SemaRef.CheckBaseClassAccess(
12908 Loc, VD->getType(), Ty, Paths.front(),
12909 /*DiagID=*/0) != Sema::AR_inaccessible) {
12910 SemaRef.BuildBasePathArray(Paths, BasePath);
12911 return SemaRef.BuildDeclRefExpr(
12912 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
12913 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012914 }
12915 }
12916 }
12917 }
12918 if (ReductionIdScopeSpec.isSet()) {
12919 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
12920 return ExprError();
12921 }
12922 return ExprEmpty();
12923}
12924
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012925namespace {
12926/// Data for the reduction-based clauses.
12927struct ReductionData {
12928 /// List of original reduction items.
12929 SmallVector<Expr *, 8> Vars;
12930 /// List of private copies of the reduction items.
12931 SmallVector<Expr *, 8> Privates;
12932 /// LHS expressions for the reduction_op expressions.
12933 SmallVector<Expr *, 8> LHSs;
12934 /// RHS expressions for the reduction_op expressions.
12935 SmallVector<Expr *, 8> RHSs;
12936 /// Reduction operation expression.
12937 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000012938 /// Taskgroup descriptors for the corresponding reduction items in
12939 /// in_reduction clauses.
12940 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012941 /// List of captures for clause.
12942 SmallVector<Decl *, 4> ExprCaptures;
12943 /// List of postupdate expressions.
12944 SmallVector<Expr *, 4> ExprPostUpdates;
12945 ReductionData() = delete;
12946 /// Reserves required memory for the reduction data.
12947 ReductionData(unsigned Size) {
12948 Vars.reserve(Size);
12949 Privates.reserve(Size);
12950 LHSs.reserve(Size);
12951 RHSs.reserve(Size);
12952 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000012953 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012954 ExprCaptures.reserve(Size);
12955 ExprPostUpdates.reserve(Size);
12956 }
12957 /// Stores reduction item and reduction operation only (required for dependent
12958 /// reduction item).
12959 void push(Expr *Item, Expr *ReductionOp) {
12960 Vars.emplace_back(Item);
12961 Privates.emplace_back(nullptr);
12962 LHSs.emplace_back(nullptr);
12963 RHSs.emplace_back(nullptr);
12964 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012965 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012966 }
12967 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000012968 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
12969 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012970 Vars.emplace_back(Item);
12971 Privates.emplace_back(Private);
12972 LHSs.emplace_back(LHS);
12973 RHSs.emplace_back(RHS);
12974 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012975 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012976 }
12977};
12978} // namespace
12979
Alexey Bataeve3727102018-04-18 15:57:46 +000012980static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012981 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
12982 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
12983 const Expr *Length = OASE->getLength();
12984 if (Length == nullptr) {
12985 // For array sections of the form [1:] or [:], we would need to analyze
12986 // the lower bound...
12987 if (OASE->getColonLoc().isValid())
12988 return false;
12989
12990 // This is an array subscript which has implicit length 1!
12991 SingleElement = true;
12992 ArraySizes.push_back(llvm::APSInt::get(1));
12993 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012994 Expr::EvalResult Result;
12995 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012996 return false;
12997
Fangrui Song407659a2018-11-30 23:41:18 +000012998 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012999 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13000 ArraySizes.push_back(ConstantLengthValue);
13001 }
13002
13003 // Get the base of this array section and walk up from there.
13004 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13005
13006 // We require length = 1 for all array sections except the right-most to
13007 // guarantee that the memory region is contiguous and has no holes in it.
13008 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13009 Length = TempOASE->getLength();
13010 if (Length == nullptr) {
13011 // For array sections of the form [1:] or [:], we would need to analyze
13012 // the lower bound...
13013 if (OASE->getColonLoc().isValid())
13014 return false;
13015
13016 // This is an array subscript which has implicit length 1!
13017 ArraySizes.push_back(llvm::APSInt::get(1));
13018 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013019 Expr::EvalResult Result;
13020 if (!Length->EvaluateAsInt(Result, Context))
13021 return false;
13022
13023 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13024 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013025 return false;
13026
13027 ArraySizes.push_back(ConstantLengthValue);
13028 }
13029 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13030 }
13031
13032 // If we have a single element, we don't need to add the implicit lengths.
13033 if (!SingleElement) {
13034 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13035 // Has implicit length 1!
13036 ArraySizes.push_back(llvm::APSInt::get(1));
13037 Base = TempASE->getBase()->IgnoreParenImpCasts();
13038 }
13039 }
13040
13041 // This array section can be privatized as a single value or as a constant
13042 // sized array.
13043 return true;
13044}
13045
Alexey Bataeve3727102018-04-18 15:57:46 +000013046static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013047 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13048 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13049 SourceLocation ColonLoc, SourceLocation EndLoc,
13050 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013051 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013052 DeclarationName DN = ReductionId.getName();
13053 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013054 BinaryOperatorKind BOK = BO_Comma;
13055
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013056 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013057 // OpenMP [2.14.3.6, reduction clause]
13058 // C
13059 // reduction-identifier is either an identifier or one of the following
13060 // operators: +, -, *, &, |, ^, && and ||
13061 // C++
13062 // reduction-identifier is either an id-expression or one of the following
13063 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013064 switch (OOK) {
13065 case OO_Plus:
13066 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013067 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013068 break;
13069 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013070 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013071 break;
13072 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013073 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013074 break;
13075 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013076 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013077 break;
13078 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013079 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013080 break;
13081 case OO_AmpAmp:
13082 BOK = BO_LAnd;
13083 break;
13084 case OO_PipePipe:
13085 BOK = BO_LOr;
13086 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013087 case OO_New:
13088 case OO_Delete:
13089 case OO_Array_New:
13090 case OO_Array_Delete:
13091 case OO_Slash:
13092 case OO_Percent:
13093 case OO_Tilde:
13094 case OO_Exclaim:
13095 case OO_Equal:
13096 case OO_Less:
13097 case OO_Greater:
13098 case OO_LessEqual:
13099 case OO_GreaterEqual:
13100 case OO_PlusEqual:
13101 case OO_MinusEqual:
13102 case OO_StarEqual:
13103 case OO_SlashEqual:
13104 case OO_PercentEqual:
13105 case OO_CaretEqual:
13106 case OO_AmpEqual:
13107 case OO_PipeEqual:
13108 case OO_LessLess:
13109 case OO_GreaterGreater:
13110 case OO_LessLessEqual:
13111 case OO_GreaterGreaterEqual:
13112 case OO_EqualEqual:
13113 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013114 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013115 case OO_PlusPlus:
13116 case OO_MinusMinus:
13117 case OO_Comma:
13118 case OO_ArrowStar:
13119 case OO_Arrow:
13120 case OO_Call:
13121 case OO_Subscript:
13122 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013123 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013124 case NUM_OVERLOADED_OPERATORS:
13125 llvm_unreachable("Unexpected reduction identifier");
13126 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013127 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013128 if (II->isStr("max"))
13129 BOK = BO_GT;
13130 else if (II->isStr("min"))
13131 BOK = BO_LT;
13132 }
13133 break;
13134 }
13135 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013136 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013137 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013138 else
13139 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013140 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013141
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013142 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13143 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013144 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013145 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013146 // OpenMP [2.1, C/C++]
13147 // A list item is a variable or array section, subject to the restrictions
13148 // specified in Section 2.4 on page 42 and in each of the sections
13149 // describing clauses and directives for which a list appears.
13150 // OpenMP [2.14.3.3, Restrictions, p.1]
13151 // A variable that is part of another variable (as an array or
13152 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013153 if (!FirstIter && IR != ER)
13154 ++IR;
13155 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013156 SourceLocation ELoc;
13157 SourceRange ERange;
13158 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013159 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013160 /*AllowArraySection=*/true);
13161 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013162 // Try to find 'declare reduction' corresponding construct before using
13163 // builtin/overloaded operators.
13164 QualType Type = Context.DependentTy;
13165 CXXCastPath BasePath;
13166 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013167 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013168 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013169 Expr *ReductionOp = nullptr;
13170 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013171 (DeclareReductionRef.isUnset() ||
13172 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013173 ReductionOp = DeclareReductionRef.get();
13174 // It will be analyzed later.
13175 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013176 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013177 ValueDecl *D = Res.first;
13178 if (!D)
13179 continue;
13180
Alexey Bataev88202be2017-07-27 13:20:36 +000013181 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013182 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013183 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13184 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013185 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013186 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013187 } else if (OASE) {
13188 QualType BaseType =
13189 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13190 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013191 Type = ATy->getElementType();
13192 else
13193 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013194 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013195 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013196 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013197 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013198 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013199
Alexey Bataevc5e02582014-06-16 07:08:35 +000013200 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13201 // A variable that appears in a private clause must not have an incomplete
13202 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013203 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013204 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013205 continue;
13206 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013207 // A list item that appears in a reduction clause must not be
13208 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013209 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13210 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013211 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013212
13213 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013214 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13215 // If a list-item is a reference type then it must bind to the same object
13216 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013217 if (!ASE && !OASE) {
13218 if (VD) {
13219 VarDecl *VDDef = VD->getDefinition();
13220 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13221 DSARefChecker Check(Stack);
13222 if (Check.Visit(VDDef->getInit())) {
13223 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13224 << getOpenMPClauseName(ClauseKind) << ERange;
13225 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13226 continue;
13227 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013228 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013229 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013230
Alexey Bataevbc529672018-09-28 19:33:14 +000013231 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13232 // in a Construct]
13233 // Variables with the predetermined data-sharing attributes may not be
13234 // listed in data-sharing attributes clauses, except for the cases
13235 // listed below. For these exceptions only, listing a predetermined
13236 // variable in a data-sharing attribute clause is allowed and overrides
13237 // the variable's predetermined data-sharing attributes.
13238 // OpenMP [2.14.3.6, Restrictions, p.3]
13239 // Any number of reduction clauses can be specified on the directive,
13240 // but a list item can appear only once in the reduction clauses for that
13241 // directive.
13242 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13243 if (DVar.CKind == OMPC_reduction) {
13244 S.Diag(ELoc, diag::err_omp_once_referenced)
13245 << getOpenMPClauseName(ClauseKind);
13246 if (DVar.RefExpr)
13247 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13248 continue;
13249 }
13250 if (DVar.CKind != OMPC_unknown) {
13251 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13252 << getOpenMPClauseName(DVar.CKind)
13253 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013254 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013255 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013256 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013257
13258 // OpenMP [2.14.3.6, Restrictions, p.1]
13259 // A list item that appears in a reduction clause of a worksharing
13260 // construct must be shared in the parallel regions to which any of the
13261 // worksharing regions arising from the worksharing construct bind.
13262 if (isOpenMPWorksharingDirective(CurrDir) &&
13263 !isOpenMPParallelDirective(CurrDir) &&
13264 !isOpenMPTeamsDirective(CurrDir)) {
13265 DVar = Stack->getImplicitDSA(D, true);
13266 if (DVar.CKind != OMPC_shared) {
13267 S.Diag(ELoc, diag::err_omp_required_access)
13268 << getOpenMPClauseName(OMPC_reduction)
13269 << getOpenMPClauseName(OMPC_shared);
13270 reportOriginalDsa(S, Stack, D, DVar);
13271 continue;
13272 }
13273 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013274 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013275
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013276 // Try to find 'declare reduction' corresponding construct before using
13277 // builtin/overloaded operators.
13278 CXXCastPath BasePath;
13279 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013280 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013281 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13282 if (DeclareReductionRef.isInvalid())
13283 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013284 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013285 (DeclareReductionRef.isUnset() ||
13286 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013287 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013288 continue;
13289 }
13290 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13291 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013292 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013293 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013294 << Type << ReductionIdRange;
13295 continue;
13296 }
13297
13298 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13299 // The type of a list item that appears in a reduction clause must be valid
13300 // for the reduction-identifier. For a max or min reduction in C, the type
13301 // of the list item must be an allowed arithmetic data type: char, int,
13302 // float, double, or _Bool, possibly modified with long, short, signed, or
13303 // unsigned. For a max or min reduction in C++, the type of the list item
13304 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13305 // double, or bool, possibly modified with long, short, signed, or unsigned.
13306 if (DeclareReductionRef.isUnset()) {
13307 if ((BOK == BO_GT || BOK == BO_LT) &&
13308 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013309 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13310 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013311 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013312 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013313 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13314 VarDecl::DeclarationOnly;
13315 S.Diag(D->getLocation(),
13316 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013317 << D;
13318 }
13319 continue;
13320 }
13321 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013322 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000013323 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
13324 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013325 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013326 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13327 VarDecl::DeclarationOnly;
13328 S.Diag(D->getLocation(),
13329 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013330 << D;
13331 }
13332 continue;
13333 }
13334 }
13335
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013336 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013337 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
13338 D->hasAttrs() ? &D->getAttrs() : nullptr);
13339 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
13340 D->hasAttrs() ? &D->getAttrs() : nullptr);
13341 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013342
13343 // Try if we can determine constant lengths for all array sections and avoid
13344 // the VLA.
13345 bool ConstantLengthOASE = false;
13346 if (OASE) {
13347 bool SingleElement;
13348 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000013349 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013350 Context, OASE, SingleElement, ArraySizes);
13351
13352 // If we don't have a single element, we must emit a constant array type.
13353 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013354 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000013355 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
13356 ArrayType::Normal,
13357 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013358 }
13359 }
13360
13361 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013362 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013363 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013364 if (!Context.getTargetInfo().isVLASupported()) {
13365 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13366 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13367 S.Diag(ELoc, diag::note_vla_unsupported);
13368 } else {
13369 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13370 S.targetDiag(ELoc, diag::note_vla_unsupported);
13371 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013372 continue;
13373 }
David Majnemer9d168222016-08-05 17:44:54 +000013374 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013375 // Create pseudo array type for private copy. The size for this array will
13376 // be generated during codegen.
13377 // For array subscripts or single variables Private Ty is the same as Type
13378 // (type of the variable or single array element).
13379 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013380 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013381 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013382 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013383 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013384 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013385 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013386 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013387 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013388 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013389 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13390 D->hasAttrs() ? &D->getAttrs() : nullptr,
13391 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013392 // Add initializer for private variable.
13393 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013394 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13395 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013396 if (DeclareReductionRef.isUsable()) {
13397 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13398 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13399 if (DRD->getInitializer()) {
13400 Init = DRDRef;
13401 RHSVD->setInit(DRDRef);
13402 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013403 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013404 } else {
13405 switch (BOK) {
13406 case BO_Add:
13407 case BO_Xor:
13408 case BO_Or:
13409 case BO_LOr:
13410 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13411 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013412 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013413 break;
13414 case BO_Mul:
13415 case BO_LAnd:
13416 if (Type->isScalarType() || Type->isAnyComplexType()) {
13417 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013418 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013419 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013420 break;
13421 case BO_And: {
13422 // '&' reduction op - initializer is '~0'.
13423 QualType OrigType = Type;
13424 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13425 Type = ComplexTy->getElementType();
13426 if (Type->isRealFloatingType()) {
13427 llvm::APFloat InitValue =
13428 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13429 /*isIEEE=*/true);
13430 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13431 Type, ELoc);
13432 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013433 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013434 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13435 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13436 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13437 }
13438 if (Init && OrigType->isAnyComplexType()) {
13439 // Init = 0xFFFF + 0xFFFFi;
13440 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013441 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013442 }
13443 Type = OrigType;
13444 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013445 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013446 case BO_LT:
13447 case BO_GT: {
13448 // 'min' reduction op - initializer is 'Largest representable number in
13449 // the reduction list item type'.
13450 // 'max' reduction op - initializer is 'Least representable number in
13451 // the reduction list item type'.
13452 if (Type->isIntegerType() || Type->isPointerType()) {
13453 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013454 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013455 QualType IntTy =
13456 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13457 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013458 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13459 : llvm::APInt::getMinValue(Size)
13460 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13461 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013462 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13463 if (Type->isPointerType()) {
13464 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013465 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013466 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013467 if (CastExpr.isInvalid())
13468 continue;
13469 Init = CastExpr.get();
13470 }
13471 } else if (Type->isRealFloatingType()) {
13472 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13473 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13474 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13475 Type, ELoc);
13476 }
13477 break;
13478 }
13479 case BO_PtrMemD:
13480 case BO_PtrMemI:
13481 case BO_MulAssign:
13482 case BO_Div:
13483 case BO_Rem:
13484 case BO_Sub:
13485 case BO_Shl:
13486 case BO_Shr:
13487 case BO_LE:
13488 case BO_GE:
13489 case BO_EQ:
13490 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013491 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013492 case BO_AndAssign:
13493 case BO_XorAssign:
13494 case BO_OrAssign:
13495 case BO_Assign:
13496 case BO_AddAssign:
13497 case BO_SubAssign:
13498 case BO_DivAssign:
13499 case BO_RemAssign:
13500 case BO_ShlAssign:
13501 case BO_ShrAssign:
13502 case BO_Comma:
13503 llvm_unreachable("Unexpected reduction operation");
13504 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013505 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013506 if (Init && DeclareReductionRef.isUnset())
13507 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13508 else if (!Init)
13509 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013510 if (RHSVD->isInvalidDecl())
13511 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013512 if (!RHSVD->hasInit() &&
13513 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013514 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13515 << Type << ReductionIdRange;
13516 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13517 VarDecl::DeclarationOnly;
13518 S.Diag(D->getLocation(),
13519 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013520 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013521 continue;
13522 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013523 // Store initializer for single element in private copy. Will be used during
13524 // codegen.
13525 PrivateVD->setInit(RHSVD->getInit());
13526 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013527 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013528 ExprResult ReductionOp;
13529 if (DeclareReductionRef.isUsable()) {
13530 QualType RedTy = DeclareReductionRef.get()->getType();
13531 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013532 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13533 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013534 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013535 LHS = S.DefaultLvalueConversion(LHS.get());
13536 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013537 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13538 CK_UncheckedDerivedToBase, LHS.get(),
13539 &BasePath, LHS.get()->getValueKind());
13540 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13541 CK_UncheckedDerivedToBase, RHS.get(),
13542 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013543 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013544 FunctionProtoType::ExtProtoInfo EPI;
13545 QualType Params[] = {PtrRedTy, PtrRedTy};
13546 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13547 auto *OVE = new (Context) OpaqueValueExpr(
13548 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013549 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013550 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013551 ReductionOp =
13552 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013553 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013554 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013555 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013556 if (ReductionOp.isUsable()) {
13557 if (BOK != BO_LT && BOK != BO_GT) {
13558 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013559 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013560 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013561 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013562 auto *ConditionalOp = new (Context)
13563 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13564 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013565 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013566 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013567 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013568 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013569 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013570 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13571 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013572 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013573 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013574 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013575 }
13576
Alexey Bataevfa312f32017-07-21 18:48:21 +000013577 // OpenMP [2.15.4.6, Restrictions, p.2]
13578 // A list item that appears in an in_reduction clause of a task construct
13579 // must appear in a task_reduction clause of a construct associated with a
13580 // taskgroup region that includes the participating task in its taskgroup
13581 // set. The construct associated with the innermost region that meets this
13582 // condition must specify the same reduction-identifier as the in_reduction
13583 // clause.
13584 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013585 SourceRange ParentSR;
13586 BinaryOperatorKind ParentBOK;
13587 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013588 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013589 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013590 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13591 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013592 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013593 Stack->getTopMostTaskgroupReductionData(
13594 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013595 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13596 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13597 if (!IsParentBOK && !IsParentReductionOp) {
13598 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13599 continue;
13600 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013601 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13602 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13603 IsParentReductionOp) {
13604 bool EmitError = true;
13605 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13606 llvm::FoldingSetNodeID RedId, ParentRedId;
13607 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13608 DeclareReductionRef.get()->Profile(RedId, Context,
13609 /*Canonical=*/true);
13610 EmitError = RedId != ParentRedId;
13611 }
13612 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013613 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013614 diag::err_omp_reduction_identifier_mismatch)
13615 << ReductionIdRange << RefExpr->getSourceRange();
13616 S.Diag(ParentSR.getBegin(),
13617 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013618 << ParentSR
13619 << (IsParentBOK ? ParentBOKDSA.RefExpr
13620 : ParentReductionOpDSA.RefExpr)
13621 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013622 continue;
13623 }
13624 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013625 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13626 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013627 }
13628
Alexey Bataev60da77e2016-02-29 05:54:20 +000013629 DeclRefExpr *Ref = nullptr;
13630 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013631 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013632 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013633 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013634 VarsExpr =
13635 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13636 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013637 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013638 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013639 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013640 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013641 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013642 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013643 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013644 if (!RefRes.isUsable())
13645 continue;
13646 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013647 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13648 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013649 if (!PostUpdateRes.isUsable())
13650 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013651 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13652 Stack->getCurrentDirective() == OMPD_taskgroup) {
13653 S.Diag(RefExpr->getExprLoc(),
13654 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000013655 << RefExpr->getSourceRange();
13656 continue;
13657 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013658 RD.ExprPostUpdates.emplace_back(
13659 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000013660 }
13661 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013662 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000013663 // All reduction items are still marked as reduction (to do not increase
13664 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013665 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013666 if (CurrDir == OMPD_taskgroup) {
13667 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013668 Stack->addTaskgroupReductionData(D, ReductionIdRange,
13669 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000013670 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013671 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013672 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013673 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
13674 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013675 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013676 return RD.Vars.empty();
13677}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013678
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013679OMPClause *Sema::ActOnOpenMPReductionClause(
13680 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13681 SourceLocation ColonLoc, SourceLocation EndLoc,
13682 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13683 ArrayRef<Expr *> UnresolvedReductions) {
13684 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013685 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013686 StartLoc, LParenLoc, ColonLoc, EndLoc,
13687 ReductionIdScopeSpec, ReductionId,
13688 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013689 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000013690
Alexey Bataevc5e02582014-06-16 07:08:35 +000013691 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013692 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13693 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13694 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13695 buildPreInits(Context, RD.ExprCaptures),
13696 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000013697}
13698
Alexey Bataev169d96a2017-07-18 20:17:46 +000013699OMPClause *Sema::ActOnOpenMPTaskReductionClause(
13700 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13701 SourceLocation ColonLoc, SourceLocation EndLoc,
13702 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13703 ArrayRef<Expr *> UnresolvedReductions) {
13704 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013705 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
13706 StartLoc, LParenLoc, ColonLoc, EndLoc,
13707 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013708 UnresolvedReductions, RD))
13709 return nullptr;
13710
13711 return OMPTaskReductionClause::Create(
13712 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13713 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13714 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13715 buildPreInits(Context, RD.ExprCaptures),
13716 buildPostUpdate(*this, RD.ExprPostUpdates));
13717}
13718
Alexey Bataevfa312f32017-07-21 18:48:21 +000013719OMPClause *Sema::ActOnOpenMPInReductionClause(
13720 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13721 SourceLocation ColonLoc, SourceLocation EndLoc,
13722 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13723 ArrayRef<Expr *> UnresolvedReductions) {
13724 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013725 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013726 StartLoc, LParenLoc, ColonLoc, EndLoc,
13727 ReductionIdScopeSpec, ReductionId,
13728 UnresolvedReductions, RD))
13729 return nullptr;
13730
13731 return OMPInReductionClause::Create(
13732 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13733 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000013734 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013735 buildPreInits(Context, RD.ExprCaptures),
13736 buildPostUpdate(*this, RD.ExprPostUpdates));
13737}
13738
Alexey Bataevecba70f2016-04-12 11:02:11 +000013739bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
13740 SourceLocation LinLoc) {
13741 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
13742 LinKind == OMPC_LINEAR_unknown) {
13743 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
13744 return true;
13745 }
13746 return false;
13747}
13748
Alexey Bataeve3727102018-04-18 15:57:46 +000013749bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000013750 OpenMPLinearClauseKind LinKind,
13751 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013752 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000013753 // A variable must not have an incomplete type or a reference type.
13754 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
13755 return true;
13756 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
13757 !Type->isReferenceType()) {
13758 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
13759 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
13760 return true;
13761 }
13762 Type = Type.getNonReferenceType();
13763
Joel E. Dennybae586f2019-01-04 22:12:13 +000013764 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13765 // A variable that is privatized must not have a const-qualified type
13766 // unless it is of class type with a mutable member. This restriction does
13767 // not apply to the firstprivate clause.
13768 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000013769 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013770
13771 // A list item must be of integral or pointer type.
13772 Type = Type.getUnqualifiedType().getCanonicalType();
13773 const auto *Ty = Type.getTypePtrOrNull();
13774 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
13775 !Ty->isPointerType())) {
13776 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
13777 if (D) {
13778 bool IsDecl =
13779 !VD ||
13780 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13781 Diag(D->getLocation(),
13782 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13783 << D;
13784 }
13785 return true;
13786 }
13787 return false;
13788}
13789
Alexey Bataev182227b2015-08-20 10:54:39 +000013790OMPClause *Sema::ActOnOpenMPLinearClause(
13791 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
13792 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
13793 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013794 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013795 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000013796 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013797 SmallVector<Decl *, 4> ExprCaptures;
13798 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013799 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000013800 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000013801 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013802 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013803 SourceLocation ELoc;
13804 SourceRange ERange;
13805 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013806 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013807 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013808 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013809 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013810 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013811 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000013812 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013813 ValueDecl *D = Res.first;
13814 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000013815 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000013816
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013817 QualType Type = D->getType();
13818 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000013819
13820 // OpenMP [2.14.3.7, linear clause]
13821 // A list-item cannot appear in more than one linear clause.
13822 // A list-item that appears in a linear clause cannot appear in any
13823 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013824 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000013825 if (DVar.RefExpr) {
13826 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13827 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000013828 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000013829 continue;
13830 }
13831
Alexey Bataevecba70f2016-04-12 11:02:11 +000013832 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000013833 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013834 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000013835
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013836 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000013837 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013838 buildVarDecl(*this, ELoc, Type, D->getName(),
13839 D->hasAttrs() ? &D->getAttrs() : nullptr,
13840 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013841 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013842 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013843 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013844 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013845 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013846 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013847 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013848 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013849 ExprCaptures.push_back(Ref->getDecl());
13850 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13851 ExprResult RefRes = DefaultLvalueConversion(Ref);
13852 if (!RefRes.isUsable())
13853 continue;
13854 ExprResult PostUpdateRes =
13855 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
13856 SimpleRefExpr, RefRes.get());
13857 if (!PostUpdateRes.isUsable())
13858 continue;
13859 ExprPostUpdates.push_back(
13860 IgnoredValueConversions(PostUpdateRes.get()).get());
13861 }
13862 }
13863 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013864 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013865 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013866 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013867 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013868 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013869 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013870 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013871
13872 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013873 Vars.push_back((VD || CurContext->isDependentContext())
13874 ? RefExpr->IgnoreParens()
13875 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013876 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000013877 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000013878 }
13879
13880 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013881 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013882
13883 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000013884 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013885 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
13886 !Step->isInstantiationDependent() &&
13887 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013888 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000013889 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000013890 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013891 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013892 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000013893
Alexander Musman3276a272015-03-21 10:12:56 +000013894 // Build var to save the step value.
13895 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013896 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000013897 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013898 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013899 ExprResult CalcStep =
13900 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013901 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013902
Alexander Musman8dba6642014-04-22 13:09:42 +000013903 // Warn about zero linear step (it would be probably better specified as
13904 // making corresponding variables 'const').
13905 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000013906 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
13907 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000013908 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
13909 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000013910 if (!IsConstant && CalcStep.isUsable()) {
13911 // Calculate the step beforehand instead of doing this on each iteration.
13912 // (This is not used if the number of iterations may be kfold-ed).
13913 CalcStepExpr = CalcStep.get();
13914 }
Alexander Musman8dba6642014-04-22 13:09:42 +000013915 }
13916
Alexey Bataev182227b2015-08-20 10:54:39 +000013917 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
13918 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013919 StepExpr, CalcStepExpr,
13920 buildPreInits(Context, ExprCaptures),
13921 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000013922}
13923
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013924static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
13925 Expr *NumIterations, Sema &SemaRef,
13926 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000013927 // Walk the vars and build update/final expressions for the CodeGen.
13928 SmallVector<Expr *, 8> Updates;
13929 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000013930 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000013931 Expr *Step = Clause.getStep();
13932 Expr *CalcStep = Clause.getCalcStep();
13933 // OpenMP [2.14.3.7, linear clause]
13934 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000013935 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000013936 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013937 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000013938 Step = cast<BinaryOperator>(CalcStep)->getLHS();
13939 bool HasErrors = false;
13940 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013941 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000013942 OpenMPLinearClauseKind LinKind = Clause.getModifier();
13943 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013944 SourceLocation ELoc;
13945 SourceRange ERange;
13946 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013947 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013948 ValueDecl *D = Res.first;
13949 if (Res.second || !D) {
13950 Updates.push_back(nullptr);
13951 Finals.push_back(nullptr);
13952 HasErrors = true;
13953 continue;
13954 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013955 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000013956 // OpenMP [2.15.11, distribute simd Construct]
13957 // A list item may not appear in a linear clause, unless it is the loop
13958 // iteration variable.
13959 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
13960 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
13961 SemaRef.Diag(ELoc,
13962 diag::err_omp_linear_distribute_var_non_loop_iteration);
13963 Updates.push_back(nullptr);
13964 Finals.push_back(nullptr);
13965 HasErrors = true;
13966 continue;
13967 }
Alexander Musman3276a272015-03-21 10:12:56 +000013968 Expr *InitExpr = *CurInit;
13969
13970 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000013971 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013972 Expr *CapturedRef;
13973 if (LinKind == OMPC_LINEAR_uval)
13974 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
13975 else
13976 CapturedRef =
13977 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
13978 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
13979 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000013980
13981 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013982 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000013983 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000013984 Update = buildCounterUpdate(
13985 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
13986 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013987 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013988 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013989 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013990 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013991
13992 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013993 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000013994 if (!Info.first)
13995 Final =
13996 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000013997 InitExpr, NumIterations, Step, /*Subtract=*/false,
13998 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013999 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014000 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014001 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014002 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014003
Alexander Musman3276a272015-03-21 10:12:56 +000014004 if (!Update.isUsable() || !Final.isUsable()) {
14005 Updates.push_back(nullptr);
14006 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014007 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014008 HasErrors = true;
14009 } else {
14010 Updates.push_back(Update.get());
14011 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014012 if (!Info.first)
14013 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014014 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014015 ++CurInit;
14016 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014017 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014018 if (Expr *S = Clause.getStep())
14019 UsedExprs.push_back(S);
14020 // Fill the remaining part with the nullptr.
14021 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014022 Clause.setUpdates(Updates);
14023 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014024 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014025 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014026}
14027
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014028OMPClause *Sema::ActOnOpenMPAlignedClause(
14029 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14030 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014031 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014032 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014033 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14034 SourceLocation ELoc;
14035 SourceRange ERange;
14036 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014037 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014038 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014039 // It will be analyzed later.
14040 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014041 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014042 ValueDecl *D = Res.first;
14043 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014044 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014045
Alexey Bataev1efd1662016-03-29 10:59:56 +000014046 QualType QType = D->getType();
14047 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014048
14049 // OpenMP [2.8.1, simd construct, Restrictions]
14050 // The type of list items appearing in the aligned clause must be
14051 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014052 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014053 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014054 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014055 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014056 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014057 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014058 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014059 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014060 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014061 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014062 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014063 continue;
14064 }
14065
14066 // OpenMP [2.8.1, simd construct, Restrictions]
14067 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014068 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000014069 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014070 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14071 << getOpenMPClauseName(OMPC_aligned);
14072 continue;
14073 }
14074
Alexey Bataev1efd1662016-03-29 10:59:56 +000014075 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014076 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014077 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14078 Vars.push_back(DefaultFunctionArrayConversion(
14079 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14080 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014081 }
14082
14083 // OpenMP [2.8.1, simd construct, Description]
14084 // The parameter of the aligned clause, alignment, must be a constant
14085 // positive integer expression.
14086 // If no optional parameter is specified, implementation-defined default
14087 // alignments for SIMD instructions on the target platforms are assumed.
14088 if (Alignment != nullptr) {
14089 ExprResult AlignResult =
14090 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14091 if (AlignResult.isInvalid())
14092 return nullptr;
14093 Alignment = AlignResult.get();
14094 }
14095 if (Vars.empty())
14096 return nullptr;
14097
14098 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14099 EndLoc, Vars, Alignment);
14100}
14101
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014102OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14103 SourceLocation StartLoc,
14104 SourceLocation LParenLoc,
14105 SourceLocation EndLoc) {
14106 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014107 SmallVector<Expr *, 8> SrcExprs;
14108 SmallVector<Expr *, 8> DstExprs;
14109 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014110 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014111 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14112 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014113 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014114 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014115 SrcExprs.push_back(nullptr);
14116 DstExprs.push_back(nullptr);
14117 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014118 continue;
14119 }
14120
Alexey Bataeved09d242014-05-28 05:53:51 +000014121 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014122 // OpenMP [2.1, C/C++]
14123 // A list item is a variable name.
14124 // OpenMP [2.14.4.1, Restrictions, p.1]
14125 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014126 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014127 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014128 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14129 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014130 continue;
14131 }
14132
14133 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014134 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014135
14136 QualType Type = VD->getType();
14137 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14138 // It will be analyzed later.
14139 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014140 SrcExprs.push_back(nullptr);
14141 DstExprs.push_back(nullptr);
14142 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014143 continue;
14144 }
14145
14146 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14147 // A list item that appears in a copyin clause must be threadprivate.
14148 if (!DSAStack->isThreadPrivate(VD)) {
14149 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014150 << getOpenMPClauseName(OMPC_copyin)
14151 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014152 continue;
14153 }
14154
14155 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14156 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014157 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014158 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014159 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14160 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014161 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014162 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014163 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014164 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014165 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014166 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014167 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014168 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014169 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014170 // For arrays generate assignment operation for single element and replace
14171 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014172 ExprResult AssignmentOp =
14173 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14174 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014175 if (AssignmentOp.isInvalid())
14176 continue;
14177 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014178 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014179 if (AssignmentOp.isInvalid())
14180 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014181
14182 DSAStack->addDSA(VD, DE, OMPC_copyin);
14183 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014184 SrcExprs.push_back(PseudoSrcExpr);
14185 DstExprs.push_back(PseudoDstExpr);
14186 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014187 }
14188
Alexey Bataeved09d242014-05-28 05:53:51 +000014189 if (Vars.empty())
14190 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014191
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014192 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14193 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014194}
14195
Alexey Bataevbae9a792014-06-27 10:37:06 +000014196OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14197 SourceLocation StartLoc,
14198 SourceLocation LParenLoc,
14199 SourceLocation EndLoc) {
14200 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014201 SmallVector<Expr *, 8> SrcExprs;
14202 SmallVector<Expr *, 8> DstExprs;
14203 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014204 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014205 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14206 SourceLocation ELoc;
14207 SourceRange ERange;
14208 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014209 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014210 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014211 // It will be analyzed later.
14212 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014213 SrcExprs.push_back(nullptr);
14214 DstExprs.push_back(nullptr);
14215 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014216 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014217 ValueDecl *D = Res.first;
14218 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014219 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014220
Alexey Bataeve122da12016-03-17 10:50:17 +000014221 QualType Type = D->getType();
14222 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014223
14224 // OpenMP [2.14.4.2, Restrictions, p.2]
14225 // A list item that appears in a copyprivate clause may not appear in a
14226 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014227 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014228 DSAStackTy::DSAVarData DVar =
14229 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014230 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14231 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014232 Diag(ELoc, diag::err_omp_wrong_dsa)
14233 << getOpenMPClauseName(DVar.CKind)
14234 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014235 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014236 continue;
14237 }
14238
14239 // OpenMP [2.11.4.2, Restrictions, p.1]
14240 // All list items that appear in a copyprivate clause must be either
14241 // threadprivate or private in the enclosing context.
14242 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014243 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014244 if (DVar.CKind == OMPC_shared) {
14245 Diag(ELoc, diag::err_omp_required_access)
14246 << getOpenMPClauseName(OMPC_copyprivate)
14247 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014248 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014249 continue;
14250 }
14251 }
14252 }
14253
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014254 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014255 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014256 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014257 << getOpenMPClauseName(OMPC_copyprivate) << Type
14258 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014259 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014260 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014261 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014262 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014263 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014264 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014265 continue;
14266 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014267
Alexey Bataevbae9a792014-06-27 10:37:06 +000014268 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14269 // A variable of class type (or array thereof) that appears in a
14270 // copyin clause requires an accessible, unambiguous copy assignment
14271 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014272 Type = Context.getBaseElementType(Type.getNonReferenceType())
14273 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014274 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014275 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014276 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014277 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14278 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014279 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014280 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014281 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14282 ExprResult AssignmentOp = BuildBinOp(
14283 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014284 if (AssignmentOp.isInvalid())
14285 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014286 AssignmentOp =
14287 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014288 if (AssignmentOp.isInvalid())
14289 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014290
14291 // No need to mark vars as copyprivate, they are already threadprivate or
14292 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014293 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014294 Vars.push_back(
14295 VD ? RefExpr->IgnoreParens()
14296 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014297 SrcExprs.push_back(PseudoSrcExpr);
14298 DstExprs.push_back(PseudoDstExpr);
14299 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014300 }
14301
14302 if (Vars.empty())
14303 return nullptr;
14304
Alexey Bataeva63048e2015-03-23 06:18:07 +000014305 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14306 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014307}
14308
Alexey Bataev6125da92014-07-21 11:26:11 +000014309OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14310 SourceLocation StartLoc,
14311 SourceLocation LParenLoc,
14312 SourceLocation EndLoc) {
14313 if (VarList.empty())
14314 return nullptr;
14315
14316 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
14317}
Alexey Bataevdea47612014-07-23 07:46:59 +000014318
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014319OMPClause *
14320Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
14321 SourceLocation DepLoc, SourceLocation ColonLoc,
14322 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
14323 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014324 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014325 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000014326 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014327 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000014328 return nullptr;
14329 }
14330 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014331 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
14332 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000014333 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014334 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000014335 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
14336 /*Last=*/OMPC_DEPEND_unknown, Except)
14337 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014338 return nullptr;
14339 }
14340 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000014341 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014342 llvm::APSInt DepCounter(/*BitWidth=*/32);
14343 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000014344 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
14345 if (const Expr *OrderedCountExpr =
14346 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014347 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
14348 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014349 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014350 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014351 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000014352 assert(RefExpr && "NULL expr in OpenMP shared clause.");
14353 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
14354 // It will be analyzed later.
14355 Vars.push_back(RefExpr);
14356 continue;
14357 }
14358
14359 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000014360 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000014361 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014362 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014363 DepCounter >= TotalDepCount) {
14364 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14365 continue;
14366 }
14367 ++DepCounter;
14368 // OpenMP [2.13.9, Summary]
14369 // depend(dependence-type : vec), where dependence-type is:
14370 // 'sink' and where vec is the iteration vector, which has the form:
14371 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14372 // where n is the value specified by the ordered clause in the loop
14373 // directive, xi denotes the loop iteration variable of the i-th nested
14374 // loop associated with the loop directive, and di is a constant
14375 // non-negative integer.
14376 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014377 // It will be analyzed later.
14378 Vars.push_back(RefExpr);
14379 continue;
14380 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014381 SimpleExpr = SimpleExpr->IgnoreImplicit();
14382 OverloadedOperatorKind OOK = OO_None;
14383 SourceLocation OOLoc;
14384 Expr *LHS = SimpleExpr;
14385 Expr *RHS = nullptr;
14386 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14387 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14388 OOLoc = BO->getOperatorLoc();
14389 LHS = BO->getLHS()->IgnoreParenImpCasts();
14390 RHS = BO->getRHS()->IgnoreParenImpCasts();
14391 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14392 OOK = OCE->getOperator();
14393 OOLoc = OCE->getOperatorLoc();
14394 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14395 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14396 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14397 OOK = MCE->getMethodDecl()
14398 ->getNameInfo()
14399 .getName()
14400 .getCXXOverloadedOperator();
14401 OOLoc = MCE->getCallee()->getExprLoc();
14402 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14403 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014404 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014405 SourceLocation ELoc;
14406 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014407 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014408 if (Res.second) {
14409 // It will be analyzed later.
14410 Vars.push_back(RefExpr);
14411 }
14412 ValueDecl *D = Res.first;
14413 if (!D)
14414 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014415
Alexey Bataev17daedf2018-02-15 22:42:57 +000014416 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14417 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14418 continue;
14419 }
14420 if (RHS) {
14421 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14422 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14423 if (RHSRes.isInvalid())
14424 continue;
14425 }
14426 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014427 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014428 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014429 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014430 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014431 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014432 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14433 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014434 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014435 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014436 continue;
14437 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014438 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014439 } else {
14440 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14441 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14442 (ASE &&
14443 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14444 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14445 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14446 << RefExpr->getSourceRange();
14447 continue;
14448 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014449
14450 ExprResult Res;
14451 {
14452 Sema::TentativeAnalysisScope Trap(*this);
14453 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14454 RefExpr->IgnoreParenImpCasts());
14455 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014456 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14457 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14458 << RefExpr->getSourceRange();
14459 continue;
14460 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014461 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014462 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014463 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014464
14465 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14466 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014467 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014468 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14469 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14470 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14471 }
14472 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14473 Vars.empty())
14474 return nullptr;
14475
Alexey Bataev8b427062016-05-25 12:36:08 +000014476 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014477 DepKind, DepLoc, ColonLoc, Vars,
14478 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014479 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14480 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014481 DSAStack->addDoacrossDependClause(C, OpsOffs);
14482 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014483}
Michael Wonge710d542015-08-07 16:16:36 +000014484
14485OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14486 SourceLocation LParenLoc,
14487 SourceLocation EndLoc) {
14488 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014489 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014490
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014491 // OpenMP [2.9.1, Restrictions]
14492 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014493 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014494 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014495 return nullptr;
14496
Alexey Bataev931e19b2017-10-02 16:32:39 +000014497 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014498 OpenMPDirectiveKind CaptureRegion =
14499 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14500 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014501 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014502 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014503 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14504 HelperValStmt = buildPreInits(Context, Captures);
14505 }
14506
Alexey Bataev8451efa2018-01-15 19:06:12 +000014507 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14508 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014509}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014510
Alexey Bataeve3727102018-04-18 15:57:46 +000014511static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014512 DSAStackTy *Stack, QualType QTy,
14513 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014514 NamedDecl *ND;
14515 if (QTy->isIncompleteType(&ND)) {
14516 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14517 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014518 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014519 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14520 !QTy.isTrivialType(SemaRef.Context))
14521 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014522 return true;
14523}
14524
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014525/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014526/// (array section or array subscript) does NOT specify the whole size of the
14527/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014528static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014529 const Expr *E,
14530 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014531 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014532
14533 // If this is an array subscript, it refers to the whole size if the size of
14534 // the dimension is constant and equals 1. Also, an array section assumes the
14535 // format of an array subscript if no colon is used.
14536 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014537 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014538 return ATy->getSize().getSExtValue() != 1;
14539 // Size can't be evaluated statically.
14540 return false;
14541 }
14542
14543 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014544 const Expr *LowerBound = OASE->getLowerBound();
14545 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014546
14547 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014548 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014549 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014550 Expr::EvalResult Result;
14551 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014552 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014553
14554 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014555 if (ConstLowerBound.getSExtValue())
14556 return true;
14557 }
14558
14559 // If we don't have a length we covering the whole dimension.
14560 if (!Length)
14561 return false;
14562
14563 // If the base is a pointer, we don't have a way to get the size of the
14564 // pointee.
14565 if (BaseQTy->isPointerType())
14566 return false;
14567
14568 // We can only check if the length is the same as the size of the dimension
14569 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014570 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014571 if (!CATy)
14572 return false;
14573
Fangrui Song407659a2018-11-30 23:41:18 +000014574 Expr::EvalResult Result;
14575 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014576 return false; // Can't get the integer value as a constant.
14577
Fangrui Song407659a2018-11-30 23:41:18 +000014578 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014579 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14580}
14581
14582// Return true if it can be proven that the provided array expression (array
14583// section or array subscript) does NOT specify a single element of the array
14584// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014585static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014586 const Expr *E,
14587 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014588 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014589
14590 // An array subscript always refer to a single element. Also, an array section
14591 // assumes the format of an array subscript if no colon is used.
14592 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14593 return false;
14594
14595 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014596 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014597
14598 // If we don't have a length we have to check if the array has unitary size
14599 // for this dimension. Also, we should always expect a length if the base type
14600 // is pointer.
14601 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014602 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014603 return ATy->getSize().getSExtValue() != 1;
14604 // We cannot assume anything.
14605 return false;
14606 }
14607
14608 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014609 Expr::EvalResult Result;
14610 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014611 return false; // Can't get the integer value as a constant.
14612
Fangrui Song407659a2018-11-30 23:41:18 +000014613 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014614 return ConstLength.getSExtValue() != 1;
14615}
14616
Samuel Antao661c0902016-05-26 17:39:58 +000014617// Return the expression of the base of the mappable expression or null if it
14618// cannot be determined and do all the necessary checks to see if the expression
14619// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014620// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014621static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014622 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014623 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014624 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014625 SourceLocation ELoc = E->getExprLoc();
14626 SourceRange ERange = E->getSourceRange();
14627
14628 // The base of elements of list in a map clause have to be either:
14629 // - a reference to variable or field.
14630 // - a member expression.
14631 // - an array expression.
14632 //
14633 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14634 // reference to 'r'.
14635 //
14636 // If we have:
14637 //
14638 // struct SS {
14639 // Bla S;
14640 // foo() {
14641 // #pragma omp target map (S.Arr[:12]);
14642 // }
14643 // }
14644 //
14645 // We want to retrieve the member expression 'this->S';
14646
Alexey Bataeve3727102018-04-18 15:57:46 +000014647 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014648
Samuel Antao5de996e2016-01-22 20:21:36 +000014649 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14650 // If a list item is an array section, it must specify contiguous storage.
14651 //
14652 // For this restriction it is sufficient that we make sure only references
14653 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014654 // exist except in the rightmost expression (unless they cover the whole
14655 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000014656 //
14657 // r.ArrS[3:5].Arr[6:7]
14658 //
14659 // r.ArrS[3:5].x
14660 //
14661 // but these would be valid:
14662 // r.ArrS[3].Arr[6:7]
14663 //
14664 // r.ArrS[3].x
14665
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014666 bool AllowUnitySizeArraySection = true;
14667 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014668
Dmitry Polukhin644a9252016-03-11 07:58:34 +000014669 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014670 E = E->IgnoreParenImpCasts();
14671
14672 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
14673 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000014674 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014675
14676 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014677
14678 // If we got a reference to a declaration, we should not expect any array
14679 // section before that.
14680 AllowUnitySizeArraySection = false;
14681 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014682
14683 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014684 CurComponents.emplace_back(CurE, CurE->getDecl());
14685 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014686 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000014687
14688 if (isa<CXXThisExpr>(BaseE))
14689 // We found a base expression: this->Val.
14690 RelevantExpr = CurE;
14691 else
14692 E = BaseE;
14693
14694 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014695 if (!NoDiagnose) {
14696 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
14697 << CurE->getSourceRange();
14698 return nullptr;
14699 }
14700 if (RelevantExpr)
14701 return nullptr;
14702 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014703 }
14704
14705 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
14706
14707 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
14708 // A bit-field cannot appear in a map clause.
14709 //
14710 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014711 if (!NoDiagnose) {
14712 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
14713 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
14714 return nullptr;
14715 }
14716 if (RelevantExpr)
14717 return nullptr;
14718 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014719 }
14720
14721 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14722 // If the type of a list item is a reference to a type T then the type
14723 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014724 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014725
14726 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
14727 // A list item cannot be a variable that is a member of a structure with
14728 // a union type.
14729 //
Alexey Bataeve3727102018-04-18 15:57:46 +000014730 if (CurType->isUnionType()) {
14731 if (!NoDiagnose) {
14732 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
14733 << CurE->getSourceRange();
14734 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014735 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014736 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014737 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014738
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014739 // If we got a member expression, we should not expect any array section
14740 // before that:
14741 //
14742 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
14743 // If a list item is an element of a structure, only the rightmost symbol
14744 // of the variable reference can be an array section.
14745 //
14746 AllowUnitySizeArraySection = false;
14747 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014748
14749 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014750 CurComponents.emplace_back(CurE, FD);
14751 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014752 E = CurE->getBase()->IgnoreParenImpCasts();
14753
14754 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014755 if (!NoDiagnose) {
14756 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14757 << 0 << CurE->getSourceRange();
14758 return nullptr;
14759 }
14760 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014761 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014762
14763 // If we got an array subscript that express the whole dimension we
14764 // can have any array expressions before. If it only expressing part of
14765 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000014766 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014767 E->getType()))
14768 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014769
Patrick Lystere13b1e32019-01-02 19:28:48 +000014770 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14771 Expr::EvalResult Result;
14772 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
14773 if (!Result.Val.getInt().isNullValue()) {
14774 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14775 diag::err_omp_invalid_map_this_expr);
14776 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14777 diag::note_omp_invalid_subscript_on_this_ptr_map);
14778 }
14779 }
14780 RelevantExpr = TE;
14781 }
14782
Samuel Antao90927002016-04-26 14:54:23 +000014783 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014784 CurComponents.emplace_back(CurE, nullptr);
14785 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014786 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000014787 E = CurE->getBase()->IgnoreParenImpCasts();
14788
Alexey Bataev27041fa2017-12-05 15:22:49 +000014789 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014790 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14791
Samuel Antao5de996e2016-01-22 20:21:36 +000014792 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14793 // If the type of a list item is a reference to a type T then the type
14794 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000014795 if (CurType->isReferenceType())
14796 CurType = CurType->getPointeeType();
14797
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014798 bool IsPointer = CurType->isAnyPointerType();
14799
14800 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014801 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14802 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014803 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014804 }
14805
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014806 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000014807 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014808 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000014809 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014810
Samuel Antaodab51bb2016-07-18 23:22:11 +000014811 if (AllowWholeSizeArraySection) {
14812 // Any array section is currently allowed. Allowing a whole size array
14813 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014814 //
14815 // If this array section refers to the whole dimension we can still
14816 // accept other array sections before this one, except if the base is a
14817 // pointer. Otherwise, only unitary sections are accepted.
14818 if (NotWhole || IsPointer)
14819 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000014820 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014821 // A unity or whole array section is not allowed and that is not
14822 // compatible with the properties of the current array section.
14823 SemaRef.Diag(
14824 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
14825 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014826 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014827 }
Samuel Antao90927002016-04-26 14:54:23 +000014828
Patrick Lystere13b1e32019-01-02 19:28:48 +000014829 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14830 Expr::EvalResult ResultR;
14831 Expr::EvalResult ResultL;
14832 if (CurE->getLength()->EvaluateAsInt(ResultR,
14833 SemaRef.getASTContext())) {
14834 if (!ResultR.Val.getInt().isOneValue()) {
14835 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14836 diag::err_omp_invalid_map_this_expr);
14837 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14838 diag::note_omp_invalid_length_on_this_ptr_mapping);
14839 }
14840 }
14841 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
14842 ResultL, SemaRef.getASTContext())) {
14843 if (!ResultL.Val.getInt().isNullValue()) {
14844 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14845 diag::err_omp_invalid_map_this_expr);
14846 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14847 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
14848 }
14849 }
14850 RelevantExpr = TE;
14851 }
14852
Samuel Antao90927002016-04-26 14:54:23 +000014853 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014854 CurComponents.emplace_back(CurE, nullptr);
14855 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014856 if (!NoDiagnose) {
14857 // If nothing else worked, this is not a valid map clause expression.
14858 SemaRef.Diag(
14859 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
14860 << ERange;
14861 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000014862 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014863 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014864 }
14865
14866 return RelevantExpr;
14867}
14868
14869// Return true if expression E associated with value VD has conflicts with other
14870// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000014871static bool checkMapConflicts(
14872 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000014873 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000014874 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
14875 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014876 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000014877 SourceLocation ELoc = E->getExprLoc();
14878 SourceRange ERange = E->getSourceRange();
14879
14880 // In order to easily check the conflicts we need to match each component of
14881 // the expression under test with the components of the expressions that are
14882 // already in the stack.
14883
Samuel Antao5de996e2016-01-22 20:21:36 +000014884 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014885 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014886 "Map clause expression with unexpected base!");
14887
14888 // Variables to help detecting enclosing problems in data environment nests.
14889 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000014890 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014891
Samuel Antao90927002016-04-26 14:54:23 +000014892 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
14893 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000014894 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
14895 ERange, CKind, &EnclosingExpr,
14896 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
14897 StackComponents,
14898 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014899 assert(!StackComponents.empty() &&
14900 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014901 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014902 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000014903 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014904
Samuel Antao90927002016-04-26 14:54:23 +000014905 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000014906 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000014907
Samuel Antao5de996e2016-01-22 20:21:36 +000014908 // Expressions must start from the same base. Here we detect at which
14909 // point both expressions diverge from each other and see if we can
14910 // detect if the memory referred to both expressions is contiguous and
14911 // do not overlap.
14912 auto CI = CurComponents.rbegin();
14913 auto CE = CurComponents.rend();
14914 auto SI = StackComponents.rbegin();
14915 auto SE = StackComponents.rend();
14916 for (; CI != CE && SI != SE; ++CI, ++SI) {
14917
14918 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
14919 // At most one list item can be an array item derived from a given
14920 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000014921 if (CurrentRegionOnly &&
14922 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
14923 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
14924 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
14925 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
14926 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000014927 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000014928 << CI->getAssociatedExpression()->getSourceRange();
14929 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
14930 diag::note_used_here)
14931 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000014932 return true;
14933 }
14934
14935 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000014936 if (CI->getAssociatedExpression()->getStmtClass() !=
14937 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000014938 break;
14939
14940 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000014941 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000014942 break;
14943 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000014944 // Check if the extra components of the expressions in the enclosing
14945 // data environment are redundant for the current base declaration.
14946 // If they are, the maps completely overlap, which is legal.
14947 for (; SI != SE; ++SI) {
14948 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000014949 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000014950 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000014951 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014952 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000014953 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014954 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000014955 Type =
14956 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14957 }
14958 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000014959 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000014960 SemaRef, SI->getAssociatedExpression(), Type))
14961 break;
14962 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014963
14964 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14965 // List items of map clauses in the same construct must not share
14966 // original storage.
14967 //
14968 // If the expressions are exactly the same or one is a subset of the
14969 // other, it means they are sharing storage.
14970 if (CI == CE && SI == SE) {
14971 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014972 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000014973 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014974 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014975 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014976 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14977 << ERange;
14978 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014979 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14980 << RE->getSourceRange();
14981 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014982 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014983 // If we find the same expression in the enclosing data environment,
14984 // that is legal.
14985 IsEnclosedByDataEnvironmentExpr = true;
14986 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000014987 }
14988
Samuel Antao90927002016-04-26 14:54:23 +000014989 QualType DerivedType =
14990 std::prev(CI)->getAssociatedDeclaration()->getType();
14991 SourceLocation DerivedLoc =
14992 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000014993
14994 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14995 // If the type of a list item is a reference to a type T then the type
14996 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000014997 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014998
14999 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15000 // A variable for which the type is pointer and an array section
15001 // derived from that variable must not appear as list items of map
15002 // clauses of the same construct.
15003 //
15004 // Also, cover one of the cases in:
15005 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15006 // If any part of the original storage of a list item has corresponding
15007 // storage in the device data environment, all of the original storage
15008 // must have corresponding storage in the device data environment.
15009 //
15010 if (DerivedType->isAnyPointerType()) {
15011 if (CI == CE || SI == SE) {
15012 SemaRef.Diag(
15013 DerivedLoc,
15014 diag::err_omp_pointer_mapped_along_with_derived_section)
15015 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015016 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15017 << RE->getSourceRange();
15018 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015019 }
15020 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015021 SI->getAssociatedExpression()->getStmtClass() ||
15022 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15023 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015024 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015025 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015026 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015027 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15028 << RE->getSourceRange();
15029 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015030 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015031 }
15032
15033 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15034 // List items of map clauses in the same construct must not share
15035 // original storage.
15036 //
15037 // An expression is a subset of the other.
15038 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015039 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015040 if (CI != CE || SI != SE) {
15041 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15042 // a pointer.
15043 auto Begin =
15044 CI != CE ? CurComponents.begin() : StackComponents.begin();
15045 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15046 auto It = Begin;
15047 while (It != End && !It->getAssociatedDeclaration())
15048 std::advance(It, 1);
15049 assert(It != End &&
15050 "Expected at least one component with the declaration.");
15051 if (It != Begin && It->getAssociatedDeclaration()
15052 ->getType()
15053 .getCanonicalType()
15054 ->isAnyPointerType()) {
15055 IsEnclosedByDataEnvironmentExpr = false;
15056 EnclosingExpr = nullptr;
15057 return false;
15058 }
15059 }
Samuel Antao661c0902016-05-26 17:39:58 +000015060 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015061 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015062 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015063 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15064 << ERange;
15065 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015066 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15067 << RE->getSourceRange();
15068 return true;
15069 }
15070
15071 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015072 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015073 if (!CurrentRegionOnly && SI != SE)
15074 EnclosingExpr = RE;
15075
15076 // The current expression is a subset of the expression in the data
15077 // environment.
15078 IsEnclosedByDataEnvironmentExpr |=
15079 (!CurrentRegionOnly && CI != CE && SI == SE);
15080
15081 return false;
15082 });
15083
15084 if (CurrentRegionOnly)
15085 return FoundError;
15086
15087 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15088 // If any part of the original storage of a list item has corresponding
15089 // storage in the device data environment, all of the original storage must
15090 // have corresponding storage in the device data environment.
15091 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15092 // If a list item is an element of a structure, and a different element of
15093 // the structure has a corresponding list item in the device data environment
15094 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015095 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015096 // data environment prior to the task encountering the construct.
15097 //
15098 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15099 SemaRef.Diag(ELoc,
15100 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15101 << ERange;
15102 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15103 << EnclosingExpr->getSourceRange();
15104 return true;
15105 }
15106
15107 return FoundError;
15108}
15109
Michael Kruse4304e9d2019-02-19 16:38:20 +000015110// Look up the user-defined mapper given the mapper name and mapped type, and
15111// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015112static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15113 CXXScopeSpec &MapperIdScopeSpec,
15114 const DeclarationNameInfo &MapperId,
15115 QualType Type,
15116 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015117 if (MapperIdScopeSpec.isInvalid())
15118 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015119 // Get the actual type for the array type.
15120 if (Type->isArrayType()) {
15121 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15122 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15123 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015124 // Find all user-defined mappers with the given MapperId.
15125 SmallVector<UnresolvedSet<8>, 4> Lookups;
15126 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15127 Lookup.suppressDiagnostics();
15128 if (S) {
15129 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15130 NamedDecl *D = Lookup.getRepresentativeDecl();
15131 while (S && !S->isDeclScope(D))
15132 S = S->getParent();
15133 if (S)
15134 S = S->getParent();
15135 Lookups.emplace_back();
15136 Lookups.back().append(Lookup.begin(), Lookup.end());
15137 Lookup.clear();
15138 }
15139 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15140 // Extract the user-defined mappers with the given MapperId.
15141 Lookups.push_back(UnresolvedSet<8>());
15142 for (NamedDecl *D : ULE->decls()) {
15143 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15144 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15145 Lookups.back().addDecl(DMD);
15146 }
15147 }
15148 // Defer the lookup for dependent types. The results will be passed through
15149 // UnresolvedMapper on instantiation.
15150 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15151 Type->isInstantiationDependentType() ||
15152 Type->containsUnexpandedParameterPack() ||
15153 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15154 return !D->isInvalidDecl() &&
15155 (D->getType()->isDependentType() ||
15156 D->getType()->isInstantiationDependentType() ||
15157 D->getType()->containsUnexpandedParameterPack());
15158 })) {
15159 UnresolvedSet<8> URS;
15160 for (const UnresolvedSet<8> &Set : Lookups) {
15161 if (Set.empty())
15162 continue;
15163 URS.append(Set.begin(), Set.end());
15164 }
15165 return UnresolvedLookupExpr::Create(
15166 SemaRef.Context, /*NamingClass=*/nullptr,
15167 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15168 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15169 }
Michael Kruse945249b2019-09-26 22:53:01 +000015170 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015171 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15172 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015173 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15174 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15175 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15176 return ExprError();
15177 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015178 // Perform argument dependent lookup.
15179 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15180 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15181 // Return the first user-defined mapper with the desired type.
15182 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15183 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15184 if (!D->isInvalidDecl() &&
15185 SemaRef.Context.hasSameType(D->getType(), Type))
15186 return D;
15187 return nullptr;
15188 }))
15189 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15190 // Find the first user-defined mapper with a type derived from the desired
15191 // type.
15192 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15193 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15194 if (!D->isInvalidDecl() &&
15195 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15196 !Type.isMoreQualifiedThan(D->getType()))
15197 return D;
15198 return nullptr;
15199 })) {
15200 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15201 /*DetectVirtual=*/false);
15202 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15203 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15204 VD->getType().getUnqualifiedType()))) {
15205 if (SemaRef.CheckBaseClassAccess(
15206 Loc, VD->getType(), Type, Paths.front(),
15207 /*DiagID=*/0) != Sema::AR_inaccessible) {
15208 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15209 }
15210 }
15211 }
15212 }
15213 // Report error if a mapper is specified, but cannot be found.
15214 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15215 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15216 << Type << MapperId.getName();
15217 return ExprError();
15218 }
15219 return ExprEmpty();
15220}
15221
Samuel Antao661c0902016-05-26 17:39:58 +000015222namespace {
15223// Utility struct that gathers all the related lists associated with a mappable
15224// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015225struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015226 // The list of expressions.
15227 ArrayRef<Expr *> VarList;
15228 // The list of processed expressions.
15229 SmallVector<Expr *, 16> ProcessedVarList;
15230 // The mappble components for each expression.
15231 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15232 // The base declaration of the variable.
15233 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015234 // The reference to the user-defined mapper associated with every expression.
15235 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015236
15237 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15238 // We have a list of components and base declarations for each entry in the
15239 // variable list.
15240 VarComponents.reserve(VarList.size());
15241 VarBaseDeclarations.reserve(VarList.size());
15242 }
15243};
15244}
15245
15246// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015247// \a CKind. In the check process the valid expressions, mappable expression
15248// components, variables, and user-defined mappers are extracted and used to
15249// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15250// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15251// and \a MapperId are expected to be valid if the clause kind is 'map'.
15252static void checkMappableExpressionList(
15253 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15254 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015255 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15256 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015257 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015258 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015259 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15260 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015261 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015262
15263 // If the identifier of user-defined mapper is not specified, it is "default".
15264 // We do not change the actual name in this clause to distinguish whether a
15265 // mapper is specified explicitly, i.e., it is not explicitly specified when
15266 // MapperId.getName() is empty.
15267 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15268 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15269 MapperId.setName(DeclNames.getIdentifier(
15270 &SemaRef.getASTContext().Idents.get("default")));
15271 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015272
15273 // Iterators to find the current unresolved mapper expression.
15274 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15275 bool UpdateUMIt = false;
15276 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015277
Samuel Antao90927002016-04-26 14:54:23 +000015278 // Keep track of the mappable components and base declarations in this clause.
15279 // Each entry in the list is going to have a list of components associated. We
15280 // record each set of the components so that we can build the clause later on.
15281 // In the end we should have the same amount of declarations and component
15282 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015283
Alexey Bataeve3727102018-04-18 15:57:46 +000015284 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015285 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015286 SourceLocation ELoc = RE->getExprLoc();
15287
Michael Kruse4304e9d2019-02-19 16:38:20 +000015288 // Find the current unresolved mapper expression.
15289 if (UpdateUMIt && UMIt != UMEnd) {
15290 UMIt++;
15291 assert(
15292 UMIt != UMEnd &&
15293 "Expect the size of UnresolvedMappers to match with that of VarList");
15294 }
15295 UpdateUMIt = true;
15296 if (UMIt != UMEnd)
15297 UnresolvedMapper = *UMIt;
15298
Alexey Bataeve3727102018-04-18 15:57:46 +000015299 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015300
15301 if (VE->isValueDependent() || VE->isTypeDependent() ||
15302 VE->isInstantiationDependent() ||
15303 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000015304 // Try to find the associated user-defined mapper.
15305 ExprResult ER = buildUserDefinedMapperRef(
15306 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15307 VE->getType().getCanonicalType(), UnresolvedMapper);
15308 if (ER.isInvalid())
15309 continue;
15310 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000015311 // We can only analyze this information once the missing information is
15312 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000015313 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015314 continue;
15315 }
15316
Alexey Bataeve3727102018-04-18 15:57:46 +000015317 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015318
Samuel Antao5de996e2016-01-22 20:21:36 +000015319 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000015320 SemaRef.Diag(ELoc,
15321 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000015322 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000015323 continue;
15324 }
15325
Samuel Antao90927002016-04-26 14:54:23 +000015326 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
15327 ValueDecl *CurDeclaration = nullptr;
15328
15329 // Obtain the array or member expression bases if required. Also, fill the
15330 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000015331 const Expr *BE = checkMapClauseExpressionBase(
15332 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000015333 if (!BE)
15334 continue;
15335
Samuel Antao90927002016-04-26 14:54:23 +000015336 assert(!CurComponents.empty() &&
15337 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015338
Patrick Lystere13b1e32019-01-02 19:28:48 +000015339 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
15340 // Add store "this" pointer to class in DSAStackTy for future checking
15341 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000015342 // Try to find the associated user-defined mapper.
15343 ExprResult ER = buildUserDefinedMapperRef(
15344 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15345 VE->getType().getCanonicalType(), UnresolvedMapper);
15346 if (ER.isInvalid())
15347 continue;
15348 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000015349 // Skip restriction checking for variable or field declarations
15350 MVLI.ProcessedVarList.push_back(RE);
15351 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15352 MVLI.VarComponents.back().append(CurComponents.begin(),
15353 CurComponents.end());
15354 MVLI.VarBaseDeclarations.push_back(nullptr);
15355 continue;
15356 }
15357
Samuel Antao90927002016-04-26 14:54:23 +000015358 // For the following checks, we rely on the base declaration which is
15359 // expected to be associated with the last component. The declaration is
15360 // expected to be a variable or a field (if 'this' is being mapped).
15361 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15362 assert(CurDeclaration && "Null decl on map clause.");
15363 assert(
15364 CurDeclaration->isCanonicalDecl() &&
15365 "Expecting components to have associated only canonical declarations.");
15366
15367 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015368 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015369
15370 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015371 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015372
15373 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015374 // threadprivate variables cannot appear in a map clause.
15375 // OpenMP 4.5 [2.10.5, target update Construct]
15376 // threadprivate variables cannot appear in a from clause.
15377 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015378 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015379 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15380 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015381 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015382 continue;
15383 }
15384
Samuel Antao5de996e2016-01-22 20:21:36 +000015385 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15386 // A list item cannot appear in both a map clause and a data-sharing
15387 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015388
Samuel Antao5de996e2016-01-22 20:21:36 +000015389 // Check conflicts with other map clause expressions. We check the conflicts
15390 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015391 // environment, because the restrictions are different. We only have to
15392 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015393 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015394 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015395 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015396 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015397 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015398 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015399 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015400
Samuel Antao661c0902016-05-26 17:39:58 +000015401 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015402 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15403 // If the type of a list item is a reference to a type T then the type will
15404 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015405 auto I = llvm::find_if(
15406 CurComponents,
15407 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15408 return MC.getAssociatedDeclaration();
15409 });
15410 assert(I != CurComponents.end() && "Null decl on map clause.");
15411 QualType Type =
15412 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015413
Samuel Antao661c0902016-05-26 17:39:58 +000015414 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15415 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015416 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015417 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015418 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015419 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015420 continue;
15421
Samuel Antao661c0902016-05-26 17:39:58 +000015422 if (CKind == OMPC_map) {
15423 // target enter data
15424 // OpenMP [2.10.2, Restrictions, p. 99]
15425 // A map-type must be specified in all map clauses and must be either
15426 // to or alloc.
15427 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15428 if (DKind == OMPD_target_enter_data &&
15429 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15430 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15431 << (IsMapTypeImplicit ? 1 : 0)
15432 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15433 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015434 continue;
15435 }
Samuel Antao661c0902016-05-26 17:39:58 +000015436
15437 // target exit_data
15438 // OpenMP [2.10.3, Restrictions, p. 102]
15439 // A map-type must be specified in all map clauses and must be either
15440 // from, release, or delete.
15441 if (DKind == OMPD_target_exit_data &&
15442 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15443 MapType == OMPC_MAP_delete)) {
15444 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15445 << (IsMapTypeImplicit ? 1 : 0)
15446 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15447 << getOpenMPDirectiveName(DKind);
15448 continue;
15449 }
15450
15451 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15452 // A list item cannot appear in both a map clause and a data-sharing
15453 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015454 //
15455 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15456 // A list item cannot appear in both a map clause and a data-sharing
15457 // attribute clause on the same construct unless the construct is a
15458 // combined construct.
15459 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15460 isOpenMPTargetExecutionDirective(DKind)) ||
15461 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015462 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015463 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015464 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015465 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015466 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015467 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015468 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015469 continue;
15470 }
15471 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015472 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015473
Michael Kruse01f670d2019-02-22 22:29:42 +000015474 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015475 ExprResult ER = buildUserDefinedMapperRef(
15476 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15477 Type.getCanonicalType(), UnresolvedMapper);
15478 if (ER.isInvalid())
15479 continue;
15480 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015481
Samuel Antao90927002016-04-26 14:54:23 +000015482 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015483 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015484
15485 // Store the components in the stack so that they can be used to check
15486 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015487 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15488 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015489
15490 // Save the components and declaration to create the clause. For purposes of
15491 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015492 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015493 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15494 MVLI.VarComponents.back().append(CurComponents.begin(),
15495 CurComponents.end());
15496 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15497 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015498 }
Samuel Antao661c0902016-05-26 17:39:58 +000015499}
15500
Michael Kruse4304e9d2019-02-19 16:38:20 +000015501OMPClause *Sema::ActOnOpenMPMapClause(
15502 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15503 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15504 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15505 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15506 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15507 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15508 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15509 OMPC_MAP_MODIFIER_unknown,
15510 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015511 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15512
15513 // Process map-type-modifiers, flag errors for duplicate modifiers.
15514 unsigned Count = 0;
15515 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15516 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15517 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15518 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15519 continue;
15520 }
15521 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015522 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015523 Modifiers[Count] = MapTypeModifiers[I];
15524 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15525 ++Count;
15526 }
15527
Michael Kruse4304e9d2019-02-19 16:38:20 +000015528 MappableVarListInfo MVLI(VarList);
15529 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015530 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15531 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015532
Samuel Antao5de996e2016-01-22 20:21:36 +000015533 // We need to produce a map clause even if we don't have variables so that
15534 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015535 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15536 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15537 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15538 MapperIdScopeSpec.getWithLocInContext(Context),
15539 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015540}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015541
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015542QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15543 TypeResult ParsedType) {
15544 assert(ParsedType.isUsable());
15545
15546 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15547 if (ReductionType.isNull())
15548 return QualType();
15549
15550 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15551 // A type name in a declare reduction directive cannot be a function type, an
15552 // array type, a reference type, or a type qualified with const, volatile or
15553 // restrict.
15554 if (ReductionType.hasQualifiers()) {
15555 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15556 return QualType();
15557 }
15558
15559 if (ReductionType->isFunctionType()) {
15560 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15561 return QualType();
15562 }
15563 if (ReductionType->isReferenceType()) {
15564 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15565 return QualType();
15566 }
15567 if (ReductionType->isArrayType()) {
15568 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15569 return QualType();
15570 }
15571 return ReductionType;
15572}
15573
15574Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15575 Scope *S, DeclContext *DC, DeclarationName Name,
15576 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15577 AccessSpecifier AS, Decl *PrevDeclInScope) {
15578 SmallVector<Decl *, 8> Decls;
15579 Decls.reserve(ReductionTypes.size());
15580
15581 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015582 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015583 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15584 // A reduction-identifier may not be re-declared in the current scope for the
15585 // same type or for a type that is compatible according to the base language
15586 // rules.
15587 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15588 OMPDeclareReductionDecl *PrevDRD = nullptr;
15589 bool InCompoundScope = true;
15590 if (S != nullptr) {
15591 // Find previous declaration with the same name not referenced in other
15592 // declarations.
15593 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15594 InCompoundScope =
15595 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15596 LookupName(Lookup, S);
15597 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15598 /*AllowInlineNamespace=*/false);
15599 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015600 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015601 while (Filter.hasNext()) {
15602 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15603 if (InCompoundScope) {
15604 auto I = UsedAsPrevious.find(PrevDecl);
15605 if (I == UsedAsPrevious.end())
15606 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015607 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015608 UsedAsPrevious[D] = true;
15609 }
15610 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15611 PrevDecl->getLocation();
15612 }
15613 Filter.done();
15614 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015615 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015616 if (!PrevData.second) {
15617 PrevDRD = PrevData.first;
15618 break;
15619 }
15620 }
15621 }
15622 } else if (PrevDeclInScope != nullptr) {
15623 auto *PrevDRDInScope = PrevDRD =
15624 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15625 do {
15626 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15627 PrevDRDInScope->getLocation();
15628 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15629 } while (PrevDRDInScope != nullptr);
15630 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015631 for (const auto &TyData : ReductionTypes) {
15632 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015633 bool Invalid = false;
15634 if (I != PreviousRedeclTypes.end()) {
15635 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15636 << TyData.first;
15637 Diag(I->second, diag::note_previous_definition);
15638 Invalid = true;
15639 }
15640 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15641 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15642 Name, TyData.first, PrevDRD);
15643 DC->addDecl(DRD);
15644 DRD->setAccess(AS);
15645 Decls.push_back(DRD);
15646 if (Invalid)
15647 DRD->setInvalidDecl();
15648 else
15649 PrevDRD = DRD;
15650 }
15651
15652 return DeclGroupPtrTy::make(
15653 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15654}
15655
15656void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15657 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15658
15659 // Enter new function scope.
15660 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015661 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015662 getCurFunction()->setHasOMPDeclareReductionCombiner();
15663
15664 if (S != nullptr)
15665 PushDeclContext(S, DRD);
15666 else
15667 CurContext = DRD;
15668
Faisal Valid143a0c2017-04-01 21:30:49 +000015669 PushExpressionEvaluationContext(
15670 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015671
15672 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015673 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
15674 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
15675 // uses semantics of argument handles by value, but it should be passed by
15676 // reference. C lang does not support references, so pass all parameters as
15677 // pointers.
15678 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015679 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015680 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015681 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
15682 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
15683 // uses semantics of argument handles by value, but it should be passed by
15684 // reference. C lang does not support references, so pass all parameters as
15685 // pointers.
15686 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015687 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015688 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
15689 if (S != nullptr) {
15690 PushOnScopeChains(OmpInParm, S);
15691 PushOnScopeChains(OmpOutParm, S);
15692 } else {
15693 DRD->addDecl(OmpInParm);
15694 DRD->addDecl(OmpOutParm);
15695 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015696 Expr *InE =
15697 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
15698 Expr *OutE =
15699 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
15700 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015701}
15702
15703void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
15704 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15705 DiscardCleanupsInEvaluationContext();
15706 PopExpressionEvaluationContext();
15707
15708 PopDeclContext();
15709 PopFunctionScopeInfo();
15710
15711 if (Combiner != nullptr)
15712 DRD->setCombiner(Combiner);
15713 else
15714 DRD->setInvalidDecl();
15715}
15716
Alexey Bataev070f43a2017-09-06 14:49:58 +000015717VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015718 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15719
15720 // Enter new function scope.
15721 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015722 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015723
15724 if (S != nullptr)
15725 PushDeclContext(S, DRD);
15726 else
15727 CurContext = DRD;
15728
Faisal Valid143a0c2017-04-01 21:30:49 +000015729 PushExpressionEvaluationContext(
15730 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015731
15732 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015733 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
15734 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
15735 // uses semantics of argument handles by value, but it should be passed by
15736 // reference. C lang does not support references, so pass all parameters as
15737 // pointers.
15738 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015739 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015740 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015741 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
15742 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
15743 // uses semantics of argument handles by value, but it should be passed by
15744 // reference. C lang does not support references, so pass all parameters as
15745 // pointers.
15746 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015747 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015748 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015749 if (S != nullptr) {
15750 PushOnScopeChains(OmpPrivParm, S);
15751 PushOnScopeChains(OmpOrigParm, S);
15752 } else {
15753 DRD->addDecl(OmpPrivParm);
15754 DRD->addDecl(OmpOrigParm);
15755 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015756 Expr *OrigE =
15757 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
15758 Expr *PrivE =
15759 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
15760 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000015761 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015762}
15763
Alexey Bataev070f43a2017-09-06 14:49:58 +000015764void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
15765 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015766 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15767 DiscardCleanupsInEvaluationContext();
15768 PopExpressionEvaluationContext();
15769
15770 PopDeclContext();
15771 PopFunctionScopeInfo();
15772
Alexey Bataev070f43a2017-09-06 14:49:58 +000015773 if (Initializer != nullptr) {
15774 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
15775 } else if (OmpPrivParm->hasInit()) {
15776 DRD->setInitializer(OmpPrivParm->getInit(),
15777 OmpPrivParm->isDirectInit()
15778 ? OMPDeclareReductionDecl::DirectInit
15779 : OMPDeclareReductionDecl::CopyInit);
15780 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015781 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000015782 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015783}
15784
15785Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
15786 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015787 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015788 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015789 if (S)
15790 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
15791 /*AddToContext=*/false);
15792 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015793 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000015794 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015795 }
15796 return DeclReductions;
15797}
15798
Michael Kruse251e1482019-02-01 20:25:04 +000015799TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
15800 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15801 QualType T = TInfo->getType();
15802 if (D.isInvalidType())
15803 return true;
15804
15805 if (getLangOpts().CPlusPlus) {
15806 // Check that there are no default arguments (C++ only).
15807 CheckExtraCXXDefaultArguments(D);
15808 }
15809
15810 return CreateParsedType(T, TInfo);
15811}
15812
15813QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
15814 TypeResult ParsedType) {
15815 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
15816
15817 QualType MapperType = GetTypeFromParser(ParsedType.get());
15818 assert(!MapperType.isNull() && "Expect valid mapper type");
15819
15820 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15821 // The type must be of struct, union or class type in C and C++
15822 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
15823 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
15824 return QualType();
15825 }
15826 return MapperType;
15827}
15828
15829OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
15830 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
15831 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
15832 Decl *PrevDeclInScope) {
15833 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
15834 forRedeclarationInCurContext());
15835 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15836 // A mapper-identifier may not be redeclared in the current scope for the
15837 // same type or for a type that is compatible according to the base language
15838 // rules.
15839 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15840 OMPDeclareMapperDecl *PrevDMD = nullptr;
15841 bool InCompoundScope = true;
15842 if (S != nullptr) {
15843 // Find previous declaration with the same name not referenced in other
15844 // declarations.
15845 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15846 InCompoundScope =
15847 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15848 LookupName(Lookup, S);
15849 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15850 /*AllowInlineNamespace=*/false);
15851 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
15852 LookupResult::Filter Filter = Lookup.makeFilter();
15853 while (Filter.hasNext()) {
15854 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
15855 if (InCompoundScope) {
15856 auto I = UsedAsPrevious.find(PrevDecl);
15857 if (I == UsedAsPrevious.end())
15858 UsedAsPrevious[PrevDecl] = false;
15859 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
15860 UsedAsPrevious[D] = true;
15861 }
15862 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15863 PrevDecl->getLocation();
15864 }
15865 Filter.done();
15866 if (InCompoundScope) {
15867 for (const auto &PrevData : UsedAsPrevious) {
15868 if (!PrevData.second) {
15869 PrevDMD = PrevData.first;
15870 break;
15871 }
15872 }
15873 }
15874 } else if (PrevDeclInScope) {
15875 auto *PrevDMDInScope = PrevDMD =
15876 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
15877 do {
15878 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
15879 PrevDMDInScope->getLocation();
15880 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
15881 } while (PrevDMDInScope != nullptr);
15882 }
15883 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
15884 bool Invalid = false;
15885 if (I != PreviousRedeclTypes.end()) {
15886 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
15887 << MapperType << Name;
15888 Diag(I->second, diag::note_previous_definition);
15889 Invalid = true;
15890 }
15891 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
15892 MapperType, VN, PrevDMD);
15893 DC->addDecl(DMD);
15894 DMD->setAccess(AS);
15895 if (Invalid)
15896 DMD->setInvalidDecl();
15897
15898 // Enter new function scope.
15899 PushFunctionScope();
15900 setFunctionHasBranchProtectedScope();
15901
15902 CurContext = DMD;
15903
15904 return DMD;
15905}
15906
15907void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
15908 Scope *S,
15909 QualType MapperType,
15910 SourceLocation StartLoc,
15911 DeclarationName VN) {
15912 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
15913 if (S)
15914 PushOnScopeChains(VD, S);
15915 else
15916 DMD->addDecl(VD);
15917 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
15918 DMD->setMapperVarRef(MapperVarRefExpr);
15919}
15920
15921Sema::DeclGroupPtrTy
15922Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
15923 ArrayRef<OMPClause *> ClauseList) {
15924 PopDeclContext();
15925 PopFunctionScopeInfo();
15926
15927 if (D) {
15928 if (S)
15929 PushOnScopeChains(D, S, /*AddToContext=*/false);
15930 D->CreateClauses(Context, ClauseList);
15931 }
15932
15933 return DeclGroupPtrTy::make(DeclGroupRef(D));
15934}
15935
David Majnemer9d168222016-08-05 17:44:54 +000015936OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000015937 SourceLocation StartLoc,
15938 SourceLocation LParenLoc,
15939 SourceLocation EndLoc) {
15940 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015941 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015942
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015943 // OpenMP [teams Constrcut, Restrictions]
15944 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015945 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000015946 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015947 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015948
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015949 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015950 OpenMPDirectiveKind CaptureRegion =
15951 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
15952 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015953 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015954 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015955 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15956 HelperValStmt = buildPreInits(Context, Captures);
15957 }
15958
15959 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
15960 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000015961}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015962
15963OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
15964 SourceLocation StartLoc,
15965 SourceLocation LParenLoc,
15966 SourceLocation EndLoc) {
15967 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015968 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015969
15970 // OpenMP [teams Constrcut, Restrictions]
15971 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015972 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000015973 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015974 return nullptr;
15975
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015976 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015977 OpenMPDirectiveKind CaptureRegion =
15978 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
15979 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015980 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015981 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015982 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15983 HelperValStmt = buildPreInits(Context, Captures);
15984 }
15985
15986 return new (Context) OMPThreadLimitClause(
15987 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015988}
Alexey Bataeva0569352015-12-01 10:17:31 +000015989
15990OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
15991 SourceLocation StartLoc,
15992 SourceLocation LParenLoc,
15993 SourceLocation EndLoc) {
15994 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000015995 Stmt *HelperValStmt = nullptr;
15996 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000015997
15998 // OpenMP [2.9.1, task Constrcut]
15999 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016000 if (!isNonNegativeIntegerValue(
16001 ValExpr, *this, OMPC_priority,
16002 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16003 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016004 return nullptr;
16005
Alexey Bataev31ba4762019-10-16 18:09:37 +000016006 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16007 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016008}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016009
16010OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16011 SourceLocation StartLoc,
16012 SourceLocation LParenLoc,
16013 SourceLocation EndLoc) {
16014 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016015 Stmt *HelperValStmt = nullptr;
16016 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016017
16018 // OpenMP [2.9.2, taskloop Constrcut]
16019 // The parameter of the grainsize clause must be a positive integer
16020 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016021 if (!isNonNegativeIntegerValue(
16022 ValExpr, *this, OMPC_grainsize,
16023 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16024 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016025 return nullptr;
16026
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016027 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16028 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016029}
Alexey Bataev382967a2015-12-08 12:06:20 +000016030
16031OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16032 SourceLocation StartLoc,
16033 SourceLocation LParenLoc,
16034 SourceLocation EndLoc) {
16035 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016036 Stmt *HelperValStmt = nullptr;
16037 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016038
16039 // OpenMP [2.9.2, taskloop Constrcut]
16040 // The parameter of the num_tasks clause must be a positive integer
16041 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016042 if (!isNonNegativeIntegerValue(
16043 ValExpr, *this, OMPC_num_tasks,
16044 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16045 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016046 return nullptr;
16047
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016048 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16049 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016050}
16051
Alexey Bataev28c75412015-12-15 08:19:24 +000016052OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16053 SourceLocation LParenLoc,
16054 SourceLocation EndLoc) {
16055 // OpenMP [2.13.2, critical construct, Description]
16056 // ... where hint-expression is an integer constant expression that evaluates
16057 // to a valid lock hint.
16058 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16059 if (HintExpr.isInvalid())
16060 return nullptr;
16061 return new (Context)
16062 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16063}
16064
Carlo Bertollib4adf552016-01-15 18:50:31 +000016065OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16066 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16067 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16068 SourceLocation EndLoc) {
16069 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16070 std::string Values;
16071 Values += "'";
16072 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16073 Values += "'";
16074 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16075 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16076 return nullptr;
16077 }
16078 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016079 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016080 if (ChunkSize) {
16081 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16082 !ChunkSize->isInstantiationDependent() &&
16083 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016084 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016085 ExprResult Val =
16086 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16087 if (Val.isInvalid())
16088 return nullptr;
16089
16090 ValExpr = Val.get();
16091
16092 // OpenMP [2.7.1, Restrictions]
16093 // chunk_size must be a loop invariant integer expression with a positive
16094 // value.
16095 llvm::APSInt Result;
16096 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16097 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16098 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16099 << "dist_schedule" << ChunkSize->getSourceRange();
16100 return nullptr;
16101 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016102 } else if (getOpenMPCaptureRegionForClause(
16103 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
16104 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016105 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016106 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016107 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016108 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16109 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016110 }
16111 }
16112 }
16113
16114 return new (Context)
16115 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016116 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016117}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016118
16119OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16120 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16121 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16122 SourceLocation KindLoc, SourceLocation EndLoc) {
16123 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000016124 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016125 std::string Value;
16126 SourceLocation Loc;
16127 Value += "'";
16128 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16129 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000016130 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016131 Loc = MLoc;
16132 } else {
16133 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000016134 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016135 Loc = KindLoc;
16136 }
16137 Value += "'";
16138 Diag(Loc, diag::err_omp_unexpected_clause_value)
16139 << Value << getOpenMPClauseName(OMPC_defaultmap);
16140 return nullptr;
16141 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000016142 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016143
16144 return new (Context)
16145 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16146}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016147
16148bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16149 DeclContext *CurLexicalContext = getCurLexicalContext();
16150 if (!CurLexicalContext->isFileContext() &&
16151 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016152 !CurLexicalContext->isExternCXXContext() &&
16153 !isa<CXXRecordDecl>(CurLexicalContext) &&
16154 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16155 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16156 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016157 Diag(Loc, diag::err_omp_region_not_file_context);
16158 return false;
16159 }
Kelvin Libc38e632018-09-10 02:07:09 +000016160 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016161 return true;
16162}
16163
16164void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016165 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016166 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016167 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016168}
16169
Alexey Bataev729e2422019-08-23 16:11:14 +000016170NamedDecl *
16171Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16172 const DeclarationNameInfo &Id,
16173 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016174 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16175 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16176
16177 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016178 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016179 Lookup.suppressDiagnostics();
16180
16181 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016182 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016183 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016184 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016185 CTK_ErrorRecovery)) {
16186 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16187 << Id.getName());
16188 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016189 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016190 }
16191
16192 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016193 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016194 }
16195
16196 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016197 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16198 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016199 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016200 return nullptr;
16201 }
16202 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16203 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16204 return ND;
16205}
16206
16207void Sema::ActOnOpenMPDeclareTargetName(
16208 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16209 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16210 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16211 isa<FunctionTemplateDecl>(ND)) &&
16212 "Expected variable, function or function template.");
16213
16214 // Diagnose marking after use as it may lead to incorrect diagnosis and
16215 // codegen.
16216 if (LangOpts.OpenMP >= 50 &&
16217 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16218 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16219
16220 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16221 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16222 if (DevTy.hasValue() && *DevTy != DT) {
16223 Diag(Loc, diag::err_omp_device_type_mismatch)
16224 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16225 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16226 return;
16227 }
16228 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16229 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16230 if (!Res) {
16231 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16232 SourceRange(Loc, Loc));
16233 ND->addAttr(A);
16234 if (ASTMutationListener *ML = Context.getASTMutationListener())
16235 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16236 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16237 } else if (*Res != MT) {
16238 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016239 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016240}
16241
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016242static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16243 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016244 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016245 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016246 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016247 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16248 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16249 if (SemaRef.LangOpts.OpenMP >= 50 &&
16250 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16251 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16252 VD->hasGlobalStorage()) {
16253 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16254 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16255 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
16256 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
16257 // If a lambda declaration and definition appears between a
16258 // declare target directive and the matching end declare target
16259 // directive, all variables that are captured by the lambda
16260 // expression must also appear in a to clause.
16261 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000016262 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016263 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
16264 << VD << 0 << SR;
16265 return;
16266 }
16267 }
16268 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000016269 return;
16270 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
16271 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016272}
16273
16274static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
16275 Sema &SemaRef, DSAStackTy *Stack,
16276 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000016277 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000016278 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
16279 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016280}
16281
Kelvin Li1ce87c72017-12-12 20:08:12 +000016282void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
16283 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016284 if (!D || D->isInvalidDecl())
16285 return;
16286 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016287 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000016288 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000016289 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000016290 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
16291 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000016292 return;
16293 // 2.10.6: threadprivate variable cannot appear in a declare target
16294 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016295 if (DSAStack->isThreadPrivate(VD)) {
16296 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000016297 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016298 return;
16299 }
16300 }
Alexey Bataev97b72212018-08-14 18:31:20 +000016301 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
16302 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016303 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016304 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16305 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016306 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000016307 Diag(IdLoc, diag::err_omp_function_in_link_clause);
16308 Diag(FD->getLocation(), diag::note_defined_here) << FD;
16309 return;
16310 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016311 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000016312 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16313 OMPDeclareTargetDeclAttr::getDeviceType(FD);
16314 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16315 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000016316 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000016317 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
16318 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
16319 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000016320 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016321 if (auto *VD = dyn_cast<ValueDecl>(D)) {
16322 // Problem if any with var declared with incomplete type will be reported
16323 // as normal, so no need to check it here.
16324 if ((E || !VD->getType()->isIncompleteType()) &&
16325 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
16326 return;
16327 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
16328 // Checking declaration inside declare target region.
16329 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
16330 isa<FunctionTemplateDecl>(D)) {
16331 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000016332 Context, OMPDeclareTargetDeclAttr::MT_To,
16333 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000016334 D->addAttr(A);
16335 if (ASTMutationListener *ML = Context.getASTMutationListener())
16336 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
16337 }
16338 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016339 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016340 }
Alexey Bataev30a78212018-09-11 13:59:10 +000016341 if (!E)
16342 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016343 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
16344}
Samuel Antao661c0902016-05-26 17:39:58 +000016345
16346OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000016347 CXXScopeSpec &MapperIdScopeSpec,
16348 DeclarationNameInfo &MapperId,
16349 const OMPVarListLocTy &Locs,
16350 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000016351 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016352 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
16353 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000016354 if (MVLI.ProcessedVarList.empty())
16355 return nullptr;
16356
Michael Kruse01f670d2019-02-22 22:29:42 +000016357 return OMPToClause::Create(
16358 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16359 MVLI.VarComponents, MVLI.UDMapperList,
16360 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000016361}
Samuel Antaoec172c62016-05-26 17:49:04 +000016362
16363OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000016364 CXXScopeSpec &MapperIdScopeSpec,
16365 DeclarationNameInfo &MapperId,
16366 const OMPVarListLocTy &Locs,
16367 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000016368 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000016369 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
16370 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000016371 if (MVLI.ProcessedVarList.empty())
16372 return nullptr;
16373
Michael Kruse0336c752019-02-25 20:34:15 +000016374 return OMPFromClause::Create(
16375 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
16376 MVLI.VarComponents, MVLI.UDMapperList,
16377 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016378}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016379
16380OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016381 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016382 MappableVarListInfo MVLI(VarList);
16383 SmallVector<Expr *, 8> PrivateCopies;
16384 SmallVector<Expr *, 8> Inits;
16385
Alexey Bataeve3727102018-04-18 15:57:46 +000016386 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016387 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16388 SourceLocation ELoc;
16389 SourceRange ERange;
16390 Expr *SimpleRefExpr = RefExpr;
16391 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16392 if (Res.second) {
16393 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016394 MVLI.ProcessedVarList.push_back(RefExpr);
16395 PrivateCopies.push_back(nullptr);
16396 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016397 }
16398 ValueDecl *D = Res.first;
16399 if (!D)
16400 continue;
16401
16402 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016403 Type = Type.getNonReferenceType().getUnqualifiedType();
16404
16405 auto *VD = dyn_cast<VarDecl>(D);
16406
16407 // Item should be a pointer or reference to pointer.
16408 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016409 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16410 << 0 << RefExpr->getSourceRange();
16411 continue;
16412 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016413
16414 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016415 auto VDPrivate =
16416 buildVarDecl(*this, ELoc, Type, D->getName(),
16417 D->hasAttrs() ? &D->getAttrs() : nullptr,
16418 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016419 if (VDPrivate->isInvalidDecl())
16420 continue;
16421
16422 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016423 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016424 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16425
16426 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016427 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016428 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016429 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16430 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016431 AddInitializerToDecl(VDPrivate,
16432 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016433 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016434
16435 // If required, build a capture to implement the privatization initialized
16436 // with the current list item value.
16437 DeclRefExpr *Ref = nullptr;
16438 if (!VD)
16439 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16440 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16441 PrivateCopies.push_back(VDPrivateRefExpr);
16442 Inits.push_back(VDInitRefExpr);
16443
16444 // We need to add a data sharing attribute for this variable to make sure it
16445 // is correctly captured. A variable that shows up in a use_device_ptr has
16446 // similar properties of a first private variable.
16447 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16448
16449 // Create a mappable component for the list item. List items in this clause
16450 // only need a component.
16451 MVLI.VarBaseDeclarations.push_back(D);
16452 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16453 MVLI.VarComponents.back().push_back(
16454 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016455 }
16456
Samuel Antaocc10b852016-07-28 14:23:26 +000016457 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016458 return nullptr;
16459
Samuel Antaocc10b852016-07-28 14:23:26 +000016460 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016461 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16462 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016463}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016464
16465OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016466 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016467 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016468 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016469 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016470 SourceLocation ELoc;
16471 SourceRange ERange;
16472 Expr *SimpleRefExpr = RefExpr;
16473 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16474 if (Res.second) {
16475 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016476 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016477 }
16478 ValueDecl *D = Res.first;
16479 if (!D)
16480 continue;
16481
16482 QualType Type = D->getType();
16483 // item should be a pointer or array or reference to pointer or array
16484 if (!Type.getNonReferenceType()->isPointerType() &&
16485 !Type.getNonReferenceType()->isArrayType()) {
16486 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16487 << 0 << RefExpr->getSourceRange();
16488 continue;
16489 }
Samuel Antao6890b092016-07-28 14:25:09 +000016490
16491 // Check if the declaration in the clause does not show up in any data
16492 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016493 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016494 if (isOpenMPPrivate(DVar.CKind)) {
16495 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16496 << getOpenMPClauseName(DVar.CKind)
16497 << getOpenMPClauseName(OMPC_is_device_ptr)
16498 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016499 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016500 continue;
16501 }
16502
Alexey Bataeve3727102018-04-18 15:57:46 +000016503 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016504 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016505 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016506 [&ConflictExpr](
16507 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16508 OpenMPClauseKind) -> bool {
16509 ConflictExpr = R.front().getAssociatedExpression();
16510 return true;
16511 })) {
16512 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16513 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16514 << ConflictExpr->getSourceRange();
16515 continue;
16516 }
16517
16518 // Store the components in the stack so that they can be used to check
16519 // against other clauses later on.
16520 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16521 DSAStack->addMappableExpressionComponents(
16522 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16523
16524 // Record the expression we've just processed.
16525 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16526
16527 // Create a mappable component for the list item. List items in this clause
16528 // only need a component. We use a null declaration to signal fields in
16529 // 'this'.
16530 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16531 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16532 "Unexpected device pointer expression!");
16533 MVLI.VarBaseDeclarations.push_back(
16534 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16535 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16536 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016537 }
16538
Samuel Antao6890b092016-07-28 14:25:09 +000016539 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016540 return nullptr;
16541
Michael Kruse4304e9d2019-02-19 16:38:20 +000016542 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16543 MVLI.VarBaseDeclarations,
16544 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016545}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016546
16547OMPClause *Sema::ActOnOpenMPAllocateClause(
16548 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16549 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16550 if (Allocator) {
16551 // OpenMP [2.11.4 allocate Clause, Description]
16552 // allocator is an expression of omp_allocator_handle_t type.
16553 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16554 return nullptr;
16555
16556 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16557 if (AllocatorRes.isInvalid())
16558 return nullptr;
16559 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16560 DSAStack->getOMPAllocatorHandleT(),
16561 Sema::AA_Initializing,
16562 /*AllowExplicit=*/true);
16563 if (AllocatorRes.isInvalid())
16564 return nullptr;
16565 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016566 } else {
16567 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16568 // allocate clauses that appear on a target construct or on constructs in a
16569 // target region must specify an allocator expression unless a requires
16570 // directive with the dynamic_allocators clause is present in the same
16571 // compilation unit.
16572 if (LangOpts.OpenMPIsDevice &&
16573 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16574 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016575 }
16576 // Analyze and build list of variables.
16577 SmallVector<Expr *, 8> Vars;
16578 for (Expr *RefExpr : VarList) {
16579 assert(RefExpr && "NULL expr in OpenMP private clause.");
16580 SourceLocation ELoc;
16581 SourceRange ERange;
16582 Expr *SimpleRefExpr = RefExpr;
16583 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16584 if (Res.second) {
16585 // It will be analyzed later.
16586 Vars.push_back(RefExpr);
16587 }
16588 ValueDecl *D = Res.first;
16589 if (!D)
16590 continue;
16591
16592 auto *VD = dyn_cast<VarDecl>(D);
16593 DeclRefExpr *Ref = nullptr;
16594 if (!VD && !CurContext->isDependentContext())
16595 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16596 Vars.push_back((VD || CurContext->isDependentContext())
16597 ? RefExpr->IgnoreParens()
16598 : Ref);
16599 }
16600
16601 if (Vars.empty())
16602 return nullptr;
16603
16604 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16605 ColonLoc, EndLoc, Vars);
16606}