blob: 6e2a34447a4d7a292705e1678fffc0e3d2dfe991 [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000142 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000143 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000144 bool NowaitRegion = false;
145 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000146 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000147 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000148 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000149 /// Reference to the taskgroup task_reduction reference expression.
150 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000151 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000152 /// List of globals marked as declare target link in this target region
153 /// (isOpenMPTargetExecutionDirective(Directive) == true).
154 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000155 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000156 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000157 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
158 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000159 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000160 };
161
Alexey Bataeve3727102018-04-18 15:57:46 +0000162 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000164 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000165 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000166 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
167 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000168 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000169 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000171 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000172 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000173 /// true if all the vaiables in the target executable directives must be
174 /// captured by reference.
175 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000176 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000177 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000178
Richard Smith375dec52019-05-30 23:21:14 +0000179 /// Iterators over the stack iterate in order from innermost to outermost
180 /// directive.
181 using const_iterator = StackTy::const_reverse_iterator;
182 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000183 return Stack.empty() ? const_iterator()
184 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000185 }
186 const_iterator end() const {
187 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
188 }
189 using iterator = StackTy::reverse_iterator;
190 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000191 return Stack.empty() ? iterator()
192 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000193 }
194 iterator end() {
195 return Stack.empty() ? iterator() : Stack.back().first.rend();
196 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197
Richard Smith375dec52019-05-30 23:21:14 +0000198 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000199
Alexey Bataev4b465392017-04-26 15:06:24 +0000200 bool isStackEmpty() const {
201 return Stack.empty() ||
202 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000203 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000204 }
Richard Smith375dec52019-05-30 23:21:14 +0000205 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000206 return isStackEmpty() ? 0
207 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000208 }
209
210 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000211 size_t Size = getStackSize();
212 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000213 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000214 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000215 }
216 const SharingMapTy *getTopOfStackOrNull() const {
217 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
218 }
219 SharingMapTy &getTopOfStack() {
220 assert(!isStackEmpty() && "no current directive");
221 return *getTopOfStackOrNull();
222 }
223 const SharingMapTy &getTopOfStack() const {
224 return const_cast<DSAStackTy&>(*this).getTopOfStack();
225 }
226
227 SharingMapTy *getSecondOnStackOrNull() {
228 size_t Size = getStackSize();
229 if (Size <= 1)
230 return nullptr;
231 return &Stack.back().first[Size - 2];
232 }
233 const SharingMapTy *getSecondOnStackOrNull() const {
234 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
235 }
236
237 /// Get the stack element at a certain level (previously returned by
238 /// \c getNestingLevel).
239 ///
240 /// Note that nesting levels count from outermost to innermost, and this is
241 /// the reverse of our iteration order where new inner levels are pushed at
242 /// the front of the stack.
243 SharingMapTy &getStackElemAtLevel(unsigned Level) {
244 assert(Level < getStackSize() && "no such stack element");
245 return Stack.back().first[Level];
246 }
247 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
248 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
249 }
250
251 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
252
253 /// Checks if the variable is a local for OpenMP region.
254 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000255
Kelvin Li1408f912018-09-26 04:28:39 +0000256 /// Vector of previously declared requires directives
257 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000258 /// omp_allocator_handle_t type.
259 QualType OMPAllocatorHandleT;
260 /// Expression for the predefined allocators.
261 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
262 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000263 /// Vector of previously encountered target directives
264 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000265
Alexey Bataev758e55e2013-09-06 18:03:48 +0000266public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000267 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000268
Alexey Bataev27ef9512019-03-20 20:14:22 +0000269 /// Sets omp_allocator_handle_t type.
270 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
271 /// Gets omp_allocator_handle_t type.
272 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
273 /// Sets the given default allocator.
274 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
275 Expr *Allocator) {
276 OMPPredefinedAllocators[AllocatorKind] = Allocator;
277 }
278 /// Returns the specified default allocator.
279 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
280 return OMPPredefinedAllocators[AllocatorKind];
281 }
282
Alexey Bataevaac108a2015-06-23 04:51:00 +0000283 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000284 OpenMPClauseKind getClauseParsingMode() const {
285 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
286 return ClauseKindMode;
287 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000288 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000289
Richard Smith0621a8f2019-05-31 00:45:10 +0000290 bool isBodyComplete() const {
291 const SharingMapTy *Top = getTopOfStackOrNull();
292 return Top && Top->BodyComplete;
293 }
294 void setBodyComplete() {
295 getTopOfStack().BodyComplete = true;
296 }
297
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000298 bool isForceVarCapturing() const { return ForceCapturing; }
299 void setForceVarCapturing(bool V) { ForceCapturing = V; }
300
Alexey Bataev60705422018-10-30 15:50:12 +0000301 void setForceCaptureByReferenceInTargetExecutable(bool V) {
302 ForceCaptureByReferenceInTargetExecutable = V;
303 }
304 bool isForceCaptureByReferenceInTargetExecutable() const {
305 return ForceCaptureByReferenceInTargetExecutable;
306 }
307
Alexey Bataev758e55e2013-09-06 18:03:48 +0000308 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000309 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000310 assert(!IgnoredStackElements &&
311 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000312 if (Stack.empty() ||
313 Stack.back().second != CurrentNonCapturingFunctionScope)
314 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
315 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
316 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000317 }
318
319 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000320 assert(!IgnoredStackElements &&
321 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000322 assert(!Stack.back().first.empty() &&
323 "Data-sharing attributes stack is empty!");
324 Stack.back().first.pop_back();
325 }
326
Richard Smith0621a8f2019-05-31 00:45:10 +0000327 /// RAII object to temporarily leave the scope of a directive when we want to
328 /// logically operate in its parent.
329 class ParentDirectiveScope {
330 DSAStackTy &Self;
331 bool Active;
332 public:
333 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
334 : Self(Self), Active(false) {
335 if (Activate)
336 enable();
337 }
338 ~ParentDirectiveScope() { disable(); }
339 void disable() {
340 if (Active) {
341 --Self.IgnoredStackElements;
342 Active = false;
343 }
344 }
345 void enable() {
346 if (!Active) {
347 ++Self.IgnoredStackElements;
348 Active = true;
349 }
350 }
351 };
352
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000353 /// Marks that we're started loop parsing.
354 void loopInit() {
355 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
356 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000357 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000358 }
359 /// Start capturing of the variables in the loop context.
360 void loopStart() {
361 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
362 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000363 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000364 }
365 /// true, if variables are captured, false otherwise.
366 bool isLoopStarted() const {
367 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
368 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000369 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000370 }
371 /// Marks (or clears) declaration as possibly loop counter.
372 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000373 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000374 D ? D->getCanonicalDecl() : D;
375 }
376 /// Gets the possible loop counter decl.
377 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000378 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000379 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000380 /// Start new OpenMP region stack in new non-capturing function.
381 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000382 assert(!IgnoredStackElements &&
383 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
385 assert(!isa<CapturingScopeInfo>(CurFnScope));
386 CurrentNonCapturingFunctionScope = CurFnScope;
387 }
388 /// Pop region stack for non-capturing function.
389 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000390 assert(!IgnoredStackElements &&
391 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000392 if (!Stack.empty() && Stack.back().second == OldFSI) {
393 assert(Stack.back().first.empty());
394 Stack.pop_back();
395 }
396 CurrentNonCapturingFunctionScope = nullptr;
397 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
398 if (!isa<CapturingScopeInfo>(FSI)) {
399 CurrentNonCapturingFunctionScope = FSI;
400 break;
401 }
402 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000403 }
404
Alexey Bataeve3727102018-04-18 15:57:46 +0000405 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000406 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000407 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000408 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000409 getCriticalWithHint(const DeclarationNameInfo &Name) const {
410 auto I = Criticals.find(Name.getAsString());
411 if (I != Criticals.end())
412 return I->second;
413 return std::make_pair(nullptr, llvm::APSInt());
414 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000416 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000417 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000418 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000419
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000420 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000421 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000423 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000424 /// \return The index of the loop control variable in the list of associated
425 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000426 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000427 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000428 /// parent region.
429 /// \return The index of the loop control variable in the list of associated
430 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000431 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000432 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000433 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000434 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000435
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000436 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000437 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000438 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000439
Alexey Bataevfa312f32017-07-21 18:48:21 +0000440 /// Adds additional information for the reduction items with the reduction id
441 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000442 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000443 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000444 /// Adds additional information for the reduction items with the reduction id
445 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000446 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000447 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000448 /// Returns the location and reduction operation from the innermost parent
449 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000450 const DSAVarData
451 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
452 BinaryOperatorKind &BOK,
453 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000454 /// Returns the location and reduction operation from the innermost parent
455 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000456 const DSAVarData
457 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
458 const Expr *&ReductionRef,
459 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000460 /// Return reduction reference expression for the current taskgroup.
461 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000462 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000463 "taskgroup reference expression requested for non taskgroup "
464 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000465 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000466 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000467 /// Checks if the given \p VD declaration is actually a taskgroup reduction
468 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000469 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000470 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
471 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000472 ->getDecl() == VD;
473 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000474
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000475 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000476 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000477 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000478 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000479 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000480 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000481 /// match specified \a CPred predicate in any directive which matches \a DPred
482 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000483 const DSAVarData
484 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
485 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
486 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000487 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000488 /// match specified \a CPred predicate in any innermost directive which
489 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000490 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000491 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000492 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
493 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000494 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000495 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000496 /// attributes which match specified \a CPred predicate at the specified
497 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000498 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000499 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000500 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000502 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000503 /// specified \a DPred predicate.
504 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000505 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000506 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000509 bool hasDirective(
510 const llvm::function_ref<bool(
511 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
512 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000513 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000516 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000517 const SharingMapTy *Top = getTopOfStackOrNull();
518 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000521 OpenMPDirectiveKind getDirective(unsigned Level) const {
522 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000523 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000524 }
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 Bataev13314bf2014-10-09 04:18:56 +0000969 if (isOpenMPParallelDirective(DVar.DKind) ||
970 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000971 DVar.CKind = OMPC_shared;
972 return DVar;
973 }
974
975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
976 // in a Construct, implicitly determined, p.4]
977 // In a task construct, if no default clause is present, a variable that in
978 // the enclosing context is determined to be shared by all implicit tasks
979 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000980 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000981 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +0000982 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000983 do {
984 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000985 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000986 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000987 // In a task construct, if no default clause is present, a variable
988 // whose data-sharing attribute is not determined by the rules above is
989 // firstprivate.
990 DVarTemp = getDSA(I, D);
991 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000992 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000993 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000994 return DVar;
995 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000996 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000997 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000998 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000999 return DVar;
1000 }
1001 }
1002 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1003 // in a Construct, implicitly determined, p.3]
1004 // For constructs other than task, if no default clause is present, these
1005 // variables inherit their data-sharing attributes from the enclosing
1006 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001007 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001008}
1009
Alexey Bataeve3727102018-04-18 15:57:46 +00001010const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1011 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001012 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001013 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001014 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001015 auto It = StackElem.AlignedMap.find(D);
1016 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001017 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001018 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001019 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001020 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001021 assert(It->second && "Unexpected nullptr expr in the aligned map");
1022 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001023}
1024
Alexey Bataeve3727102018-04-18 15:57:46 +00001025void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001026 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001027 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001028 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001029 StackElem.LCVMap.try_emplace(
1030 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001031}
1032
Alexey Bataeve3727102018-04-18 15:57:46 +00001033const DSAStackTy::LCDeclInfo
1034DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001035 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001036 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001037 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001038 auto It = StackElem.LCVMap.find(D);
1039 if (It != StackElem.LCVMap.end())
1040 return It->second;
1041 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001042}
1043
Alexey Bataeve3727102018-04-18 15:57:46 +00001044const DSAStackTy::LCDeclInfo
1045DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001046 const SharingMapTy *Parent = getSecondOnStackOrNull();
1047 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001048 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001049 auto It = Parent->LCVMap.find(D);
1050 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001051 return It->second;
1052 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001053}
1054
Alexey Bataeve3727102018-04-18 15:57:46 +00001055const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001056 const SharingMapTy *Parent = getSecondOnStackOrNull();
1057 assert(Parent && "Data-sharing attributes stack is empty");
1058 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001059 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001060 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001061 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001062 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001063 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001064}
1065
Alexey Bataeve3727102018-04-18 15:57:46 +00001066void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001067 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001068 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001069 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001070 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001071 Data.Attributes = A;
1072 Data.RefExpr.setPointer(E);
1073 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001074 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001075 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001076 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1077 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1078 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1079 (isLoopControlVariable(D).first && A == OMPC_private));
1080 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1081 Data.RefExpr.setInt(/*IntVal=*/true);
1082 return;
1083 }
1084 const bool IsLastprivate =
1085 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1086 Data.Attributes = A;
1087 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1088 Data.PrivateCopy = PrivateCopy;
1089 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001090 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001091 Data.Attributes = A;
1092 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1093 Data.PrivateCopy = nullptr;
1094 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001095 }
1096}
1097
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001098/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001099static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001100 StringRef Name, const AttrVec *Attrs = nullptr,
1101 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001102 DeclContext *DC = SemaRef.CurContext;
1103 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1104 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001105 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001106 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1107 if (Attrs) {
1108 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1109 I != E; ++I)
1110 Decl->addAttr(*I);
1111 }
1112 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001113 if (OrigRef) {
1114 Decl->addAttr(
1115 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1116 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001117 return Decl;
1118}
1119
1120static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1121 SourceLocation Loc,
1122 bool RefersToCapture = false) {
1123 D->setReferenced();
1124 D->markUsed(S.Context);
1125 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1126 SourceLocation(), D, RefersToCapture, Loc, Ty,
1127 VK_LValue);
1128}
1129
Alexey Bataeve3727102018-04-18 15:57:46 +00001130void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001131 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001132 D = getCanonicalDecl(D);
1133 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001134 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001135 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001136 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001137 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001138 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001139 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001140 "Additional reduction info may be specified only once for reduction "
1141 "items.");
1142 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001143 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001144 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001145 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001146 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1147 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001148 TaskgroupReductionRef =
1149 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001150 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001151}
1152
Alexey Bataeve3727102018-04-18 15:57:46 +00001153void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001154 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001155 D = getCanonicalDecl(D);
1156 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001157 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001158 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001159 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001160 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001161 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001162 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001163 "Additional reduction info may be specified only once for reduction "
1164 "items.");
1165 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001166 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001167 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001168 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001169 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1170 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001171 TaskgroupReductionRef =
1172 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001173 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001174}
1175
Alexey Bataeve3727102018-04-18 15:57:46 +00001176const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1177 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1178 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001179 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001180 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001181 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001182 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001183 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001184 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001185 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001186 if (!ReductionData.ReductionOp ||
1187 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001188 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001189 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001190 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001191 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1192 "expression for the descriptor is not "
1193 "set.");
1194 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001195 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1196 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001197 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001198 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001199}
1200
Alexey Bataeve3727102018-04-18 15:57:46 +00001201const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1202 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1203 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001204 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001205 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001206 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001207 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001208 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001209 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001210 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001211 if (!ReductionData.ReductionOp ||
1212 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001213 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001214 SR = ReductionData.ReductionRange;
1215 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001216 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1217 "expression for the descriptor is not "
1218 "set.");
1219 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001220 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1221 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001222 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001223 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001224}
1225
Richard Smith375dec52019-05-30 23:21:14 +00001226bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001227 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001228 for (const_iterator E = end(); I != E; ++I) {
1229 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1230 isOpenMPTargetExecutionDirective(I->Directive)) {
1231 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1232 Scope *CurScope = getCurScope();
1233 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1234 CurScope = CurScope->getParent();
1235 return CurScope != TopScope;
1236 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001237 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001238 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001239}
1240
Joel E. Dennyd2649292019-01-04 22:11:56 +00001241static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1242 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001243 bool *IsClassType = nullptr) {
1244 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001245 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001246 bool IsConstant = Type.isConstant(Context);
1247 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001248 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1249 ? Type->getAsCXXRecordDecl()
1250 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001251 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1252 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1253 RD = CTD->getTemplatedDecl();
1254 if (IsClassType)
1255 *IsClassType = RD;
1256 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1257 RD->hasDefinition() && RD->hasMutableFields());
1258}
1259
Joel E. Dennyd2649292019-01-04 22:11:56 +00001260static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1261 QualType Type, OpenMPClauseKind CKind,
1262 SourceLocation ELoc,
1263 bool AcceptIfMutable = true,
1264 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001265 ASTContext &Context = SemaRef.getASTContext();
1266 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001267 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1268 unsigned Diag = ListItemNotVar
1269 ? diag::err_omp_const_list_item
1270 : IsClassType ? diag::err_omp_const_not_mutable_variable
1271 : diag::err_omp_const_variable;
1272 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1273 if (!ListItemNotVar && D) {
1274 const VarDecl *VD = dyn_cast<VarDecl>(D);
1275 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1276 VarDecl::DeclarationOnly;
1277 SemaRef.Diag(D->getLocation(),
1278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1279 << D;
1280 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001281 return true;
1282 }
1283 return false;
1284}
1285
Alexey Bataeve3727102018-04-18 15:57:46 +00001286const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1287 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001288 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001289 DSAVarData DVar;
1290
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001291 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001292 auto TI = Threadprivates.find(D);
1293 if (TI != Threadprivates.end()) {
1294 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001295 DVar.CKind = OMPC_threadprivate;
1296 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001297 }
1298 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001299 DVar.RefExpr = buildDeclRefExpr(
1300 SemaRef, VD, D->getType().getNonReferenceType(),
1301 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1302 DVar.CKind = OMPC_threadprivate;
1303 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001304 return DVar;
1305 }
1306 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1307 // in a Construct, C/C++, predetermined, p.1]
1308 // Variables appearing in threadprivate directives are threadprivate.
1309 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1310 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1311 SemaRef.getLangOpts().OpenMPUseTLS &&
1312 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1313 (VD && VD->getStorageClass() == SC_Register &&
1314 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1315 DVar.RefExpr = buildDeclRefExpr(
1316 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1317 DVar.CKind = OMPC_threadprivate;
1318 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1319 return DVar;
1320 }
1321 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1322 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1323 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001324 const_iterator IterTarget =
1325 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1326 return isOpenMPTargetExecutionDirective(Data.Directive);
1327 });
1328 if (IterTarget != end()) {
1329 const_iterator ParentIterTarget = IterTarget + 1;
1330 for (const_iterator Iter = begin();
1331 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001332 if (isOpenMPLocal(VD, Iter)) {
1333 DVar.RefExpr =
1334 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1335 D->getLocation());
1336 DVar.CKind = OMPC_threadprivate;
1337 return DVar;
1338 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001339 }
Richard Smith375dec52019-05-30 23:21:14 +00001340 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001341 auto DSAIter = IterTarget->SharingMap.find(D);
1342 if (DSAIter != IterTarget->SharingMap.end() &&
1343 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1344 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1345 DVar.CKind = OMPC_threadprivate;
1346 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001347 }
Richard Smith375dec52019-05-30 23:21:14 +00001348 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001349 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001350 D, std::distance(ParentIterTarget, End),
1351 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001352 DVar.RefExpr =
1353 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1354 IterTarget->ConstructLoc);
1355 DVar.CKind = OMPC_threadprivate;
1356 return DVar;
1357 }
1358 }
1359 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001360 }
1361
Alexey Bataev4b465392017-04-26 15:06:24 +00001362 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001363 // Not in OpenMP execution region and top scope was already checked.
1364 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001365
Alexey Bataev758e55e2013-09-06 18:03:48 +00001366 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001367 // in a Construct, C/C++, predetermined, p.4]
1368 // Static data members are shared.
1369 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1370 // in a Construct, C/C++, predetermined, p.7]
1371 // Variables with static storage duration that are declared in a scope
1372 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001373 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001374 // Check for explicitly specified attributes.
1375 const_iterator I = begin();
1376 const_iterator EndI = end();
1377 if (FromParent && I != EndI)
1378 ++I;
1379 auto It = I->SharingMap.find(D);
1380 if (It != I->SharingMap.end()) {
1381 const DSAInfo &Data = It->getSecond();
1382 DVar.RefExpr = Data.RefExpr.getPointer();
1383 DVar.PrivateCopy = Data.PrivateCopy;
1384 DVar.CKind = Data.Attributes;
1385 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1386 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001387 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001388 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001389
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001390 DVar.CKind = OMPC_shared;
1391 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001392 }
1393
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001394 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001395 // The predetermined shared attribute for const-qualified types having no
1396 // mutable members was removed after OpenMP 3.1.
1397 if (SemaRef.LangOpts.OpenMP <= 31) {
1398 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1399 // in a Construct, C/C++, predetermined, p.6]
1400 // Variables with const qualified type having no mutable member are
1401 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001402 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001403 // Variables with const-qualified type having no mutable member may be
1404 // listed in a firstprivate clause, even if they are static data members.
1405 DSAVarData DVarTemp = hasInnermostDSA(
1406 D,
1407 [](OpenMPClauseKind C) {
1408 return C == OMPC_firstprivate || C == OMPC_shared;
1409 },
1410 MatchesAlways, FromParent);
1411 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1412 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001413
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001414 DVar.CKind = OMPC_shared;
1415 return DVar;
1416 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001417 }
1418
Alexey Bataev758e55e2013-09-06 18:03:48 +00001419 // Explicitly specified attributes and local variables with predetermined
1420 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001421 const_iterator I = begin();
1422 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001423 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001424 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001425 auto It = I->SharingMap.find(D);
1426 if (It != I->SharingMap.end()) {
1427 const DSAInfo &Data = It->getSecond();
1428 DVar.RefExpr = Data.RefExpr.getPointer();
1429 DVar.PrivateCopy = Data.PrivateCopy;
1430 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001431 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001432 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001433 }
1434
1435 return DVar;
1436}
1437
Alexey Bataeve3727102018-04-18 15:57:46 +00001438const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1439 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001440 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001441 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001442 return getDSA(I, D);
1443 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001444 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001445 const_iterator StartI = begin();
1446 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001447 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001448 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001449 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001450}
1451
Alexey Bataeve3727102018-04-18 15:57:46 +00001452const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001453DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001454 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1455 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001456 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001457 if (isStackEmpty())
1458 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001459 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001460 const_iterator I = begin();
1461 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001462 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001463 ++I;
1464 for (; I != EndI; ++I) {
1465 if (!DPred(I->Directive) &&
1466 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001467 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001468 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001469 DSAVarData DVar = getDSA(NewI, D);
1470 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001471 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001472 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001473 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001474}
1475
Alexey Bataeve3727102018-04-18 15:57:46 +00001476const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001477 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1478 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001479 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001480 if (isStackEmpty())
1481 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001482 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001483 const_iterator StartI = begin();
1484 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001485 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001486 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001487 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001488 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001489 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001490 DSAVarData DVar = getDSA(NewI, D);
1491 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001492}
1493
Alexey Bataevaac108a2015-06-23 04:51:00 +00001494bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001495 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1496 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001497 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001498 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001499 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001500 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1501 auto I = StackElem.SharingMap.find(D);
1502 if (I != StackElem.SharingMap.end() &&
1503 I->getSecond().RefExpr.getPointer() &&
1504 CPred(I->getSecond().Attributes) &&
1505 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001506 return true;
1507 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001508 auto LI = StackElem.LCVMap.find(D);
1509 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001510 return CPred(OMPC_private);
1511 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001512}
1513
Samuel Antao4be30e92015-10-02 17:14:03 +00001514bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001515 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1516 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001517 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001518 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001519 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1520 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001521}
1522
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001523bool DSAStackTy::hasDirective(
1524 const llvm::function_ref<bool(OpenMPDirectiveKind,
1525 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001526 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001527 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001528 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001529 size_t Skip = FromParent ? 2 : 1;
1530 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1531 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001532 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1533 return true;
1534 }
1535 return false;
1536}
1537
Alexey Bataev758e55e2013-09-06 18:03:48 +00001538void Sema::InitDataSharingAttributesStack() {
1539 VarDataSharingAttributesStack = new DSAStackTy(*this);
1540}
1541
1542#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1543
Alexey Bataev4b465392017-04-26 15:06:24 +00001544void Sema::pushOpenMPFunctionRegion() {
1545 DSAStack->pushFunction();
1546}
1547
1548void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1549 DSAStack->popFunction(OldFSI);
1550}
1551
Alexey Bataevc416e642019-02-08 18:02:25 +00001552static bool isOpenMPDeviceDelayedContext(Sema &S) {
1553 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1554 "Expected OpenMP device compilation.");
1555 return !S.isInOpenMPTargetExecutionDirective() &&
1556 !S.isInOpenMPDeclareTargetContext();
1557}
1558
Alexey Bataev729e2422019-08-23 16:11:14 +00001559namespace {
1560/// Status of the function emission on the host/device.
1561enum class FunctionEmissionStatus {
1562 Emitted,
1563 Discarded,
1564 Unknown,
1565};
1566} // anonymous namespace
1567
Alexey Bataevc416e642019-02-08 18:02:25 +00001568/// Do we know that we will eventually codegen the given function?
Alexey Bataev729e2422019-08-23 16:11:14 +00001569static FunctionEmissionStatus isKnownDeviceEmitted(Sema &S, FunctionDecl *FD) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001570 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1571 "Expected OpenMP device compilation.");
1572 // Templates are emitted when they're instantiated.
1573 if (FD->isDependentContext())
Alexey Bataev729e2422019-08-23 16:11:14 +00001574 return FunctionEmissionStatus::Discarded;
Alexey Bataevc416e642019-02-08 18:02:25 +00001575
Alexey Bataev729e2422019-08-23 16:11:14 +00001576 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
1577 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
1578 if (DevTy.hasValue())
1579 return (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
1580 ? FunctionEmissionStatus::Discarded
1581 : FunctionEmissionStatus::Emitted;
Alexey Bataevc416e642019-02-08 18:02:25 +00001582
1583 // Otherwise, the function is known-emitted if it's in our set of
1584 // known-emitted functions.
Alexey Bataev729e2422019-08-23 16:11:14 +00001585 return (S.DeviceKnownEmittedFns.count(FD) > 0)
1586 ? FunctionEmissionStatus::Emitted
1587 : FunctionEmissionStatus::Unknown;
Alexey Bataevc416e642019-02-08 18:02:25 +00001588}
1589
1590Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1591 unsigned DiagID) {
1592 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1593 "Expected OpenMP device compilation.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001594 FunctionEmissionStatus FES =
1595 isKnownDeviceEmitted(*this, getCurFunctionDecl());
1596 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1597 switch (FES) {
1598 case FunctionEmissionStatus::Emitted:
1599 Kind = DeviceDiagBuilder::K_Immediate;
1600 break;
1601 case FunctionEmissionStatus::Unknown:
1602 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1603 : DeviceDiagBuilder::K_Immediate;
1604 break;
1605 case FunctionEmissionStatus::Discarded:
1606 Kind = DeviceDiagBuilder::K_Nop;
1607 break;
1608 }
1609
1610 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1611}
1612
1613/// Do we know that we will eventually codegen the given function?
1614static FunctionEmissionStatus isKnownHostEmitted(Sema &S, FunctionDecl *FD) {
1615 assert(S.LangOpts.OpenMP && !S.LangOpts.OpenMPIsDevice &&
1616 "Expected OpenMP host compilation.");
1617 // In OpenMP 4.5 all the functions are host functions.
1618 if (S.LangOpts.OpenMP <= 45)
1619 return FunctionEmissionStatus::Emitted;
1620
1621 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
1622 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
1623 if (DevTy.hasValue())
1624 return (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
1625 ? FunctionEmissionStatus::Discarded
1626 : FunctionEmissionStatus::Emitted;
1627
1628 // Otherwise, the function is known-emitted if it's in our set of
1629 // known-emitted functions.
1630 return (S.DeviceKnownEmittedFns.count(FD) > 0)
1631 ? FunctionEmissionStatus::Emitted
1632 : FunctionEmissionStatus::Unknown;
1633}
1634
1635Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1636 unsigned DiagID) {
1637 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1638 "Expected OpenMP host compilation.");
1639 FunctionEmissionStatus FES =
1640 isKnownHostEmitted(*this, getCurFunctionDecl());
1641 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1642 switch (FES) {
1643 case FunctionEmissionStatus::Emitted:
1644 Kind = DeviceDiagBuilder::K_Immediate;
1645 break;
1646 case FunctionEmissionStatus::Unknown:
1647 Kind = DeviceDiagBuilder::K_Deferred;
1648 break;
1649 case FunctionEmissionStatus::Discarded:
1650 Kind = DeviceDiagBuilder::K_Nop;
1651 break;
1652 }
1653
1654 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001655}
1656
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001657void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1658 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001659 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1660 "Expected OpenMP device compilation.");
1661 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001662 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001663 FunctionDecl *Caller = getCurFunctionDecl();
1664
Alexey Bataev729e2422019-08-23 16:11:14 +00001665 // host only function are not available on the device.
1666 if (Caller &&
1667 (isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted ||
1668 (!isOpenMPDeviceDelayedContext(*this) &&
1669 isKnownDeviceEmitted(*this, Caller) ==
1670 FunctionEmissionStatus::Unknown)) &&
1671 isKnownDeviceEmitted(*this, Callee) ==
1672 FunctionEmissionStatus::Discarded) {
1673 StringRef HostDevTy =
1674 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host);
1675 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1676 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1677 diag::note_omp_marked_device_type_here)
1678 << HostDevTy;
1679 return;
1680 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001681 // If the caller is known-emitted, mark the callee as known-emitted.
1682 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001683 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1684 (!Caller && !CheckForDelayedContext) ||
Alexey Bataev729e2422019-08-23 16:11:14 +00001685 (Caller &&
1686 isKnownDeviceEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001687 markKnownEmitted(*this, Caller, Callee, Loc,
1688 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001689 return CheckForDelayedContext &&
1690 isKnownDeviceEmitted(S, FD) ==
1691 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001692 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001693 else if (Caller)
1694 DeviceCallGraph[Caller].insert({Callee, Loc});
1695}
1696
Alexey Bataev729e2422019-08-23 16:11:14 +00001697void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1698 bool CheckCaller) {
1699 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1700 "Expected OpenMP host compilation.");
1701 assert(Callee && "Callee may not be null.");
1702 Callee = Callee->getMostRecentDecl();
1703 FunctionDecl *Caller = getCurFunctionDecl();
1704
1705 // device only function are not available on the host.
1706 if (Caller &&
1707 isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted &&
1708 isKnownHostEmitted(*this, Callee) == FunctionEmissionStatus::Discarded) {
1709 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1710 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1711 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1712 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1713 diag::note_omp_marked_device_type_here)
1714 << NoHostDevTy;
1715 return;
1716 }
1717 // If the caller is known-emitted, mark the callee as known-emitted.
1718 // Otherwise, mark the call in our call graph so we can traverse it later.
1719 if ((!CheckCaller && !Caller) ||
1720 (Caller &&
1721 isKnownHostEmitted(*this, Caller) == FunctionEmissionStatus::Emitted))
1722 markKnownEmitted(
1723 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1724 return CheckCaller &&
1725 isKnownHostEmitted(S, FD) == FunctionEmissionStatus::Emitted;
1726 });
1727 else if (Caller)
1728 DeviceCallGraph[Caller].insert({Callee, Loc});
1729}
1730
Alexey Bataev123ad192019-02-27 20:29:45 +00001731void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1732 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1733 "OpenMP device compilation mode is expected.");
1734 QualType Ty = E->getType();
1735 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001736 ((Ty->isFloat128Type() ||
1737 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1738 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001739 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1740 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001741 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1742 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1743 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001744}
1745
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001746bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1747 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001748 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1749
Alexey Bataeve3727102018-04-18 15:57:46 +00001750 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001751 bool IsByRef = true;
1752
1753 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001754 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001755 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001756
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001757 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001758 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001759 // This table summarizes how a given variable should be passed to the device
1760 // given its type and the clauses where it appears. This table is based on
1761 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1762 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1763 //
1764 // =========================================================================
1765 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1766 // | |(tofrom:scalar)| | pvt | | | |
1767 // =========================================================================
1768 // | scl | | | | - | | bycopy|
1769 // | scl | | - | x | - | - | bycopy|
1770 // | scl | | x | - | - | - | null |
1771 // | scl | x | | | - | | byref |
1772 // | scl | x | - | x | - | - | bycopy|
1773 // | scl | x | x | - | - | - | null |
1774 // | scl | | - | - | - | x | byref |
1775 // | scl | x | - | - | - | x | byref |
1776 //
1777 // | agg | n.a. | | | - | | byref |
1778 // | agg | n.a. | - | x | - | - | byref |
1779 // | agg | n.a. | x | - | - | - | null |
1780 // | agg | n.a. | - | - | - | x | byref |
1781 // | agg | n.a. | - | - | - | x[] | byref |
1782 //
1783 // | ptr | n.a. | | | - | | bycopy|
1784 // | ptr | n.a. | - | x | - | - | bycopy|
1785 // | ptr | n.a. | x | - | - | - | null |
1786 // | ptr | n.a. | - | - | - | x | byref |
1787 // | ptr | n.a. | - | - | - | x[] | bycopy|
1788 // | ptr | n.a. | - | - | x | | bycopy|
1789 // | ptr | n.a. | - | - | x | x | bycopy|
1790 // | ptr | n.a. | - | - | x | x[] | bycopy|
1791 // =========================================================================
1792 // Legend:
1793 // scl - scalar
1794 // ptr - pointer
1795 // agg - aggregate
1796 // x - applies
1797 // - - invalid in this combination
1798 // [] - mapped with an array section
1799 // byref - should be mapped by reference
1800 // byval - should be mapped by value
1801 // null - initialize a local variable to null on the device
1802 //
1803 // Observations:
1804 // - All scalar declarations that show up in a map clause have to be passed
1805 // by reference, because they may have been mapped in the enclosing data
1806 // environment.
1807 // - If the scalar value does not fit the size of uintptr, it has to be
1808 // passed by reference, regardless the result in the table above.
1809 // - For pointers mapped by value that have either an implicit map or an
1810 // array section, the runtime library may pass the NULL value to the
1811 // device instead of the value passed to it by the compiler.
1812
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001813 if (Ty->isReferenceType())
1814 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001815
1816 // Locate map clauses and see if the variable being captured is referred to
1817 // in any of those clauses. Here we only care about variables, not fields,
1818 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001819 bool IsVariableAssociatedWithSection = false;
1820
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001821 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001822 D, Level,
1823 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1824 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001825 MapExprComponents,
1826 OpenMPClauseKind WhereFoundClauseKind) {
1827 // Only the map clause information influences how a variable is
1828 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001829 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001830 if (WhereFoundClauseKind != OMPC_map)
1831 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001832
1833 auto EI = MapExprComponents.rbegin();
1834 auto EE = MapExprComponents.rend();
1835
1836 assert(EI != EE && "Invalid map expression!");
1837
1838 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1839 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1840
1841 ++EI;
1842 if (EI == EE)
1843 return false;
1844
1845 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1846 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1847 isa<MemberExpr>(EI->getAssociatedExpression())) {
1848 IsVariableAssociatedWithSection = true;
1849 // There is nothing more we need to know about this variable.
1850 return true;
1851 }
1852
1853 // Keep looking for more map info.
1854 return false;
1855 });
1856
1857 if (IsVariableUsedInMapClause) {
1858 // If variable is identified in a map clause it is always captured by
1859 // reference except if it is a pointer that is dereferenced somehow.
1860 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1861 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001862 // By default, all the data that has a scalar type is mapped by copy
1863 // (except for reduction variables).
1864 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001865 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1866 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001867 !Ty->isScalarType() ||
1868 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1869 DSAStack->hasExplicitDSA(
1870 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001871 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001872 }
1873
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001874 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001875 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001876 ((IsVariableUsedInMapClause &&
1877 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1878 OMPD_target) ||
1879 !DSAStack->hasExplicitDSA(
1880 D,
1881 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1882 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001883 // If the variable is artificial and must be captured by value - try to
1884 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001885 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1886 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001887 }
1888
Samuel Antao86ace552016-04-27 22:40:57 +00001889 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001890 // and alignment, because the runtime library only deals with uintptr types.
1891 // If it does not fit the uintptr size, we need to pass the data by reference
1892 // instead.
1893 if (!IsByRef &&
1894 (Ctx.getTypeSizeInChars(Ty) >
1895 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001896 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001897 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001898 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001899
1900 return IsByRef;
1901}
1902
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001903unsigned Sema::getOpenMPNestingLevel() const {
1904 assert(getLangOpts().OpenMP);
1905 return DSAStack->getNestingLevel();
1906}
1907
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001908bool Sema::isInOpenMPTargetExecutionDirective() const {
1909 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1910 !DSAStack->isClauseParsingMode()) ||
1911 DSAStack->hasDirective(
1912 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1913 SourceLocation) -> bool {
1914 return isOpenMPTargetExecutionDirective(K);
1915 },
1916 false);
1917}
1918
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001919VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1920 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001921 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001922 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001923
Richard Smith0621a8f2019-05-31 00:45:10 +00001924 // If we want to determine whether the variable should be captured from the
1925 // perspective of the current capturing scope, and we've already left all the
1926 // capturing scopes of the top directive on the stack, check from the
1927 // perspective of its parent directive (if any) instead.
1928 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
1929 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
1930
Samuel Antao4be30e92015-10-02 17:14:03 +00001931 // If we are attempting to capture a global variable in a directive with
1932 // 'target' we return true so that this global is also mapped to the device.
1933 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001934 auto *VD = dyn_cast<VarDecl>(D);
Richard Smith0621a8f2019-05-31 00:45:10 +00001935 if (VD && !VD->hasLocalStorage() &&
1936 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1937 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001938 // Try to mark variable as declare target if it is used in capturing
1939 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00001940 if (LangOpts.OpenMP <= 45 &&
1941 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001942 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001943 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001944 } else if (isInOpenMPTargetExecutionDirective()) {
1945 // If the declaration is enclosed in a 'declare target' directive,
1946 // then it should not be captured.
1947 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001948 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001949 return nullptr;
1950 return VD;
1951 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001952 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001953
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001954 if (CheckScopeInfo) {
1955 bool OpenMPFound = false;
1956 for (unsigned I = StopAt + 1; I > 0; --I) {
1957 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
1958 if(!isa<CapturingScopeInfo>(FSI))
1959 return nullptr;
1960 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
1961 if (RSI->CapRegionKind == CR_OpenMP) {
1962 OpenMPFound = true;
1963 break;
1964 }
1965 }
1966 if (!OpenMPFound)
1967 return nullptr;
1968 }
1969
Alexey Bataev48977c32015-08-04 08:10:48 +00001970 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1971 (!DSAStack->isClauseParsingMode() ||
1972 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001973 auto &&Info = DSAStack->isLoopControlVariable(D);
1974 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001975 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001976 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001977 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001978 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001979 DSAStackTy::DSAVarData DVarPrivate =
1980 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001981 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001982 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00001983 // Threadprivate variables must not be captured.
1984 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
1985 return nullptr;
1986 // The variable is not private or it is the variable in the directive with
1987 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001988 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1989 [](OpenMPDirectiveKind) { return true; },
1990 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001991 if (DVarPrivate.CKind != OMPC_unknown ||
1992 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001993 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001994 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001995 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001996}
1997
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001998void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1999 unsigned Level) const {
2000 SmallVector<OpenMPDirectiveKind, 4> Regions;
2001 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2002 FunctionScopesIndex -= Regions.size();
2003}
2004
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002005void Sema::startOpenMPLoop() {
2006 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2007 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2008 DSAStack->loopInit();
2009}
2010
Alexey Bataeve3727102018-04-18 15:57:46 +00002011bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002012 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002013 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2014 if (DSAStack->getAssociatedLoops() > 0 &&
2015 !DSAStack->isLoopStarted()) {
2016 DSAStack->resetPossibleLoopCounter(D);
2017 DSAStack->loopStart();
2018 return true;
2019 }
2020 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2021 DSAStack->isLoopControlVariable(D).first) &&
2022 !DSAStack->hasExplicitDSA(
2023 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2024 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2025 return true;
2026 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002027 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2028 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2029 DSAStack->isForceVarCapturing() &&
2030 !DSAStack->hasExplicitDSA(
2031 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2032 return true;
2033 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002034 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002035 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002036 (DSAStack->isClauseParsingMode() &&
2037 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002038 // Consider taskgroup reduction descriptor variable a private to avoid
2039 // possible capture in the region.
2040 (DSAStack->hasExplicitDirective(
2041 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2042 Level) &&
2043 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002044}
2045
Alexey Bataeve3727102018-04-18 15:57:46 +00002046void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2047 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002048 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2049 D = getCanonicalDecl(D);
2050 OpenMPClauseKind OMPC = OMPC_unknown;
2051 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2052 const unsigned NewLevel = I - 1;
2053 if (DSAStack->hasExplicitDSA(D,
2054 [&OMPC](const OpenMPClauseKind K) {
2055 if (isOpenMPPrivate(K)) {
2056 OMPC = K;
2057 return true;
2058 }
2059 return false;
2060 },
2061 NewLevel))
2062 break;
2063 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2064 D, NewLevel,
2065 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2066 OpenMPClauseKind) { return true; })) {
2067 OMPC = OMPC_map;
2068 break;
2069 }
2070 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2071 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002072 OMPC = OMPC_map;
2073 if (D->getType()->isScalarType() &&
2074 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
2075 DefaultMapAttributes::DMA_tofrom_scalar)
2076 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002077 break;
2078 }
2079 }
2080 if (OMPC != OMPC_unknown)
2081 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2082}
2083
Alexey Bataeve3727102018-04-18 15:57:46 +00002084bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
2085 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002086 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2087 // Return true if the current level is no longer enclosed in a target region.
2088
Alexey Bataeve3727102018-04-18 15:57:46 +00002089 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002090 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002091 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2092 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00002093}
2094
Alexey Bataeved09d242014-05-28 05:53:51 +00002095void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002096
Alexey Bataev729e2422019-08-23 16:11:14 +00002097void Sema::finalizeOpenMPDelayedAnalysis() {
2098 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2099 // Diagnose implicit declare target functions and their callees.
2100 for (const auto &CallerCallees : DeviceCallGraph) {
2101 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2102 OMPDeclareTargetDeclAttr::getDeviceType(
2103 CallerCallees.getFirst()->getMostRecentDecl());
2104 // Ignore host functions during device analyzis.
2105 if (LangOpts.OpenMPIsDevice && DevTy &&
2106 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2107 continue;
2108 // Ignore nohost functions during host analyzis.
2109 if (!LangOpts.OpenMPIsDevice && DevTy &&
2110 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2111 continue;
2112 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2113 &Callee : CallerCallees.getSecond()) {
2114 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2115 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2116 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2117 if (LangOpts.OpenMPIsDevice && DevTy &&
2118 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2119 // Diagnose host function called during device codegen.
2120 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2121 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2122 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2123 << HostDevTy << 0;
2124 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2125 diag::note_omp_marked_device_type_here)
2126 << HostDevTy;
2127 continue;
2128 }
2129 if (!LangOpts.OpenMPIsDevice && DevTy &&
2130 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2131 // Diagnose nohost function called during host codegen.
2132 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2133 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2134 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2135 << NoHostDevTy << 1;
2136 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2137 diag::note_omp_marked_device_type_here)
2138 << NoHostDevTy;
2139 continue;
2140 }
2141 }
2142 }
2143}
2144
Alexey Bataev758e55e2013-09-06 18:03:48 +00002145void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2146 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002147 Scope *CurScope, SourceLocation Loc) {
2148 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002149 PushExpressionEvaluationContext(
2150 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002151}
2152
Alexey Bataevaac108a2015-06-23 04:51:00 +00002153void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2154 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002155}
2156
Alexey Bataevaac108a2015-06-23 04:51:00 +00002157void Sema::EndOpenMPClause() {
2158 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002159}
2160
Alexey Bataeve106f252019-04-01 14:25:31 +00002161static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2162 ArrayRef<OMPClause *> Clauses);
2163
Alexey Bataev758e55e2013-09-06 18:03:48 +00002164void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002165 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2166 // A variable of class type (or array thereof) that appears in a lastprivate
2167 // clause requires an accessible, unambiguous default constructor for the
2168 // class type, unless the list item is also specified in a firstprivate
2169 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002170 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2171 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002172 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2173 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002174 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002175 if (DE->isValueDependent() || DE->isTypeDependent()) {
2176 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002177 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002178 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002179 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002180 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002181 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002182 const DSAStackTy::DSAVarData DVar =
2183 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002184 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002185 // Generate helper private variable and initialize it with the
2186 // default value. The address of the original variable is replaced
2187 // by the address of the new private variable in CodeGen. This new
2188 // variable is not added to IdResolver, so the code in the OpenMP
2189 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002190 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002191 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002192 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002193 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002194 if (VDPrivate->isInvalidDecl()) {
2195 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002196 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002197 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002198 PrivateCopies.push_back(buildDeclRefExpr(
2199 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002200 } else {
2201 // The variable is also a firstprivate, so initialization sequence
2202 // for private copy is generated already.
2203 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002204 }
2205 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002206 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002207 }
2208 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002209 // Check allocate clauses.
2210 if (!CurContext->isDependentContext())
2211 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002212 }
2213
Alexey Bataev758e55e2013-09-06 18:03:48 +00002214 DSAStack->pop();
2215 DiscardCleanupsInEvaluationContext();
2216 PopExpressionEvaluationContext();
2217}
2218
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002219static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2220 Expr *NumIterations, Sema &SemaRef,
2221 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002222
Alexey Bataeva769e072013-03-22 06:34:35 +00002223namespace {
2224
Alexey Bataeve3727102018-04-18 15:57:46 +00002225class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002226private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002227 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002228
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002229public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002230 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002231 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002232 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002233 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002234 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002235 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2236 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002237 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002238 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002239 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002240
2241 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002242 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002243 }
2244
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002245};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002246
Alexey Bataeve3727102018-04-18 15:57:46 +00002247class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002248private:
2249 Sema &SemaRef;
2250
2251public:
2252 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2253 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2254 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002255 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2256 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002257 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2258 SemaRef.getCurScope());
2259 }
2260 return false;
2261 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002262
2263 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002264 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002265 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002266};
2267
Alexey Bataeved09d242014-05-28 05:53:51 +00002268} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002269
2270ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2271 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002272 const DeclarationNameInfo &Id,
2273 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002274 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2275 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2276
2277 if (Lookup.isAmbiguous())
2278 return ExprError();
2279
2280 VarDecl *VD;
2281 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002282 VarDeclFilterCCC CCC(*this);
2283 if (TypoCorrection Corrected =
2284 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2285 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002286 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002287 PDiag(Lookup.empty()
2288 ? diag::err_undeclared_var_use_suggest
2289 : diag::err_omp_expected_var_arg_suggest)
2290 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002291 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002292 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002293 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2294 : diag::err_omp_expected_var_arg)
2295 << Id.getName();
2296 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002297 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002298 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2299 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2300 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2301 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002302 }
2303 Lookup.suppressDiagnostics();
2304
2305 // OpenMP [2.9.2, Syntax, C/C++]
2306 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002307 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002308 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002309 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002310 bool IsDecl =
2311 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002312 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002313 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2314 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315 return ExprError();
2316 }
2317
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002318 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002319 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002320 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2321 // A threadprivate directive for file-scope variables must appear outside
2322 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002323 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2324 !getCurLexicalContext()->isTranslationUnit()) {
2325 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002326 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002327 bool IsDecl =
2328 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2329 Diag(VD->getLocation(),
2330 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2331 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002332 return ExprError();
2333 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002334 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2335 // A threadprivate directive for static class member variables must appear
2336 // in the class definition, in the same scope in which the member
2337 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002338 if (CanonicalVD->isStaticDataMember() &&
2339 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2340 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002341 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002342 bool IsDecl =
2343 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2344 Diag(VD->getLocation(),
2345 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2346 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002347 return ExprError();
2348 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002349 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2350 // A threadprivate directive for namespace-scope variables must appear
2351 // outside any definition or declaration other than the namespace
2352 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002353 if (CanonicalVD->getDeclContext()->isNamespace() &&
2354 (!getCurLexicalContext()->isFileContext() ||
2355 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2356 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002357 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002358 bool IsDecl =
2359 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2360 Diag(VD->getLocation(),
2361 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2362 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002363 return ExprError();
2364 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002365 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2366 // A threadprivate directive for static block-scope variables must appear
2367 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002368 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002369 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002370 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002371 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002372 bool IsDecl =
2373 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2374 Diag(VD->getLocation(),
2375 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2376 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002377 return ExprError();
2378 }
2379
2380 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2381 // A threadprivate directive must lexically precede all references to any
2382 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002383 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2384 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002385 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002386 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002387 return ExprError();
2388 }
2389
2390 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002391 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2392 SourceLocation(), VD,
2393 /*RefersToEnclosingVariableOrCapture=*/false,
2394 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002395}
2396
Alexey Bataeved09d242014-05-28 05:53:51 +00002397Sema::DeclGroupPtrTy
2398Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2399 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002400 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002401 CurContext->addDecl(D);
2402 return DeclGroupPtrTy::make(DeclGroupRef(D));
2403 }
David Blaikie0403cb12016-01-15 23:43:25 +00002404 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002405}
2406
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002407namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002408class LocalVarRefChecker final
2409 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002410 Sema &SemaRef;
2411
2412public:
2413 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002414 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002415 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002416 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002417 diag::err_omp_local_var_in_threadprivate_init)
2418 << E->getSourceRange();
2419 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2420 << VD << VD->getSourceRange();
2421 return true;
2422 }
2423 }
2424 return false;
2425 }
2426 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002427 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002428 if (Child && Visit(Child))
2429 return true;
2430 }
2431 return false;
2432 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002433 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002434};
2435} // namespace
2436
Alexey Bataeved09d242014-05-28 05:53:51 +00002437OMPThreadPrivateDecl *
2438Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002439 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002440 for (Expr *RefExpr : VarList) {
2441 auto *DE = cast<DeclRefExpr>(RefExpr);
2442 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002443 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002444
Alexey Bataev376b4a42016-02-09 09:41:09 +00002445 // Mark variable as used.
2446 VD->setReferenced();
2447 VD->markUsed(Context);
2448
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002449 QualType QType = VD->getType();
2450 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2451 // It will be analyzed later.
2452 Vars.push_back(DE);
2453 continue;
2454 }
2455
Alexey Bataeva769e072013-03-22 06:34:35 +00002456 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2457 // A threadprivate variable must not have an incomplete type.
2458 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002459 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002460 continue;
2461 }
2462
2463 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2464 // A threadprivate variable must not have a reference type.
2465 if (VD->getType()->isReferenceType()) {
2466 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002467 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2468 bool IsDecl =
2469 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2470 Diag(VD->getLocation(),
2471 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2472 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002473 continue;
2474 }
2475
Samuel Antaof8b50122015-07-13 22:54:53 +00002476 // Check if this is a TLS variable. If TLS is not being supported, produce
2477 // the corresponding diagnostic.
2478 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2479 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2480 getLangOpts().OpenMPUseTLS &&
2481 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002482 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2483 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002484 Diag(ILoc, diag::err_omp_var_thread_local)
2485 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002486 bool IsDecl =
2487 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2488 Diag(VD->getLocation(),
2489 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2490 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002491 continue;
2492 }
2493
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002494 // Check if initial value of threadprivate variable reference variable with
2495 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002496 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002497 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002498 if (Checker.Visit(Init))
2499 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002500 }
2501
Alexey Bataeved09d242014-05-28 05:53:51 +00002502 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002503 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002504 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2505 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002506 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002507 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002508 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002509 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002510 if (!Vars.empty()) {
2511 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2512 Vars);
2513 D->setAccess(AS_public);
2514 }
2515 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002516}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002517
Alexey Bataev27ef9512019-03-20 20:14:22 +00002518static OMPAllocateDeclAttr::AllocatorTypeTy
2519getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2520 if (!Allocator)
2521 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2522 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2523 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002524 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002525 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002526 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002527 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002528 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2529 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2530 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002531 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002532 llvm::FoldingSetNodeID AEId, DAEId;
2533 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2534 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2535 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002536 AllocatorKindRes = AllocatorKind;
2537 break;
2538 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002539 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002540 return AllocatorKindRes;
2541}
2542
Alexey Bataeve106f252019-04-01 14:25:31 +00002543static bool checkPreviousOMPAllocateAttribute(
2544 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2545 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2546 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2547 return false;
2548 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2549 Expr *PrevAllocator = A->getAllocator();
2550 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2551 getAllocatorKind(S, Stack, PrevAllocator);
2552 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2553 if (AllocatorsMatch &&
2554 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2555 Allocator && PrevAllocator) {
2556 const Expr *AE = Allocator->IgnoreParenImpCasts();
2557 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2558 llvm::FoldingSetNodeID AEId, PAEId;
2559 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2560 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2561 AllocatorsMatch = AEId == PAEId;
2562 }
2563 if (!AllocatorsMatch) {
2564 SmallString<256> AllocatorBuffer;
2565 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2566 if (Allocator)
2567 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2568 SmallString<256> PrevAllocatorBuffer;
2569 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2570 if (PrevAllocator)
2571 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2572 S.getPrintingPolicy());
2573
2574 SourceLocation AllocatorLoc =
2575 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2576 SourceRange AllocatorRange =
2577 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2578 SourceLocation PrevAllocatorLoc =
2579 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2580 SourceRange PrevAllocatorRange =
2581 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2582 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2583 << (Allocator ? 1 : 0) << AllocatorStream.str()
2584 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2585 << AllocatorRange;
2586 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2587 << PrevAllocatorRange;
2588 return true;
2589 }
2590 return false;
2591}
2592
2593static void
2594applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2595 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2596 Expr *Allocator, SourceRange SR) {
2597 if (VD->hasAttr<OMPAllocateDeclAttr>())
2598 return;
2599 if (Allocator &&
2600 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2601 Allocator->isInstantiationDependent() ||
2602 Allocator->containsUnexpandedParameterPack()))
2603 return;
2604 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2605 Allocator, SR);
2606 VD->addAttr(A);
2607 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2608 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2609}
2610
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002611Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2612 SourceLocation Loc, ArrayRef<Expr *> VarList,
2613 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2614 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2615 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002616 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002617 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2618 // allocate directives that appear in a target region must specify an
2619 // allocator clause unless a requires directive with the dynamic_allocators
2620 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002621 if (LangOpts.OpenMPIsDevice &&
2622 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002623 targetDiag(Loc, diag::err_expected_allocator_clause);
2624 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002625 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002626 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002627 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2628 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002629 SmallVector<Expr *, 8> Vars;
2630 for (Expr *RefExpr : VarList) {
2631 auto *DE = cast<DeclRefExpr>(RefExpr);
2632 auto *VD = cast<VarDecl>(DE->getDecl());
2633
2634 // Check if this is a TLS variable or global register.
2635 if (VD->getTLSKind() != VarDecl::TLS_None ||
2636 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2637 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2638 !VD->isLocalVarDecl()))
2639 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002640
Alexey Bataev282555a2019-03-19 20:33:44 +00002641 // If the used several times in the allocate directive, the same allocator
2642 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002643 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2644 AllocatorKind, Allocator))
2645 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002646
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002647 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2648 // If a list item has a static storage type, the allocator expression in the
2649 // allocator clause must be a constant expression that evaluates to one of
2650 // the predefined memory allocator values.
2651 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002652 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002653 Diag(Allocator->getExprLoc(),
2654 diag::err_omp_expected_predefined_allocator)
2655 << Allocator->getSourceRange();
2656 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2657 VarDecl::DeclarationOnly;
2658 Diag(VD->getLocation(),
2659 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2660 << VD;
2661 continue;
2662 }
2663 }
2664
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002665 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002666 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2667 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002668 }
2669 if (Vars.empty())
2670 return nullptr;
2671 if (!Owner)
2672 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002673 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002674 D->setAccess(AS_public);
2675 Owner->addDecl(D);
2676 return DeclGroupPtrTy::make(DeclGroupRef(D));
2677}
2678
2679Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002680Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2681 ArrayRef<OMPClause *> ClauseList) {
2682 OMPRequiresDecl *D = nullptr;
2683 if (!CurContext->isFileContext()) {
2684 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2685 } else {
2686 D = CheckOMPRequiresDecl(Loc, ClauseList);
2687 if (D) {
2688 CurContext->addDecl(D);
2689 DSAStack->addRequiresDecl(D);
2690 }
2691 }
2692 return DeclGroupPtrTy::make(DeclGroupRef(D));
2693}
2694
2695OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2696 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002697 /// For target specific clauses, the requires directive cannot be
2698 /// specified after the handling of any of the target regions in the
2699 /// current compilation unit.
2700 ArrayRef<SourceLocation> TargetLocations =
2701 DSAStack->getEncounteredTargetLocs();
2702 if (!TargetLocations.empty()) {
2703 for (const OMPClause *CNew : ClauseList) {
2704 // Check if any of the requires clauses affect target regions.
2705 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2706 isa<OMPUnifiedAddressClause>(CNew) ||
2707 isa<OMPReverseOffloadClause>(CNew) ||
2708 isa<OMPDynamicAllocatorsClause>(CNew)) {
2709 Diag(Loc, diag::err_omp_target_before_requires)
2710 << getOpenMPClauseName(CNew->getClauseKind());
2711 for (SourceLocation TargetLoc : TargetLocations) {
2712 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2713 }
2714 }
2715 }
2716 }
2717
Kelvin Li1408f912018-09-26 04:28:39 +00002718 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2719 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2720 ClauseList);
2721 return nullptr;
2722}
2723
Alexey Bataeve3727102018-04-18 15:57:46 +00002724static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2725 const ValueDecl *D,
2726 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002727 bool IsLoopIterVar = false) {
2728 if (DVar.RefExpr) {
2729 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2730 << getOpenMPClauseName(DVar.CKind);
2731 return;
2732 }
2733 enum {
2734 PDSA_StaticMemberShared,
2735 PDSA_StaticLocalVarShared,
2736 PDSA_LoopIterVarPrivate,
2737 PDSA_LoopIterVarLinear,
2738 PDSA_LoopIterVarLastprivate,
2739 PDSA_ConstVarShared,
2740 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002741 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002742 PDSA_LocalVarPrivate,
2743 PDSA_Implicit
2744 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002745 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002746 auto ReportLoc = D->getLocation();
2747 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002748 if (IsLoopIterVar) {
2749 if (DVar.CKind == OMPC_private)
2750 Reason = PDSA_LoopIterVarPrivate;
2751 else if (DVar.CKind == OMPC_lastprivate)
2752 Reason = PDSA_LoopIterVarLastprivate;
2753 else
2754 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002755 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2756 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002757 Reason = PDSA_TaskVarFirstprivate;
2758 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002759 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002760 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002761 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002762 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002763 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002764 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002765 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002766 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002767 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002768 ReportHint = true;
2769 Reason = PDSA_LocalVarPrivate;
2770 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002771 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002772 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002773 << Reason << ReportHint
2774 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2775 } else if (DVar.ImplicitDSALoc.isValid()) {
2776 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2777 << getOpenMPClauseName(DVar.CKind);
2778 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002779}
2780
Alexey Bataev758e55e2013-09-06 18:03:48 +00002781namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002782class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002783 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002784 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002785 bool ErrorFound = false;
2786 CapturedStmt *CS = nullptr;
2787 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2788 llvm::SmallVector<Expr *, 4> ImplicitMap;
2789 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2790 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002791
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002792 void VisitSubCaptures(OMPExecutableDirective *S) {
2793 // Check implicitly captured variables.
2794 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2795 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002796 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002797 }
2798
Alexey Bataev758e55e2013-09-06 18:03:48 +00002799public:
2800 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002801 if (E->isTypeDependent() || E->isValueDependent() ||
2802 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2803 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002804 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002805 // Check the datasharing rules for the expressions in the clauses.
2806 if (!CS) {
2807 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2808 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2809 Visit(CED->getInit());
2810 return;
2811 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002812 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2813 // Do not analyze internal variables and do not enclose them into
2814 // implicit clauses.
2815 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002816 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002817 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00002818 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002819 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002820
Alexey Bataeve3727102018-04-18 15:57:46 +00002821 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002822 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002823 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002824 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825
Alexey Bataevafe50572017-10-06 17:00:28 +00002826 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002827 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002828 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00002829 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00002830 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
2831 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002832 return;
2833
Alexey Bataeve3727102018-04-18 15:57:46 +00002834 SourceLocation ELoc = E->getExprLoc();
2835 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002836 // The default(none) clause requires that each variable that is referenced
2837 // in the construct, and does not have a predetermined data-sharing
2838 // attribute, must have its data-sharing attribute explicitly determined
2839 // by being listed in a data-sharing attribute clause.
2840 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002841 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002842 VarsWithInheritedDSA.count(VD) == 0) {
2843 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002844 return;
2845 }
2846
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002847 if (isOpenMPTargetExecutionDirective(DKind) &&
2848 !Stack->isLoopControlVariable(VD).first) {
2849 if (!Stack->checkMappableExprComponentListsForDecl(
2850 VD, /*CurrentRegionOnly=*/true,
2851 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2852 StackComponents,
2853 OpenMPClauseKind) {
2854 // Variable is used if it has been marked as an array, array
2855 // section or the variable iself.
2856 return StackComponents.size() == 1 ||
2857 std::all_of(
2858 std::next(StackComponents.rbegin()),
2859 StackComponents.rend(),
2860 [](const OMPClauseMappableExprCommon::
2861 MappableComponent &MC) {
2862 return MC.getAssociatedDeclaration() ==
2863 nullptr &&
2864 (isa<OMPArraySectionExpr>(
2865 MC.getAssociatedExpression()) ||
2866 isa<ArraySubscriptExpr>(
2867 MC.getAssociatedExpression()));
2868 });
2869 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002870 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002871 // By default lambdas are captured as firstprivates.
2872 if (const auto *RD =
2873 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002874 IsFirstprivate = RD->isLambda();
2875 IsFirstprivate =
2876 IsFirstprivate ||
2877 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002878 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002879 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002880 ImplicitFirstprivate.emplace_back(E);
2881 else
2882 ImplicitMap.emplace_back(E);
2883 return;
2884 }
2885 }
2886
Alexey Bataev758e55e2013-09-06 18:03:48 +00002887 // OpenMP [2.9.3.6, Restrictions, p.2]
2888 // A list item that appears in a reduction clause of the innermost
2889 // enclosing worksharing or parallel construct may not be accessed in an
2890 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002891 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002892 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2893 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002894 return isOpenMPParallelDirective(K) ||
2895 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2896 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002897 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002898 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002899 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002900 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002902 return;
2903 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002904
2905 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002906 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002907 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002908 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002909 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002910 return;
2911 }
2912
2913 // Store implicitly used globals with declare target link for parent
2914 // target.
2915 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2916 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2917 Stack->addToParentTargetRegionLinkGlobals(E);
2918 return;
2919 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002920 }
2921 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002922 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002923 if (E->isTypeDependent() || E->isValueDependent() ||
2924 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2925 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002926 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002927 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002928 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002929 if (!FD)
2930 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002931 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002932 // Check if the variable has explicit DSA set and stop analysis if it
2933 // so.
2934 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2935 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002936
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002937 if (isOpenMPTargetExecutionDirective(DKind) &&
2938 !Stack->isLoopControlVariable(FD).first &&
2939 !Stack->checkMappableExprComponentListsForDecl(
2940 FD, /*CurrentRegionOnly=*/true,
2941 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2942 StackComponents,
2943 OpenMPClauseKind) {
2944 return isa<CXXThisExpr>(
2945 cast<MemberExpr>(
2946 StackComponents.back().getAssociatedExpression())
2947 ->getBase()
2948 ->IgnoreParens());
2949 })) {
2950 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2951 // A bit-field cannot appear in a map clause.
2952 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002953 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002954 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002955
2956 // Check to see if the member expression is referencing a class that
2957 // has already been explicitly mapped
2958 if (Stack->isClassPreviouslyMapped(TE->getType()))
2959 return;
2960
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002961 ImplicitMap.emplace_back(E);
2962 return;
2963 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002964
Alexey Bataeve3727102018-04-18 15:57:46 +00002965 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002966 // OpenMP [2.9.3.6, Restrictions, p.2]
2967 // A list item that appears in a reduction clause of the innermost
2968 // enclosing worksharing or parallel construct may not be accessed in
2969 // an explicit task.
2970 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002971 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2972 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002973 return isOpenMPParallelDirective(K) ||
2974 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2975 },
2976 /*FromParent=*/true);
2977 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2978 ErrorFound = true;
2979 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002980 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002981 return;
2982 }
2983
2984 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002985 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002986 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002987 !Stack->isLoopControlVariable(FD).first) {
2988 // Check if there is a captured expression for the current field in the
2989 // region. Do not mark it as firstprivate unless there is no captured
2990 // expression.
2991 // TODO: try to make it firstprivate.
2992 if (DVar.CKind != OMPC_unknown)
2993 ImplicitFirstprivate.push_back(E);
2994 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002995 return;
2996 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002997 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002998 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002999 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003000 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003001 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003002 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003003 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3004 if (!Stack->checkMappableExprComponentListsForDecl(
3005 VD, /*CurrentRegionOnly=*/true,
3006 [&CurComponents](
3007 OMPClauseMappableExprCommon::MappableExprComponentListRef
3008 StackComponents,
3009 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003010 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003011 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003012 for (const auto &SC : llvm::reverse(StackComponents)) {
3013 // Do both expressions have the same kind?
3014 if (CCI->getAssociatedExpression()->getStmtClass() !=
3015 SC.getAssociatedExpression()->getStmtClass())
3016 if (!(isa<OMPArraySectionExpr>(
3017 SC.getAssociatedExpression()) &&
3018 isa<ArraySubscriptExpr>(
3019 CCI->getAssociatedExpression())))
3020 return false;
3021
Alexey Bataeve3727102018-04-18 15:57:46 +00003022 const Decl *CCD = CCI->getAssociatedDeclaration();
3023 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003024 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3025 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3026 if (SCD != CCD)
3027 return false;
3028 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003029 if (CCI == CCE)
3030 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003031 }
3032 return true;
3033 })) {
3034 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003035 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003036 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003037 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003038 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003039 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003040 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003041 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003042 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003043 // for task|target directives.
3044 // Skip analysis of arguments of implicitly defined map clause for target
3045 // directives.
3046 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3047 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003048 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003049 if (CC)
3050 Visit(CC);
3051 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003052 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003053 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003054 // Check implicitly captured variables.
3055 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003056 }
3057 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003058 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003059 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003060 // Check implicitly captured variables in the task-based directives to
3061 // check if they must be firstprivatized.
3062 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003063 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003064 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003065 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003066
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003067 void visitSubCaptures(CapturedStmt *S) {
3068 for (const CapturedStmt::Capture &Cap : S->captures()) {
3069 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3070 continue;
3071 VarDecl *VD = Cap.getCapturedVar();
3072 // Do not try to map the variable if it or its sub-component was mapped
3073 // already.
3074 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3075 Stack->checkMappableExprComponentListsForDecl(
3076 VD, /*CurrentRegionOnly=*/true,
3077 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3078 OpenMPClauseKind) { return true; }))
3079 continue;
3080 DeclRefExpr *DRE = buildDeclRefExpr(
3081 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3082 Cap.getLocation(), /*RefersToCapture=*/true);
3083 Visit(DRE);
3084 }
3085 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003086 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003087 ArrayRef<Expr *> getImplicitFirstprivate() const {
3088 return ImplicitFirstprivate;
3089 }
3090 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00003091 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003092 return VarsWithInheritedDSA;
3093 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003094
Alexey Bataev7ff55242014-06-19 09:13:45 +00003095 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003096 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3097 // Process declare target link variables for the target directives.
3098 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3099 for (DeclRefExpr *E : Stack->getLinkGlobals())
3100 Visit(E);
3101 }
3102 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003103};
Alexey Bataeved09d242014-05-28 05:53:51 +00003104} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003105
Alexey Bataevbae9a792014-06-27 10:37:06 +00003106void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003107 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003108 case OMPD_parallel:
3109 case OMPD_parallel_for:
3110 case OMPD_parallel_for_simd:
3111 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003112 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003113 case OMPD_teams_distribute:
3114 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003115 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003116 QualType KmpInt32PtrTy =
3117 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003118 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003119 std::make_pair(".global_tid.", KmpInt32PtrTy),
3120 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3121 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003122 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003123 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3124 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003125 break;
3126 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003127 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003128 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003129 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003130 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003131 case OMPD_target_teams_distribute:
3132 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003133 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3134 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3135 QualType KmpInt32PtrTy =
3136 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3137 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003138 FunctionProtoType::ExtProtoInfo EPI;
3139 EPI.Variadic = true;
3140 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3141 Sema::CapturedParamNameType Params[] = {
3142 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003143 std::make_pair(".part_id.", KmpInt32PtrTy),
3144 std::make_pair(".privates.", VoidPtrTy),
3145 std::make_pair(
3146 ".copy_fn.",
3147 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003148 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3149 std::make_pair(StringRef(), QualType()) // __context with shared vars
3150 };
3151 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003152 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003153 // Mark this captured region as inlined, because we don't use outlined
3154 // function directly.
3155 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3156 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003157 Context, {}, AttributeCommonInfo::AS_Keyword,
3158 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003159 Sema::CapturedParamNameType ParamsTarget[] = {
3160 std::make_pair(StringRef(), QualType()) // __context with shared vars
3161 };
3162 // Start a captured region for 'target' with no implicit parameters.
3163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003164 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003165 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003166 std::make_pair(".global_tid.", KmpInt32PtrTy),
3167 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3168 std::make_pair(StringRef(), QualType()) // __context with shared vars
3169 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003170 // Start a captured region for 'teams' or 'parallel'. Both regions have
3171 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003172 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003173 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003174 break;
3175 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003176 case OMPD_target:
3177 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003178 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3179 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3180 QualType KmpInt32PtrTy =
3181 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3182 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003183 FunctionProtoType::ExtProtoInfo EPI;
3184 EPI.Variadic = true;
3185 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3186 Sema::CapturedParamNameType Params[] = {
3187 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003188 std::make_pair(".part_id.", KmpInt32PtrTy),
3189 std::make_pair(".privates.", VoidPtrTy),
3190 std::make_pair(
3191 ".copy_fn.",
3192 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003193 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3194 std::make_pair(StringRef(), QualType()) // __context with shared vars
3195 };
3196 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003197 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003198 // Mark this captured region as inlined, because we don't use outlined
3199 // function directly.
3200 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3201 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003202 Context, {}, AttributeCommonInfo::AS_Keyword,
3203 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003204 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003205 std::make_pair(StringRef(), QualType()),
3206 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003207 break;
3208 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003209 case OMPD_simd:
3210 case OMPD_for:
3211 case OMPD_for_simd:
3212 case OMPD_sections:
3213 case OMPD_section:
3214 case OMPD_single:
3215 case OMPD_master:
3216 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003217 case OMPD_taskgroup:
3218 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003219 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003220 case OMPD_ordered:
3221 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003222 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003223 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003224 std::make_pair(StringRef(), QualType()) // __context with shared vars
3225 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003226 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3227 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003228 break;
3229 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003230 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3232 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3233 QualType KmpInt32PtrTy =
3234 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3235 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003236 FunctionProtoType::ExtProtoInfo EPI;
3237 EPI.Variadic = true;
3238 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003239 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003240 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003241 std::make_pair(".part_id.", KmpInt32PtrTy),
3242 std::make_pair(".privates.", VoidPtrTy),
3243 std::make_pair(
3244 ".copy_fn.",
3245 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003246 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003247 std::make_pair(StringRef(), QualType()) // __context with shared vars
3248 };
3249 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3250 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003251 // Mark this captured region as inlined, because we don't use outlined
3252 // function directly.
3253 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3254 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003255 Context, {}, AttributeCommonInfo::AS_Keyword,
3256 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003257 break;
3258 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003259 case OMPD_taskloop:
3260 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003261 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003262 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3263 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003264 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003265 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3266 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003267 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003268 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3269 .withConst();
3270 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3271 QualType KmpInt32PtrTy =
3272 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3273 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003274 FunctionProtoType::ExtProtoInfo EPI;
3275 EPI.Variadic = true;
3276 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003277 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003278 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003279 std::make_pair(".part_id.", KmpInt32PtrTy),
3280 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003281 std::make_pair(
3282 ".copy_fn.",
3283 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3284 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3285 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003286 std::make_pair(".ub.", KmpUInt64Ty),
3287 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003288 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003289 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003290 std::make_pair(StringRef(), QualType()) // __context with shared vars
3291 };
3292 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3293 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003294 // Mark this captured region as inlined, because we don't use outlined
3295 // function directly.
3296 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3297 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003298 Context, {}, AttributeCommonInfo::AS_Keyword,
3299 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003300 break;
3301 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003302 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003303 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003304 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003305 QualType KmpInt32PtrTy =
3306 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3307 Sema::CapturedParamNameType Params[] = {
3308 std::make_pair(".global_tid.", KmpInt32PtrTy),
3309 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003310 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3311 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003312 std::make_pair(StringRef(), QualType()) // __context with shared vars
3313 };
3314 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3315 Params);
3316 break;
3317 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003318 case OMPD_target_teams_distribute_parallel_for:
3319 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003320 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003321 QualType KmpInt32PtrTy =
3322 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003323 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003324
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003325 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003326 FunctionProtoType::ExtProtoInfo EPI;
3327 EPI.Variadic = true;
3328 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3329 Sema::CapturedParamNameType Params[] = {
3330 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003331 std::make_pair(".part_id.", KmpInt32PtrTy),
3332 std::make_pair(".privates.", VoidPtrTy),
3333 std::make_pair(
3334 ".copy_fn.",
3335 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003336 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3337 std::make_pair(StringRef(), QualType()) // __context with shared vars
3338 };
3339 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003340 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003341 // Mark this captured region as inlined, because we don't use outlined
3342 // function directly.
3343 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3344 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003345 Context, {}, AttributeCommonInfo::AS_Keyword,
3346 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003347 Sema::CapturedParamNameType ParamsTarget[] = {
3348 std::make_pair(StringRef(), QualType()) // __context with shared vars
3349 };
3350 // Start a captured region for 'target' with no implicit parameters.
3351 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003352 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003353
3354 Sema::CapturedParamNameType ParamsTeams[] = {
3355 std::make_pair(".global_tid.", KmpInt32PtrTy),
3356 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3357 std::make_pair(StringRef(), QualType()) // __context with shared vars
3358 };
3359 // Start a captured region for 'target' with no implicit parameters.
3360 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003361 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003362
3363 Sema::CapturedParamNameType ParamsParallel[] = {
3364 std::make_pair(".global_tid.", KmpInt32PtrTy),
3365 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003366 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3367 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003368 std::make_pair(StringRef(), QualType()) // __context with shared vars
3369 };
3370 // Start a captured region for 'teams' or 'parallel'. Both regions have
3371 // the same implicit parameters.
3372 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003373 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003374 break;
3375 }
3376
Alexey Bataev46506272017-12-05 17:41:34 +00003377 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003378 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003379 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003380 QualType KmpInt32PtrTy =
3381 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3382
3383 Sema::CapturedParamNameType ParamsTeams[] = {
3384 std::make_pair(".global_tid.", KmpInt32PtrTy),
3385 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3386 std::make_pair(StringRef(), QualType()) // __context with shared vars
3387 };
3388 // Start a captured region for 'target' with no implicit parameters.
3389 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003390 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003391
3392 Sema::CapturedParamNameType ParamsParallel[] = {
3393 std::make_pair(".global_tid.", KmpInt32PtrTy),
3394 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003395 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3396 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003397 std::make_pair(StringRef(), QualType()) // __context with shared vars
3398 };
3399 // Start a captured region for 'teams' or 'parallel'. Both regions have
3400 // the same implicit parameters.
3401 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003402 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003403 break;
3404 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003405 case OMPD_target_update:
3406 case OMPD_target_enter_data:
3407 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003408 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3409 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3410 QualType KmpInt32PtrTy =
3411 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3412 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003413 FunctionProtoType::ExtProtoInfo EPI;
3414 EPI.Variadic = true;
3415 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3416 Sema::CapturedParamNameType Params[] = {
3417 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003418 std::make_pair(".part_id.", KmpInt32PtrTy),
3419 std::make_pair(".privates.", VoidPtrTy),
3420 std::make_pair(
3421 ".copy_fn.",
3422 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003423 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3424 std::make_pair(StringRef(), QualType()) // __context with shared vars
3425 };
3426 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3427 Params);
3428 // Mark this captured region as inlined, because we don't use outlined
3429 // function directly.
3430 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3431 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003432 Context, {}, AttributeCommonInfo::AS_Keyword,
3433 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003434 break;
3435 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003436 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003437 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003438 case OMPD_taskyield:
3439 case OMPD_barrier:
3440 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003441 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003442 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003443 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003444 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003445 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003446 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003447 case OMPD_declare_target:
3448 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003449 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003450 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003451 llvm_unreachable("OpenMP Directive is not allowed");
3452 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003453 llvm_unreachable("Unknown OpenMP directive");
3454 }
3455}
3456
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003457int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3458 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3459 getOpenMPCaptureRegions(CaptureRegions, DKind);
3460 return CaptureRegions.size();
3461}
3462
Alexey Bataev3392d762016-02-16 11:18:12 +00003463static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003464 Expr *CaptureExpr, bool WithInit,
3465 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003466 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003467 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003468 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003469 QualType Ty = Init->getType();
3470 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003471 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003472 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003473 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003474 Ty = C.getPointerType(Ty);
3475 ExprResult Res =
3476 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3477 if (!Res.isUsable())
3478 return nullptr;
3479 Init = Res.get();
3480 }
Alexey Bataev61205072016-03-02 04:57:40 +00003481 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003482 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003483 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003484 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003485 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003486 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003487 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003488 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003489 return CED;
3490}
3491
Alexey Bataev61205072016-03-02 04:57:40 +00003492static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3493 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003494 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003495 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003496 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003497 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003498 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3499 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003500 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003501 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003502}
3503
Alexey Bataev5a3af132016-03-29 08:58:54 +00003504static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003505 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003506 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003507 OMPCapturedExprDecl *CD = buildCaptureDecl(
3508 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3509 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003510 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3511 CaptureExpr->getExprLoc());
3512 }
3513 ExprResult Res = Ref;
3514 if (!S.getLangOpts().CPlusPlus &&
3515 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003516 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003517 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003518 if (!Res.isUsable())
3519 return ExprError();
3520 }
3521 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003522}
3523
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003524namespace {
3525// OpenMP directives parsed in this section are represented as a
3526// CapturedStatement with an associated statement. If a syntax error
3527// is detected during the parsing of the associated statement, the
3528// compiler must abort processing and close the CapturedStatement.
3529//
3530// Combined directives such as 'target parallel' have more than one
3531// nested CapturedStatements. This RAII ensures that we unwind out
3532// of all the nested CapturedStatements when an error is found.
3533class CaptureRegionUnwinderRAII {
3534private:
3535 Sema &S;
3536 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003537 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003538
3539public:
3540 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3541 OpenMPDirectiveKind DKind)
3542 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3543 ~CaptureRegionUnwinderRAII() {
3544 if (ErrorFound) {
3545 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3546 while (--ThisCaptureLevel >= 0)
3547 S.ActOnCapturedRegionError();
3548 }
3549 }
3550};
3551} // namespace
3552
Alexey Bataevb600ae32019-07-01 17:46:52 +00003553void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3554 // Capture variables captured by reference in lambdas for target-based
3555 // directives.
3556 if (!CurContext->isDependentContext() &&
3557 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3558 isOpenMPTargetDataManagementDirective(
3559 DSAStack->getCurrentDirective()))) {
3560 QualType Type = V->getType();
3561 if (const auto *RD = Type.getCanonicalType()
3562 .getNonReferenceType()
3563 ->getAsCXXRecordDecl()) {
3564 bool SavedForceCaptureByReferenceInTargetExecutable =
3565 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3566 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3567 /*V=*/true);
3568 if (RD->isLambda()) {
3569 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3570 FieldDecl *ThisCapture;
3571 RD->getCaptureFields(Captures, ThisCapture);
3572 for (const LambdaCapture &LC : RD->captures()) {
3573 if (LC.getCaptureKind() == LCK_ByRef) {
3574 VarDecl *VD = LC.getCapturedVar();
3575 DeclContext *VDC = VD->getDeclContext();
3576 if (!VDC->Encloses(CurContext))
3577 continue;
3578 MarkVariableReferenced(LC.getLocation(), VD);
3579 } else if (LC.getCaptureKind() == LCK_This) {
3580 QualType ThisTy = getCurrentThisType();
3581 if (!ThisTy.isNull() &&
3582 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3583 CheckCXXThisCapture(LC.getLocation());
3584 }
3585 }
3586 }
3587 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3588 SavedForceCaptureByReferenceInTargetExecutable);
3589 }
3590 }
3591}
3592
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003593StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3594 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003595 bool ErrorFound = false;
3596 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3597 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003598 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003599 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003600 return StmtError();
3601 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003602
Alexey Bataev2ba67042017-11-28 21:11:44 +00003603 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3604 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003605 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003606 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003607 SmallVector<const OMPLinearClause *, 4> LCs;
3608 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003609 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003610 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003611 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3612 Clause->getClauseKind() == OMPC_in_reduction) {
3613 // Capture taskgroup task_reduction descriptors inside the tasking regions
3614 // with the corresponding in_reduction items.
3615 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003616 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003617 if (E)
3618 MarkDeclarationsReferencedInExpr(E);
3619 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003620 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003621 Clause->getClauseKind() == OMPC_copyprivate ||
3622 (getLangOpts().OpenMPUseTLS &&
3623 getASTContext().getTargetInfo().isTLSSupported() &&
3624 Clause->getClauseKind() == OMPC_copyin)) {
3625 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003626 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003627 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003628 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003629 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003630 }
3631 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003632 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003633 } else if (CaptureRegions.size() > 1 ||
3634 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003635 if (auto *C = OMPClauseWithPreInit::get(Clause))
3636 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003637 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003638 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003639 MarkDeclarationsReferencedInExpr(E);
3640 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003641 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003642 if (Clause->getClauseKind() == OMPC_schedule)
3643 SC = cast<OMPScheduleClause>(Clause);
3644 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003645 OC = cast<OMPOrderedClause>(Clause);
3646 else if (Clause->getClauseKind() == OMPC_linear)
3647 LCs.push_back(cast<OMPLinearClause>(Clause));
3648 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003649 // OpenMP, 2.7.1 Loop Construct, Restrictions
3650 // The nonmonotonic modifier cannot be specified if an ordered clause is
3651 // specified.
3652 if (SC &&
3653 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3654 SC->getSecondScheduleModifier() ==
3655 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3656 OC) {
3657 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3658 ? SC->getFirstScheduleModifierLoc()
3659 : SC->getSecondScheduleModifierLoc(),
3660 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003661 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003662 ErrorFound = true;
3663 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003664 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003665 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003666 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003667 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003668 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003669 ErrorFound = true;
3670 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003671 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3672 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3673 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003674 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003675 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3676 ErrorFound = true;
3677 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003678 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003679 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003680 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003681 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00003682 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003683 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003684 // Mark all variables in private list clauses as used in inner region.
3685 // Required for proper codegen of combined directives.
3686 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003687 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003688 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003689 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3690 // Find the particular capture region for the clause if the
3691 // directive is a combined one with multiple capture regions.
3692 // If the directive is not a combined one, the capture region
3693 // associated with the clause is OMPD_unknown and is generated
3694 // only once.
3695 if (CaptureRegion == ThisCaptureRegion ||
3696 CaptureRegion == OMPD_unknown) {
3697 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003698 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003699 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3700 }
3701 }
3702 }
3703 }
Richard Smith0621a8f2019-05-31 00:45:10 +00003704 if (++CompletedRegions == CaptureRegions.size())
3705 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003706 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003707 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003708 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003709}
3710
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003711static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3712 OpenMPDirectiveKind CancelRegion,
3713 SourceLocation StartLoc) {
3714 // CancelRegion is only needed for cancel and cancellation_point.
3715 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3716 return false;
3717
3718 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3719 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3720 return false;
3721
3722 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3723 << getOpenMPDirectiveName(CancelRegion);
3724 return true;
3725}
3726
Alexey Bataeve3727102018-04-18 15:57:46 +00003727static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003728 OpenMPDirectiveKind CurrentRegion,
3729 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003730 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003731 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003732 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003733 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3734 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003735 bool NestingProhibited = false;
3736 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003737 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003738 enum {
3739 NoRecommend,
3740 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003741 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003742 ShouldBeInTargetRegion,
3743 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003744 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003745 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003746 // OpenMP [2.16, Nesting of Regions]
3747 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003748 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003749 // An ordered construct with the simd clause is the only OpenMP
3750 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003751 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003752 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3753 // message.
3754 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3755 ? diag::err_omp_prohibited_region_simd
3756 : diag::warn_omp_nesting_simd);
3757 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003758 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003759 if (ParentRegion == OMPD_atomic) {
3760 // OpenMP [2.16, Nesting of Regions]
3761 // OpenMP constructs may not be nested inside an atomic region.
3762 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3763 return true;
3764 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003765 if (CurrentRegion == OMPD_section) {
3766 // OpenMP [2.7.2, sections Construct, Restrictions]
3767 // Orphaned section directives are prohibited. That is, the section
3768 // directives must appear within the sections construct and must not be
3769 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003770 if (ParentRegion != OMPD_sections &&
3771 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003772 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3773 << (ParentRegion != OMPD_unknown)
3774 << getOpenMPDirectiveName(ParentRegion);
3775 return true;
3776 }
3777 return false;
3778 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003779 // Allow some constructs (except teams and cancellation constructs) to be
3780 // orphaned (they could be used in functions, called from OpenMP regions
3781 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003782 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003783 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3784 CurrentRegion != OMPD_cancellation_point &&
3785 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003786 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003787 if (CurrentRegion == OMPD_cancellation_point ||
3788 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003789 // OpenMP [2.16, Nesting of Regions]
3790 // A cancellation point construct for which construct-type-clause is
3791 // taskgroup must be nested inside a task construct. A cancellation
3792 // point construct for which construct-type-clause is not taskgroup must
3793 // be closely nested inside an OpenMP construct that matches the type
3794 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003795 // A cancel construct for which construct-type-clause is taskgroup must be
3796 // nested inside a task construct. A cancel construct for which
3797 // construct-type-clause is not taskgroup must be closely nested inside an
3798 // OpenMP construct that matches the type specified in
3799 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003800 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003801 !((CancelRegion == OMPD_parallel &&
3802 (ParentRegion == OMPD_parallel ||
3803 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003804 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003805 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003806 ParentRegion == OMPD_target_parallel_for ||
3807 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003808 ParentRegion == OMPD_teams_distribute_parallel_for ||
3809 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003810 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3811 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003812 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3813 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003814 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003815 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003816 // OpenMP [2.16, Nesting of Regions]
3817 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003818 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003819 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003820 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003821 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3822 // OpenMP [2.16, Nesting of Regions]
3823 // A critical region may not be nested (closely or otherwise) inside a
3824 // critical region with the same name. Note that this restriction is not
3825 // sufficient to prevent deadlock.
3826 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003827 bool DeadLock = Stack->hasDirective(
3828 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3829 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003830 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003831 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3832 PreviousCriticalLoc = Loc;
3833 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003834 }
3835 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003836 },
3837 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003838 if (DeadLock) {
3839 SemaRef.Diag(StartLoc,
3840 diag::err_omp_prohibited_region_critical_same_name)
3841 << CurrentName.getName();
3842 if (PreviousCriticalLoc.isValid())
3843 SemaRef.Diag(PreviousCriticalLoc,
3844 diag::note_omp_previous_critical_region);
3845 return true;
3846 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003847 } else if (CurrentRegion == OMPD_barrier) {
3848 // OpenMP [2.16, Nesting of Regions]
3849 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003850 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003851 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3852 isOpenMPTaskingDirective(ParentRegion) ||
3853 ParentRegion == OMPD_master ||
3854 ParentRegion == OMPD_critical ||
3855 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003856 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003857 !isOpenMPParallelDirective(CurrentRegion) &&
3858 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003859 // OpenMP [2.16, Nesting of Regions]
3860 // A worksharing region may not be closely nested inside a worksharing,
3861 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003862 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3863 isOpenMPTaskingDirective(ParentRegion) ||
3864 ParentRegion == OMPD_master ||
3865 ParentRegion == OMPD_critical ||
3866 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003867 Recommend = ShouldBeInParallelRegion;
3868 } else if (CurrentRegion == OMPD_ordered) {
3869 // OpenMP [2.16, Nesting of Regions]
3870 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003871 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003872 // An ordered region must be closely nested inside a loop region (or
3873 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003874 // OpenMP [2.8.1,simd Construct, Restrictions]
3875 // An ordered construct with the simd clause is the only OpenMP construct
3876 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003877 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003878 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003879 !(isOpenMPSimdDirective(ParentRegion) ||
3880 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003881 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003882 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003883 // OpenMP [2.16, Nesting of Regions]
3884 // If specified, a teams construct must be contained within a target
3885 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00003886 NestingProhibited =
3887 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
3888 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
3889 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00003890 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003891 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003892 }
Kelvin Libf594a52016-12-17 05:48:59 +00003893 if (!NestingProhibited &&
3894 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3895 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3896 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003897 // OpenMP [2.16, Nesting of Regions]
3898 // distribute, parallel, parallel sections, parallel workshare, and the
3899 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3900 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003901 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3902 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003903 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003904 }
David Majnemer9d168222016-08-05 17:44:54 +00003905 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003906 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003907 // OpenMP 4.5 [2.17 Nesting of Regions]
3908 // The region associated with the distribute construct must be strictly
3909 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003910 NestingProhibited =
3911 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003912 Recommend = ShouldBeInTeamsRegion;
3913 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003914 if (!NestingProhibited &&
3915 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3916 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3917 // OpenMP 4.5 [2.17 Nesting of Regions]
3918 // If a target, target update, target data, target enter data, or
3919 // target exit data construct is encountered during execution of a
3920 // target region, the behavior is unspecified.
3921 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003922 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003923 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003924 if (isOpenMPTargetExecutionDirective(K)) {
3925 OffendingRegion = K;
3926 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003927 }
3928 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003929 },
3930 false /* don't skip top directive */);
3931 CloseNesting = false;
3932 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003933 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003934 if (OrphanSeen) {
3935 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3936 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3937 } else {
3938 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3939 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3940 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3941 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003942 return true;
3943 }
3944 }
3945 return false;
3946}
3947
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003948static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3949 ArrayRef<OMPClause *> Clauses,
3950 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3951 bool ErrorFound = false;
3952 unsigned NamedModifiersNumber = 0;
3953 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3954 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003955 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003956 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003957 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3958 // At most one if clause without a directive-name-modifier can appear on
3959 // the directive.
3960 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3961 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003962 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003963 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3964 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3965 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003966 } else if (CurNM != OMPD_unknown) {
3967 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003968 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003969 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003970 FoundNameModifiers[CurNM] = IC;
3971 if (CurNM == OMPD_unknown)
3972 continue;
3973 // Check if the specified name modifier is allowed for the current
3974 // directive.
3975 // At most one if clause with the particular directive-name-modifier can
3976 // appear on the directive.
3977 bool MatchFound = false;
3978 for (auto NM : AllowedNameModifiers) {
3979 if (CurNM == NM) {
3980 MatchFound = true;
3981 break;
3982 }
3983 }
3984 if (!MatchFound) {
3985 S.Diag(IC->getNameModifierLoc(),
3986 diag::err_omp_wrong_if_directive_name_modifier)
3987 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3988 ErrorFound = true;
3989 }
3990 }
3991 }
3992 // If any if clause on the directive includes a directive-name-modifier then
3993 // all if clauses on the directive must include a directive-name-modifier.
3994 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3995 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003996 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003997 diag::err_omp_no_more_if_clause);
3998 } else {
3999 std::string Values;
4000 std::string Sep(", ");
4001 unsigned AllowedCnt = 0;
4002 unsigned TotalAllowedNum =
4003 AllowedNameModifiers.size() - NamedModifiersNumber;
4004 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4005 ++Cnt) {
4006 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4007 if (!FoundNameModifiers[NM]) {
4008 Values += "'";
4009 Values += getOpenMPDirectiveName(NM);
4010 Values += "'";
4011 if (AllowedCnt + 2 == TotalAllowedNum)
4012 Values += " or ";
4013 else if (AllowedCnt + 1 != TotalAllowedNum)
4014 Values += Sep;
4015 ++AllowedCnt;
4016 }
4017 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004018 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004019 diag::err_omp_unnamed_if_clause)
4020 << (TotalAllowedNum > 1) << Values;
4021 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004022 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004023 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4024 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004025 ErrorFound = true;
4026 }
4027 return ErrorFound;
4028}
4029
Alexey Bataeve106f252019-04-01 14:25:31 +00004030static std::pair<ValueDecl *, bool>
4031getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
4032 SourceRange &ERange, bool AllowArraySection = false) {
4033 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4034 RefExpr->containsUnexpandedParameterPack())
4035 return std::make_pair(nullptr, true);
4036
4037 // OpenMP [3.1, C/C++]
4038 // A list item is a variable name.
4039 // OpenMP [2.9.3.3, Restrictions, p.1]
4040 // A variable that is part of another variable (as an array or
4041 // structure element) cannot appear in a private clause.
4042 RefExpr = RefExpr->IgnoreParens();
4043 enum {
4044 NoArrayExpr = -1,
4045 ArraySubscript = 0,
4046 OMPArraySection = 1
4047 } IsArrayExpr = NoArrayExpr;
4048 if (AllowArraySection) {
4049 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4050 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4051 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4052 Base = TempASE->getBase()->IgnoreParenImpCasts();
4053 RefExpr = Base;
4054 IsArrayExpr = ArraySubscript;
4055 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4056 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4057 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4058 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4059 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4060 Base = TempASE->getBase()->IgnoreParenImpCasts();
4061 RefExpr = Base;
4062 IsArrayExpr = OMPArraySection;
4063 }
4064 }
4065 ELoc = RefExpr->getExprLoc();
4066 ERange = RefExpr->getSourceRange();
4067 RefExpr = RefExpr->IgnoreParenImpCasts();
4068 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4069 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4070 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4071 (S.getCurrentThisType().isNull() || !ME ||
4072 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4073 !isa<FieldDecl>(ME->getMemberDecl()))) {
4074 if (IsArrayExpr != NoArrayExpr) {
4075 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4076 << ERange;
4077 } else {
4078 S.Diag(ELoc,
4079 AllowArraySection
4080 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4081 : diag::err_omp_expected_var_name_member_expr)
4082 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4083 }
4084 return std::make_pair(nullptr, false);
4085 }
4086 return std::make_pair(
4087 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4088}
4089
4090static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004091 ArrayRef<OMPClause *> Clauses) {
4092 assert(!S.CurContext->isDependentContext() &&
4093 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004094 auto AllocateRange =
4095 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004096 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4097 DeclToCopy;
4098 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4099 return isOpenMPPrivate(C->getClauseKind());
4100 });
4101 for (OMPClause *Cl : PrivateRange) {
4102 MutableArrayRef<Expr *>::iterator I, It, Et;
4103 if (Cl->getClauseKind() == OMPC_private) {
4104 auto *PC = cast<OMPPrivateClause>(Cl);
4105 I = PC->private_copies().begin();
4106 It = PC->varlist_begin();
4107 Et = PC->varlist_end();
4108 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4109 auto *PC = cast<OMPFirstprivateClause>(Cl);
4110 I = PC->private_copies().begin();
4111 It = PC->varlist_begin();
4112 Et = PC->varlist_end();
4113 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4114 auto *PC = cast<OMPLastprivateClause>(Cl);
4115 I = PC->private_copies().begin();
4116 It = PC->varlist_begin();
4117 Et = PC->varlist_end();
4118 } else if (Cl->getClauseKind() == OMPC_linear) {
4119 auto *PC = cast<OMPLinearClause>(Cl);
4120 I = PC->privates().begin();
4121 It = PC->varlist_begin();
4122 Et = PC->varlist_end();
4123 } else if (Cl->getClauseKind() == OMPC_reduction) {
4124 auto *PC = cast<OMPReductionClause>(Cl);
4125 I = PC->privates().begin();
4126 It = PC->varlist_begin();
4127 Et = PC->varlist_end();
4128 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4129 auto *PC = cast<OMPTaskReductionClause>(Cl);
4130 I = PC->privates().begin();
4131 It = PC->varlist_begin();
4132 Et = PC->varlist_end();
4133 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4134 auto *PC = cast<OMPInReductionClause>(Cl);
4135 I = PC->privates().begin();
4136 It = PC->varlist_begin();
4137 Et = PC->varlist_end();
4138 } else {
4139 llvm_unreachable("Expected private clause.");
4140 }
4141 for (Expr *E : llvm::make_range(It, Et)) {
4142 if (!*I) {
4143 ++I;
4144 continue;
4145 }
4146 SourceLocation ELoc;
4147 SourceRange ERange;
4148 Expr *SimpleRefExpr = E;
4149 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4150 /*AllowArraySection=*/true);
4151 DeclToCopy.try_emplace(Res.first,
4152 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4153 ++I;
4154 }
4155 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004156 for (OMPClause *C : AllocateRange) {
4157 auto *AC = cast<OMPAllocateClause>(C);
4158 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4159 getAllocatorKind(S, Stack, AC->getAllocator());
4160 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4161 // For task, taskloop or target directives, allocation requests to memory
4162 // allocators with the trait access set to thread result in unspecified
4163 // behavior.
4164 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4165 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4166 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4167 S.Diag(AC->getAllocator()->getExprLoc(),
4168 diag::warn_omp_allocate_thread_on_task_target_directive)
4169 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004170 }
4171 for (Expr *E : AC->varlists()) {
4172 SourceLocation ELoc;
4173 SourceRange ERange;
4174 Expr *SimpleRefExpr = E;
4175 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4176 ValueDecl *VD = Res.first;
4177 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4178 if (!isOpenMPPrivate(Data.CKind)) {
4179 S.Diag(E->getExprLoc(),
4180 diag::err_omp_expected_private_copy_for_allocate);
4181 continue;
4182 }
4183 VarDecl *PrivateVD = DeclToCopy[VD];
4184 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4185 AllocatorKind, AC->getAllocator()))
4186 continue;
4187 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4188 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004189 }
4190 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004191}
4192
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004193StmtResult Sema::ActOnOpenMPExecutableDirective(
4194 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4195 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4196 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004197 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004198 // First check CancelRegion which is then used in checkNestingOfRegions.
4199 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4200 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004201 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004202 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004203
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004204 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004205 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004206 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004207 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004208 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004209 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4210
4211 // Check default data sharing attributes for referenced variables.
4212 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004213 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4214 Stmt *S = AStmt;
4215 while (--ThisCaptureLevel >= 0)
4216 S = cast<CapturedStmt>(S)->getCapturedStmt();
4217 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004218 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4219 !isOpenMPTaskingDirective(Kind)) {
4220 // Visit subcaptures to generate implicit clauses for captured vars.
4221 auto *CS = cast<CapturedStmt>(AStmt);
4222 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4223 getOpenMPCaptureRegions(CaptureRegions, Kind);
4224 // Ignore outer tasking regions for target directives.
4225 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4226 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4227 DSAChecker.visitSubCaptures(CS);
4228 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004229 if (DSAChecker.isErrorFound())
4230 return StmtError();
4231 // Generate list of implicitly defined firstprivate variables.
4232 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004233
Alexey Bataev88202be2017-07-27 13:20:36 +00004234 SmallVector<Expr *, 4> ImplicitFirstprivates(
4235 DSAChecker.getImplicitFirstprivate().begin(),
4236 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004237 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
4238 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00004239 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004240 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004241 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004242 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004243 if (E)
4244 ImplicitFirstprivates.emplace_back(E);
4245 }
4246 }
4247 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004248 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004249 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4250 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004251 ClausesWithImplicit.push_back(Implicit);
4252 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004253 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004254 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004255 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004256 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004257 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004258 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00004259 CXXScopeSpec MapperIdScopeSpec;
4260 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004261 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00004262 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
4263 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
4264 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004265 ClausesWithImplicit.emplace_back(Implicit);
4266 ErrorFound |=
4267 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004268 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004269 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004270 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004271 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004272 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004273
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004274 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004275 switch (Kind) {
4276 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004277 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4278 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004279 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004280 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004281 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004282 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4283 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004284 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004285 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004286 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4287 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004288 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004289 case OMPD_for_simd:
4290 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4291 EndLoc, VarsWithInheritedDSA);
4292 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004293 case OMPD_sections:
4294 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4295 EndLoc);
4296 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004297 case OMPD_section:
4298 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004299 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004300 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4301 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004302 case OMPD_single:
4303 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4304 EndLoc);
4305 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004306 case OMPD_master:
4307 assert(ClausesWithImplicit.empty() &&
4308 "No clauses are allowed for 'omp master' directive");
4309 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4310 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004311 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004312 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4313 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004314 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004315 case OMPD_parallel_for:
4316 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4317 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004318 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004319 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004320 case OMPD_parallel_for_simd:
4321 Res = ActOnOpenMPParallelForSimdDirective(
4322 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004323 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004324 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004325 case OMPD_parallel_sections:
4326 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4327 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004328 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004329 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004330 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004331 Res =
4332 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004333 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004334 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004335 case OMPD_taskyield:
4336 assert(ClausesWithImplicit.empty() &&
4337 "No clauses are allowed for 'omp taskyield' directive");
4338 assert(AStmt == nullptr &&
4339 "No associated statement allowed for 'omp taskyield' directive");
4340 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4341 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004342 case OMPD_barrier:
4343 assert(ClausesWithImplicit.empty() &&
4344 "No clauses are allowed for 'omp barrier' directive");
4345 assert(AStmt == nullptr &&
4346 "No associated statement allowed for 'omp barrier' directive");
4347 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4348 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004349 case OMPD_taskwait:
4350 assert(ClausesWithImplicit.empty() &&
4351 "No clauses are allowed for 'omp taskwait' directive");
4352 assert(AStmt == nullptr &&
4353 "No associated statement allowed for 'omp taskwait' directive");
4354 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4355 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004356 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004357 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4358 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004359 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004360 case OMPD_flush:
4361 assert(AStmt == nullptr &&
4362 "No associated statement allowed for 'omp flush' directive");
4363 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4364 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004365 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004366 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4367 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004368 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004369 case OMPD_atomic:
4370 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4371 EndLoc);
4372 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004373 case OMPD_teams:
4374 Res =
4375 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4376 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004377 case OMPD_target:
4378 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4379 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004380 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004381 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004382 case OMPD_target_parallel:
4383 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4384 StartLoc, EndLoc);
4385 AllowedNameModifiers.push_back(OMPD_target);
4386 AllowedNameModifiers.push_back(OMPD_parallel);
4387 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004388 case OMPD_target_parallel_for:
4389 Res = ActOnOpenMPTargetParallelForDirective(
4390 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4391 AllowedNameModifiers.push_back(OMPD_target);
4392 AllowedNameModifiers.push_back(OMPD_parallel);
4393 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004394 case OMPD_cancellation_point:
4395 assert(ClausesWithImplicit.empty() &&
4396 "No clauses are allowed for 'omp cancellation point' directive");
4397 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4398 "cancellation point' directive");
4399 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4400 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004401 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004402 assert(AStmt == nullptr &&
4403 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004404 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4405 CancelRegion);
4406 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004407 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004408 case OMPD_target_data:
4409 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4410 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004411 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004412 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004413 case OMPD_target_enter_data:
4414 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004415 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004416 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4417 break;
Samuel Antao72590762016-01-19 20:04:50 +00004418 case OMPD_target_exit_data:
4419 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004420 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004421 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4422 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004423 case OMPD_taskloop:
4424 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4425 EndLoc, VarsWithInheritedDSA);
4426 AllowedNameModifiers.push_back(OMPD_taskloop);
4427 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004428 case OMPD_taskloop_simd:
4429 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4430 EndLoc, VarsWithInheritedDSA);
4431 AllowedNameModifiers.push_back(OMPD_taskloop);
4432 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004433 case OMPD_distribute:
4434 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4435 EndLoc, VarsWithInheritedDSA);
4436 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004437 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004438 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4439 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004440 AllowedNameModifiers.push_back(OMPD_target_update);
4441 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004442 case OMPD_distribute_parallel_for:
4443 Res = ActOnOpenMPDistributeParallelForDirective(
4444 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4445 AllowedNameModifiers.push_back(OMPD_parallel);
4446 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004447 case OMPD_distribute_parallel_for_simd:
4448 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4449 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4450 AllowedNameModifiers.push_back(OMPD_parallel);
4451 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004452 case OMPD_distribute_simd:
4453 Res = ActOnOpenMPDistributeSimdDirective(
4454 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4455 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004456 case OMPD_target_parallel_for_simd:
4457 Res = ActOnOpenMPTargetParallelForSimdDirective(
4458 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4459 AllowedNameModifiers.push_back(OMPD_target);
4460 AllowedNameModifiers.push_back(OMPD_parallel);
4461 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004462 case OMPD_target_simd:
4463 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4464 EndLoc, VarsWithInheritedDSA);
4465 AllowedNameModifiers.push_back(OMPD_target);
4466 break;
Kelvin Li02532872016-08-05 14:37:37 +00004467 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004468 Res = ActOnOpenMPTeamsDistributeDirective(
4469 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004470 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004471 case OMPD_teams_distribute_simd:
4472 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4473 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4474 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004475 case OMPD_teams_distribute_parallel_for_simd:
4476 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4477 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4478 AllowedNameModifiers.push_back(OMPD_parallel);
4479 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004480 case OMPD_teams_distribute_parallel_for:
4481 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4482 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4483 AllowedNameModifiers.push_back(OMPD_parallel);
4484 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004485 case OMPD_target_teams:
4486 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4487 EndLoc);
4488 AllowedNameModifiers.push_back(OMPD_target);
4489 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004490 case OMPD_target_teams_distribute:
4491 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4492 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4493 AllowedNameModifiers.push_back(OMPD_target);
4494 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004495 case OMPD_target_teams_distribute_parallel_for:
4496 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4497 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4498 AllowedNameModifiers.push_back(OMPD_target);
4499 AllowedNameModifiers.push_back(OMPD_parallel);
4500 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004501 case OMPD_target_teams_distribute_parallel_for_simd:
4502 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4503 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4504 AllowedNameModifiers.push_back(OMPD_target);
4505 AllowedNameModifiers.push_back(OMPD_parallel);
4506 break;
Kelvin Lida681182017-01-10 18:08:18 +00004507 case OMPD_target_teams_distribute_simd:
4508 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4509 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4510 AllowedNameModifiers.push_back(OMPD_target);
4511 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004512 case OMPD_declare_target:
4513 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004514 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004515 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004516 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004517 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004518 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004519 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004520 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004521 llvm_unreachable("OpenMP Directive is not allowed");
4522 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004523 llvm_unreachable("Unknown OpenMP directive");
4524 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004525
Roman Lebedevb5700602019-03-20 16:32:36 +00004526 ErrorFound = Res.isInvalid() || ErrorFound;
4527
Alexey Bataev412254a2019-05-09 18:44:53 +00004528 // Check variables in the clauses if default(none) was specified.
4529 if (DSAStack->getDefaultDSA() == DSA_none) {
4530 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4531 for (OMPClause *C : Clauses) {
4532 switch (C->getClauseKind()) {
4533 case OMPC_num_threads:
4534 case OMPC_dist_schedule:
4535 // Do not analyse if no parent teams directive.
4536 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()))
4537 break;
4538 continue;
4539 case OMPC_if:
4540 if (isOpenMPTeamsDirective(DSAStack->getCurrentDirective()) &&
4541 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4542 break;
4543 continue;
4544 case OMPC_schedule:
4545 break;
4546 case OMPC_ordered:
4547 case OMPC_device:
4548 case OMPC_num_teams:
4549 case OMPC_thread_limit:
4550 case OMPC_priority:
4551 case OMPC_grainsize:
4552 case OMPC_num_tasks:
4553 case OMPC_hint:
4554 case OMPC_collapse:
4555 case OMPC_safelen:
4556 case OMPC_simdlen:
4557 case OMPC_final:
4558 case OMPC_default:
4559 case OMPC_proc_bind:
4560 case OMPC_private:
4561 case OMPC_firstprivate:
4562 case OMPC_lastprivate:
4563 case OMPC_shared:
4564 case OMPC_reduction:
4565 case OMPC_task_reduction:
4566 case OMPC_in_reduction:
4567 case OMPC_linear:
4568 case OMPC_aligned:
4569 case OMPC_copyin:
4570 case OMPC_copyprivate:
4571 case OMPC_nowait:
4572 case OMPC_untied:
4573 case OMPC_mergeable:
4574 case OMPC_allocate:
4575 case OMPC_read:
4576 case OMPC_write:
4577 case OMPC_update:
4578 case OMPC_capture:
4579 case OMPC_seq_cst:
4580 case OMPC_depend:
4581 case OMPC_threads:
4582 case OMPC_simd:
4583 case OMPC_map:
4584 case OMPC_nogroup:
4585 case OMPC_defaultmap:
4586 case OMPC_to:
4587 case OMPC_from:
4588 case OMPC_use_device_ptr:
4589 case OMPC_is_device_ptr:
4590 continue;
4591 case OMPC_allocator:
4592 case OMPC_flush:
4593 case OMPC_threadprivate:
4594 case OMPC_uniform:
4595 case OMPC_unknown:
4596 case OMPC_unified_address:
4597 case OMPC_unified_shared_memory:
4598 case OMPC_reverse_offload:
4599 case OMPC_dynamic_allocators:
4600 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00004601 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00004602 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00004603 llvm_unreachable("Unexpected clause");
4604 }
4605 for (Stmt *CC : C->children()) {
4606 if (CC)
4607 DSAChecker.Visit(CC);
4608 }
4609 }
4610 for (auto &P : DSAChecker.getVarsWithInheritedDSA())
4611 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
4612 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004613 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004614 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
4615 continue;
4616 ErrorFound = true;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004617 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4618 << P.first << P.second->getSourceRange();
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00004619 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004620 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004621
4622 if (!AllowedNameModifiers.empty())
4623 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4624 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004625
Alexey Bataeved09d242014-05-28 05:53:51 +00004626 if (ErrorFound)
4627 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004628
4629 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4630 Res.getAs<OMPExecutableDirective>()
4631 ->getStructuredBlock()
4632 ->setIsOMPStructuredBlock(true);
4633 }
4634
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004635 if (!CurContext->isDependentContext() &&
4636 isOpenMPTargetExecutionDirective(Kind) &&
4637 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4638 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4639 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4640 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4641 // Register target to DSA Stack.
4642 DSAStack->addTargetDirLocation(StartLoc);
4643 }
4644
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004645 return Res;
4646}
4647
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004648Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4649 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004650 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004651 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4652 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004653 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004654 assert(Linears.size() == LinModifiers.size());
4655 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004656 if (!DG || DG.get().isNull())
4657 return DeclGroupPtrTy();
4658
Alexey Bataevd158cf62019-09-13 20:18:17 +00004659 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004660 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004661 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4662 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004663 return DG;
4664 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004665 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004666 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4667 ADecl = FTD->getTemplatedDecl();
4668
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004669 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4670 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004671 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004672 return DeclGroupPtrTy();
4673 }
4674
Alexey Bataev2af33e32016-04-07 12:45:37 +00004675 // OpenMP [2.8.2, declare simd construct, Description]
4676 // The parameter of the simdlen clause must be a constant positive integer
4677 // expression.
4678 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004679 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004680 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004681 // OpenMP [2.8.2, declare simd construct, Description]
4682 // The special this pointer can be used as if was one of the arguments to the
4683 // function in any of the linear, aligned, or uniform clauses.
4684 // The uniform clause declares one or more arguments to have an invariant
4685 // value for all concurrent invocations of the function in the execution of a
4686 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004687 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4688 const Expr *UniformedLinearThis = nullptr;
4689 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004690 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004691 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4692 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004693 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4694 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004695 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004696 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004697 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004698 }
4699 if (isa<CXXThisExpr>(E)) {
4700 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004701 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004702 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004703 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4704 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004705 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004706 // OpenMP [2.8.2, declare simd construct, Description]
4707 // The aligned clause declares that the object to which each list item points
4708 // is aligned to the number of bytes expressed in the optional parameter of
4709 // the aligned clause.
4710 // The special this pointer can be used as if was one of the arguments to the
4711 // function in any of the linear, aligned, or uniform clauses.
4712 // The type of list items appearing in the aligned clause must be array,
4713 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004714 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4715 const Expr *AlignedThis = nullptr;
4716 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004717 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004718 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4719 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4720 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004721 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4722 FD->getParamDecl(PVD->getFunctionScopeIndex())
4723 ->getCanonicalDecl() == CanonPVD) {
4724 // OpenMP [2.8.1, simd construct, Restrictions]
4725 // A list-item cannot appear in more than one aligned clause.
4726 if (AlignedArgs.count(CanonPVD) > 0) {
4727 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4728 << 1 << E->getSourceRange();
4729 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4730 diag::note_omp_explicit_dsa)
4731 << getOpenMPClauseName(OMPC_aligned);
4732 continue;
4733 }
4734 AlignedArgs[CanonPVD] = E;
4735 QualType QTy = PVD->getType()
4736 .getNonReferenceType()
4737 .getUnqualifiedType()
4738 .getCanonicalType();
4739 const Type *Ty = QTy.getTypePtrOrNull();
4740 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4741 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4742 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4743 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4744 }
4745 continue;
4746 }
4747 }
4748 if (isa<CXXThisExpr>(E)) {
4749 if (AlignedThis) {
4750 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4751 << 2 << E->getSourceRange();
4752 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4753 << getOpenMPClauseName(OMPC_aligned);
4754 }
4755 AlignedThis = E;
4756 continue;
4757 }
4758 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4759 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4760 }
4761 // The optional parameter of the aligned clause, alignment, must be a constant
4762 // positive integer expression. If no optional parameter is specified,
4763 // implementation-defined default alignments for SIMD instructions on the
4764 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004765 SmallVector<const Expr *, 4> NewAligns;
4766 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004767 ExprResult Align;
4768 if (E)
4769 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4770 NewAligns.push_back(Align.get());
4771 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004772 // OpenMP [2.8.2, declare simd construct, Description]
4773 // The linear clause declares one or more list items to be private to a SIMD
4774 // lane and to have a linear relationship with respect to the iteration space
4775 // of a loop.
4776 // The special this pointer can be used as if was one of the arguments to the
4777 // function in any of the linear, aligned, or uniform clauses.
4778 // When a linear-step expression is specified in a linear clause it must be
4779 // either a constant integer expression or an integer-typed parameter that is
4780 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004781 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004782 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4783 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004784 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004785 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4786 ++MI;
4787 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004788 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4789 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4790 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004791 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4792 FD->getParamDecl(PVD->getFunctionScopeIndex())
4793 ->getCanonicalDecl() == CanonPVD) {
4794 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4795 // A list-item cannot appear in more than one linear clause.
4796 if (LinearArgs.count(CanonPVD) > 0) {
4797 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4798 << getOpenMPClauseName(OMPC_linear)
4799 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4800 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4801 diag::note_omp_explicit_dsa)
4802 << getOpenMPClauseName(OMPC_linear);
4803 continue;
4804 }
4805 // Each argument can appear in at most one uniform or linear clause.
4806 if (UniformedArgs.count(CanonPVD) > 0) {
4807 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4808 << getOpenMPClauseName(OMPC_linear)
4809 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4810 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4811 diag::note_omp_explicit_dsa)
4812 << getOpenMPClauseName(OMPC_uniform);
4813 continue;
4814 }
4815 LinearArgs[CanonPVD] = E;
4816 if (E->isValueDependent() || E->isTypeDependent() ||
4817 E->isInstantiationDependent() ||
4818 E->containsUnexpandedParameterPack())
4819 continue;
4820 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4821 PVD->getOriginalType());
4822 continue;
4823 }
4824 }
4825 if (isa<CXXThisExpr>(E)) {
4826 if (UniformedLinearThis) {
4827 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4828 << getOpenMPClauseName(OMPC_linear)
4829 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4830 << E->getSourceRange();
4831 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4832 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4833 : OMPC_linear);
4834 continue;
4835 }
4836 UniformedLinearThis = E;
4837 if (E->isValueDependent() || E->isTypeDependent() ||
4838 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4839 continue;
4840 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4841 E->getType());
4842 continue;
4843 }
4844 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4845 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4846 }
4847 Expr *Step = nullptr;
4848 Expr *NewStep = nullptr;
4849 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004850 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004851 // Skip the same step expression, it was checked already.
4852 if (Step == E || !E) {
4853 NewSteps.push_back(E ? NewStep : nullptr);
4854 continue;
4855 }
4856 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004857 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4858 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4859 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004860 if (UniformedArgs.count(CanonPVD) == 0) {
4861 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4862 << Step->getSourceRange();
4863 } else if (E->isValueDependent() || E->isTypeDependent() ||
4864 E->isInstantiationDependent() ||
4865 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004866 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004867 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004868 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004869 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4870 << Step->getSourceRange();
4871 }
4872 continue;
4873 }
4874 NewStep = Step;
4875 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4876 !Step->isInstantiationDependent() &&
4877 !Step->containsUnexpandedParameterPack()) {
4878 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4879 .get();
4880 if (NewStep)
4881 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4882 }
4883 NewSteps.push_back(NewStep);
4884 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004885 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4886 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004887 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004888 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4889 const_cast<Expr **>(Linears.data()), Linears.size(),
4890 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4891 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004892 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00004893 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00004894}
4895
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004896Optional<std::pair<FunctionDecl *, Expr *>>
4897Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
4898 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00004899 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004900 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004901
4902 const int VariantId = 1;
4903 // Must be applied only to single decl.
4904 if (!DG.get().isSingleDecl()) {
4905 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
4906 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004907 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004908 }
4909 Decl *ADecl = DG.get().getSingleDecl();
4910 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4911 ADecl = FTD->getTemplatedDecl();
4912
4913 // Decl must be a function.
4914 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4915 if (!FD) {
4916 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
4917 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004918 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004919 }
4920
4921 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
4922 return FD->hasAttrs() &&
4923 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
4924 FD->hasAttr<TargetAttr>());
4925 };
4926 // OpenMP is not compatible with CPU-specific attributes.
4927 if (HasMultiVersionAttributes(FD)) {
4928 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
4929 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004930 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004931 }
4932
4933 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00004934 if (FD->isUsed(false))
4935 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00004936 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00004937
4938 // Check if the function was emitted already.
4939 if ((LangOpts.EmitAllDecls && FD->isDefined()) ||
4940 Context.DeclMustBeEmitted(FD))
4941 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
4942 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00004943
4944 // The VariantRef must point to function.
4945 if (!VariantRef) {
4946 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004947 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004948 }
4949
4950 // Do not check templates, wait until instantiation.
4951 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
4952 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004953 VariantRef->isInstantiationDependent() || FD->isDependentContext())
4954 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00004955
4956 // Convert VariantRef expression to the type of the original function to
4957 // resolve possible conflicts.
4958 ExprResult VariantRefCast;
4959 if (LangOpts.CPlusPlus) {
4960 QualType FnPtrType;
4961 auto *Method = dyn_cast<CXXMethodDecl>(FD);
4962 if (Method && !Method->isStatic()) {
4963 const Type *ClassType =
4964 Context.getTypeDeclType(Method->getParent()).getTypePtr();
4965 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
4966 ExprResult ER;
4967 {
4968 // Build adrr_of unary op to correctly handle type checks for member
4969 // functions.
4970 Sema::TentativeAnalysisScope Trap(*this);
4971 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
4972 VariantRef);
4973 }
4974 if (!ER.isUsable()) {
4975 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
4976 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004977 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004978 }
4979 VariantRef = ER.get();
4980 } else {
4981 FnPtrType = Context.getPointerType(FD->getType());
4982 }
4983 ImplicitConversionSequence ICS =
4984 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
4985 /*SuppressUserConversions=*/false,
4986 /*AllowExplicit=*/false,
4987 /*InOverloadResolution=*/false,
4988 /*CStyle=*/false,
4989 /*AllowObjCWritebackConversion=*/false);
4990 if (ICS.isFailure()) {
4991 Diag(VariantRef->getExprLoc(),
4992 diag::err_omp_declare_variant_incompat_types)
4993 << VariantRef->getType() << FnPtrType << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004994 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00004995 }
4996 VariantRefCast = PerformImplicitConversion(
4997 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
4998 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00004999 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005000 // Drop previously built artificial addr_of unary op for member functions.
5001 if (Method && !Method->isStatic()) {
5002 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5003 if (auto *UO = dyn_cast<UnaryOperator>(
5004 PossibleAddrOfVariantRef->IgnoreImplicit()))
5005 VariantRefCast = UO->getSubExpr();
5006 }
5007 } else {
5008 VariantRefCast = VariantRef;
5009 }
5010
5011 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5012 if (!ER.isUsable() ||
5013 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5014 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5015 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005016 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005017 }
5018
5019 // The VariantRef must point to function.
5020 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5021 if (!DRE) {
5022 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5023 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005024 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005025 }
5026 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5027 if (!NewFD) {
5028 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5029 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005030 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005031 }
5032
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005033 // Check if variant function is not marked with declare variant directive.
5034 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5035 Diag(VariantRef->getExprLoc(),
5036 diag::warn_omp_declare_variant_marked_as_declare_variant)
5037 << VariantRef->getSourceRange();
5038 SourceRange SR =
5039 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5040 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005041 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005042 }
5043
Alexey Bataevd158cf62019-09-13 20:18:17 +00005044 enum DoesntSupport {
5045 VirtFuncs = 1,
5046 Constructors = 3,
5047 Destructors = 4,
5048 DeletedFuncs = 5,
5049 DefaultedFuncs = 6,
5050 ConstexprFuncs = 7,
5051 ConstevalFuncs = 8,
5052 };
5053 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5054 if (CXXFD->isVirtual()) {
5055 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5056 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005057 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005058 }
5059
5060 if (isa<CXXConstructorDecl>(FD)) {
5061 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5062 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005063 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005064 }
5065
5066 if (isa<CXXDestructorDecl>(FD)) {
5067 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5068 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005069 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005070 }
5071 }
5072
5073 if (FD->isDeleted()) {
5074 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5075 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005076 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005077 }
5078
5079 if (FD->isDefaulted()) {
5080 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5081 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005082 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005083 }
5084
5085 if (FD->isConstexpr()) {
5086 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5087 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005088 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005089 }
5090
5091 // Check general compatibility.
5092 if (areMultiversionVariantFunctionsCompatible(
5093 FD, NewFD, PDiag(diag::err_omp_declare_variant_noproto),
5094 PartialDiagnosticAt(
5095 SR.getBegin(),
5096 PDiag(diag::note_omp_declare_variant_specified_here) << SR),
5097 PartialDiagnosticAt(
5098 VariantRef->getExprLoc(),
5099 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5100 PartialDiagnosticAt(VariantRef->getExprLoc(),
5101 PDiag(diag::err_omp_declare_variant_diff)
5102 << FD->getLocation()),
5103 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005104 return None;
5105 return std::make_pair(FD, cast<Expr>(DRE));
5106}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005107
Alexey Bataev9ff34742019-09-25 19:43:37 +00005108void Sema::ActOnOpenMPDeclareVariantDirective(
5109 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
5110 const Sema::OpenMPDeclareVariantCtsSelectorData &Data) {
5111 if (Data.CtxSet == OMPDeclareVariantAttr::CtxSetUnknown ||
5112 Data.Ctx == OMPDeclareVariantAttr::CtxUnknown)
5113 return;
5114 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5115 Context, VariantRef, Data.CtxSet, Data.Ctx, Data.ImplVendor, SR);
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005116 FD->addAttr(NewAttr);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005117}
5118
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005119void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5120 FunctionDecl *Func,
5121 bool MightBeOdrUse) {
5122 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5123
5124 if (!Func->isDependentContext() && Func->hasAttrs()) {
5125 for (OMPDeclareVariantAttr *A :
5126 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5127 // TODO: add checks for active OpenMP context where possible.
5128 Expr *VariantRef = A->getVariantFuncRef();
5129 auto *DRE = dyn_cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
5130 auto *F = cast<FunctionDecl>(DRE->getDecl());
5131 if (!F->isDefined() && F->isTemplateInstantiation())
5132 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5133 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5134 }
5135 }
5136}
5137
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005138StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5139 Stmt *AStmt,
5140 SourceLocation StartLoc,
5141 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005142 if (!AStmt)
5143 return StmtError();
5144
Alexey Bataeve3727102018-04-18 15:57:46 +00005145 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005146 // 1.2.2 OpenMP Language Terminology
5147 // Structured block - An executable statement with a single entry at the
5148 // top and a single exit at the bottom.
5149 // The point of exit cannot be a branch out of the structured block.
5150 // longjmp() and throw() must not violate the entry/exit criteria.
5151 CS->getCapturedDecl()->setNothrow();
5152
Reid Kleckner87a31802018-03-12 21:43:02 +00005153 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005154
Alexey Bataev25e5b442015-09-15 12:52:43 +00005155 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5156 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005157}
5158
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005159namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005160/// Iteration space of a single for loop.
5161struct LoopIterationSpace final {
5162 /// True if the condition operator is the strict compare operator (<, > or
5163 /// !=).
5164 bool IsStrictCompare = false;
5165 /// Condition of the loop.
5166 Expr *PreCond = nullptr;
5167 /// This expression calculates the number of iterations in the loop.
5168 /// It is always possible to calculate it before starting the loop.
5169 Expr *NumIterations = nullptr;
5170 /// The loop counter variable.
5171 Expr *CounterVar = nullptr;
5172 /// Private loop counter variable.
5173 Expr *PrivateCounterVar = nullptr;
5174 /// This is initializer for the initial value of #CounterVar.
5175 Expr *CounterInit = nullptr;
5176 /// This is step for the #CounterVar used to generate its update:
5177 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5178 Expr *CounterStep = nullptr;
5179 /// Should step be subtracted?
5180 bool Subtract = false;
5181 /// Source range of the loop init.
5182 SourceRange InitSrcRange;
5183 /// Source range of the loop condition.
5184 SourceRange CondSrcRange;
5185 /// Source range of the loop increment.
5186 SourceRange IncSrcRange;
5187 /// Minimum value that can have the loop control variable. Used to support
5188 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5189 /// since only such variables can be used in non-loop invariant expressions.
5190 Expr *MinValue = nullptr;
5191 /// Maximum value that can have the loop control variable. Used to support
5192 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5193 /// since only such variables can be used in non-loop invariant expressions.
5194 Expr *MaxValue = nullptr;
5195 /// true, if the lower bound depends on the outer loop control var.
5196 bool IsNonRectangularLB = false;
5197 /// true, if the upper bound depends on the outer loop control var.
5198 bool IsNonRectangularUB = false;
5199 /// Index of the loop this loop depends on and forms non-rectangular loop
5200 /// nest.
5201 unsigned LoopDependentIdx = 0;
5202 /// Final condition for the non-rectangular loop nest support. It is used to
5203 /// check that the number of iterations for this particular counter must be
5204 /// finished.
5205 Expr *FinalCondition = nullptr;
5206};
5207
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005208/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005209/// extracting iteration space of each loop in the loop nest, that will be used
5210/// for IR generation.
5211class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005212 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005213 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005214 /// Data-sharing stack.
5215 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005216 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005217 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005218 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005219 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005220 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005221 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005222 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005223 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005224 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005225 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005226 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005227 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005228 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005229 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005230 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005231 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005232 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005233 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005234 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005235 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005236 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005237 /// Var < UB
5238 /// Var <= UB
5239 /// UB > Var
5240 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005241 /// This will have no value when the condition is !=
5242 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005243 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005244 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005245 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005246 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005247 /// The outer loop counter this loop depends on (if any).
5248 const ValueDecl *DepDecl = nullptr;
5249 /// Contains number of loop (starts from 1) on which loop counter init
5250 /// expression of this loop depends on.
5251 Optional<unsigned> InitDependOnLC;
5252 /// Contains number of loop (starts from 1) on which loop counter condition
5253 /// expression of this loop depends on.
5254 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005255 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005256 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005257 /// Original condition required for checking of the exit condition for
5258 /// non-rectangular loop.
5259 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005260
5261public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005262 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5263 SourceLocation DefaultLoc)
5264 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5265 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005266 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005267 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005268 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005269 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005270 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005271 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005272 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005273 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005274 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005275 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005276 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005277 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005278 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005279 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005280 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005281 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005282 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005283 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005284 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005285 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005286 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005287 /// True, if the compare operator is strict (<, > or !=).
5288 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005289 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005290 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005291 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005292 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005293 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005294 Expr *
5295 buildPreCond(Scope *S, Expr *Cond,
5296 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005297 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005298 DeclRefExpr *
5299 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5300 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005301 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005302 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005303 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005304 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005305 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005306 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005307 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005308 /// Build loop data with counter value for depend clauses in ordered
5309 /// directives.
5310 Expr *
5311 buildOrderedLoopData(Scope *S, Expr *Counter,
5312 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5313 SourceLocation Loc, Expr *Inc = nullptr,
5314 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005315 /// Builds the minimum value for the loop counter.
5316 std::pair<Expr *, Expr *> buildMinMaxValues(
5317 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5318 /// Builds final condition for the non-rectangular loops.
5319 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005320 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005321 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005322 /// Returns true if the initializer forms non-rectangular loop.
5323 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5324 /// Returns true if the condition forms non-rectangular loop.
5325 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5326 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5327 unsigned getLoopDependentIdx() const {
5328 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5329 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005330
5331private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005332 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005333 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005334 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005335 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005336 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5337 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005338 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005339 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5340 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005341 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005342 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005343};
5344
Alexey Bataeve3727102018-04-18 15:57:46 +00005345bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005346 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005347 assert(!LB && !UB && !Step);
5348 return false;
5349 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005350 return LCDecl->getType()->isDependentType() ||
5351 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5352 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005353}
5354
Alexey Bataeve3727102018-04-18 15:57:46 +00005355bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005356 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005357 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005358 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005359 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005360 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005361 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005362 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005363 LCDecl = getCanonicalDecl(NewLCDecl);
5364 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005365 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5366 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005367 if ((Ctor->isCopyOrMoveConstructor() ||
5368 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5369 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005370 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005371 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005372 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005373 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005374 return false;
5375}
5376
Alexey Bataev316ccf62019-01-29 18:51:58 +00005377bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5378 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005379 bool StrictOp, SourceRange SR,
5380 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005381 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005382 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5383 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005384 if (!NewUB)
5385 return true;
5386 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005387 if (LessOp)
5388 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005389 TestIsStrictOp = StrictOp;
5390 ConditionSrcRange = SR;
5391 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005392 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005393 return false;
5394}
5395
Alexey Bataeve3727102018-04-18 15:57:46 +00005396bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005397 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005398 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005399 if (!NewStep)
5400 return true;
5401 if (!NewStep->isValueDependent()) {
5402 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005403 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005404 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5405 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005406 if (Val.isInvalid())
5407 return true;
5408 NewStep = Val.get();
5409
5410 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5411 // If test-expr is of form var relational-op b and relational-op is < or
5412 // <= then incr-expr must cause var to increase on each iteration of the
5413 // loop. If test-expr is of form var relational-op b and relational-op is
5414 // > or >= then incr-expr must cause var to decrease on each iteration of
5415 // the loop.
5416 // If test-expr is of form b relational-op var and relational-op is < or
5417 // <= then incr-expr must cause var to decrease on each iteration of the
5418 // loop. If test-expr is of form b relational-op var and relational-op is
5419 // > or >= then incr-expr must cause var to increase on each iteration of
5420 // the loop.
5421 llvm::APSInt Result;
5422 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5423 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5424 bool IsConstNeg =
5425 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005426 bool IsConstPos =
5427 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005428 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005429
5430 // != with increment is treated as <; != with decrement is treated as >
5431 if (!TestIsLessOp.hasValue())
5432 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005433 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005434 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005435 (IsConstNeg || (IsUnsigned && Subtract)) :
5436 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005437 SemaRef.Diag(NewStep->getExprLoc(),
5438 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005439 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005440 SemaRef.Diag(ConditionLoc,
5441 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005442 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005443 return true;
5444 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005445 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005446 NewStep =
5447 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5448 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005449 Subtract = !Subtract;
5450 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005451 }
5452
5453 Step = NewStep;
5454 SubtractStep = Subtract;
5455 return false;
5456}
5457
Alexey Bataev622af1d2019-04-24 19:58:30 +00005458namespace {
5459/// Checker for the non-rectangular loops. Checks if the initializer or
5460/// condition expression references loop counter variable.
5461class LoopCounterRefChecker final
5462 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5463 Sema &SemaRef;
5464 DSAStackTy &Stack;
5465 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005466 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005467 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005468 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005469 unsigned BaseLoopId = 0;
5470 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5471 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5472 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5473 << (IsInitializer ? 0 : 1);
5474 return false;
5475 }
5476 const auto &&Data = Stack.isLoopControlVariable(VD);
5477 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
5478 // The type of the loop iterator on which we depend may not have a random
5479 // access iterator type.
5480 if (Data.first && VD->getType()->isRecordType()) {
5481 SmallString<128> Name;
5482 llvm::raw_svector_ostream OS(Name);
5483 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5484 /*Qualified=*/true);
5485 SemaRef.Diag(E->getExprLoc(),
5486 diag::err_omp_wrong_dependency_iterator_type)
5487 << OS.str();
5488 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
5489 return false;
5490 }
5491 if (Data.first &&
5492 (DepDecl || (PrevDepDecl &&
5493 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
5494 if (!DepDecl && PrevDepDecl)
5495 DepDecl = PrevDepDecl;
5496 SmallString<128> Name;
5497 llvm::raw_svector_ostream OS(Name);
5498 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
5499 /*Qualified=*/true);
5500 SemaRef.Diag(E->getExprLoc(),
5501 diag::err_omp_invariant_or_linear_dependency)
5502 << OS.str();
5503 return false;
5504 }
5505 if (Data.first) {
5506 DepDecl = VD;
5507 BaseLoopId = Data.first;
5508 }
5509 return Data.first;
5510 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005511
5512public:
5513 bool VisitDeclRefExpr(const DeclRefExpr *E) {
5514 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005515 if (isa<VarDecl>(VD))
5516 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005517 return false;
5518 }
5519 bool VisitMemberExpr(const MemberExpr *E) {
5520 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
5521 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00005522 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
5523 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00005524 }
5525 return false;
5526 }
5527 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005528 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005529 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00005530 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005531 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005532 }
5533 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005534 const ValueDecl *CurLCDecl, bool IsInitializer,
5535 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00005536 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005537 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
5538 unsigned getBaseLoopId() const {
5539 assert(CurLCDecl && "Expected loop dependency.");
5540 return BaseLoopId;
5541 }
5542 const ValueDecl *getDepDecl() const {
5543 assert(CurLCDecl && "Expected loop dependency.");
5544 return DepDecl;
5545 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00005546};
5547} // namespace
5548
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005549Optional<unsigned>
5550OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
5551 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00005552 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005553 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
5554 DepDecl);
5555 if (LoopStmtChecker.Visit(S)) {
5556 DepDecl = LoopStmtChecker.getDepDecl();
5557 return LoopStmtChecker.getBaseLoopId();
5558 }
5559 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005560}
5561
Alexey Bataeve3727102018-04-18 15:57:46 +00005562bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005563 // Check init-expr for canonical loop form and save loop counter
5564 // variable - #Var and its initialization value - #LB.
5565 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
5566 // var = lb
5567 // integer-type var = lb
5568 // random-access-iterator-type var = lb
5569 // pointer-type var = lb
5570 //
5571 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00005572 if (EmitDiags) {
5573 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
5574 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005575 return true;
5576 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005577 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5578 if (!ExprTemp->cleanupsHaveSideEffects())
5579 S = ExprTemp->getSubExpr();
5580
Alexander Musmana5f070a2014-10-01 06:03:56 +00005581 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005582 if (Expr *E = dyn_cast<Expr>(S))
5583 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005584 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005585 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005586 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005587 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
5588 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5589 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005590 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5591 EmitDiags);
5592 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005593 }
5594 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5595 if (ME->isArrow() &&
5596 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005597 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5598 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005599 }
5600 }
David Majnemer9d168222016-08-05 17:44:54 +00005601 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005602 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00005603 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00005604 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005605 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00005606 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005607 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005608 diag::ext_omp_loop_not_canonical_init)
5609 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00005610 return setLCDeclAndLB(
5611 Var,
5612 buildDeclRefExpr(SemaRef, Var,
5613 Var->getType().getNonReferenceType(),
5614 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00005615 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005616 }
5617 }
5618 }
David Majnemer9d168222016-08-05 17:44:54 +00005619 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005620 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005621 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00005622 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005623 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
5624 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005625 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5626 EmitDiags);
5627 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005628 }
5629 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
5630 if (ME->isArrow() &&
5631 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00005632 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
5633 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005634 }
5635 }
5636 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005637
Alexey Bataeve3727102018-04-18 15:57:46 +00005638 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005639 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00005640 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005641 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00005642 << S->getSourceRange();
5643 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005644 return true;
5645}
5646
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005647/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005648/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00005649static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005650 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00005651 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005652 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00005653 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005654 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005655 if ((Ctor->isCopyOrMoveConstructor() ||
5656 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5657 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005658 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005659 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
5660 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005661 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005662 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005663 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005664 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
5665 return getCanonicalDecl(ME->getMemberDecl());
5666 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005667}
5668
Alexey Bataeve3727102018-04-18 15:57:46 +00005669bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005670 // Check test-expr for canonical form, save upper-bound UB, flags for
5671 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00005672 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005673 // var relational-op b
5674 // b relational-op var
5675 //
Alexey Bataev1be63402019-09-11 15:44:06 +00005676 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005677 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00005678 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
5679 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005680 return true;
5681 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00005682 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005683 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005684 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00005685 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005686 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005687 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5688 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005689 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
5690 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5691 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005692 if (getInitLCDecl(BO->getRHS()) == LCDecl)
5693 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005694 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
5695 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
5696 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00005697 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
5698 return setUB(
5699 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
5700 /*LessOp=*/llvm::None,
5701 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00005702 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005703 if (CE->getNumArgs() == 2) {
5704 auto Op = CE->getOperator();
5705 switch (Op) {
5706 case OO_Greater:
5707 case OO_GreaterEqual:
5708 case OO_Less:
5709 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005710 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5711 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005712 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5713 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00005714 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
5715 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005716 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
5717 CE->getOperatorLoc());
5718 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005719 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00005720 if (IneqCondIsCanonical)
5721 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
5722 : CE->getArg(0),
5723 /*LessOp=*/llvm::None,
5724 /*StrictOp=*/true, CE->getSourceRange(),
5725 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00005726 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005727 default:
5728 break;
5729 }
5730 }
5731 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005732 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005733 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005734 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00005735 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005736 return true;
5737}
5738
Alexey Bataeve3727102018-04-18 15:57:46 +00005739bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005740 // RHS of canonical loop form increment can be:
5741 // var + incr
5742 // incr + var
5743 // var - incr
5744 //
5745 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005746 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005747 if (BO->isAdditiveOp()) {
5748 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005749 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5750 return setStep(BO->getRHS(), !IsAdd);
5751 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5752 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005753 }
David Majnemer9d168222016-08-05 17:44:54 +00005754 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005755 bool IsAdd = CE->getOperator() == OO_Plus;
5756 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005757 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5758 return setStep(CE->getArg(1), !IsAdd);
5759 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5760 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005761 }
5762 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005763 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005764 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005765 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005766 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005767 return true;
5768}
5769
Alexey Bataeve3727102018-04-18 15:57:46 +00005770bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005771 // Check incr-expr for canonical loop form and return true if it
5772 // does not conform.
5773 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5774 // ++var
5775 // var++
5776 // --var
5777 // var--
5778 // var += incr
5779 // var -= incr
5780 // var = var + incr
5781 // var = incr + var
5782 // var = var - incr
5783 //
5784 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005785 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005786 return true;
5787 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005788 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5789 if (!ExprTemp->cleanupsHaveSideEffects())
5790 S = ExprTemp->getSubExpr();
5791
Alexander Musmana5f070a2014-10-01 06:03:56 +00005792 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005793 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005794 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005795 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005796 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5797 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005798 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005799 (UO->isDecrementOp() ? -1 : 1))
5800 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005801 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005802 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005803 switch (BO->getOpcode()) {
5804 case BO_AddAssign:
5805 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005806 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5807 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005808 break;
5809 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005810 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5811 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005812 break;
5813 default:
5814 break;
5815 }
David Majnemer9d168222016-08-05 17:44:54 +00005816 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005817 switch (CE->getOperator()) {
5818 case OO_PlusPlus:
5819 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005820 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5821 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005822 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005823 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005824 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5825 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005826 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005827 break;
5828 case OO_PlusEqual:
5829 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005830 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5831 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005832 break;
5833 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005834 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5835 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005836 break;
5837 default:
5838 break;
5839 }
5840 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005841 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005842 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005843 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005844 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005845 return true;
5846}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005847
Alexey Bataev5a3af132016-03-29 08:58:54 +00005848static ExprResult
5849tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005850 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005851 if (SemaRef.CurContext->isDependentContext())
5852 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005853 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5854 return SemaRef.PerformImplicitConversion(
5855 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5856 /*AllowExplicit=*/true);
5857 auto I = Captures.find(Capture);
5858 if (I != Captures.end())
5859 return buildCapture(SemaRef, Capture, I->second);
5860 DeclRefExpr *Ref = nullptr;
5861 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5862 Captures[Capture] = Ref;
5863 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005864}
5865
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005866/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005867Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005868 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005869 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005870 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005871 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005872 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005873 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005874 Expr *LBVal = LB;
5875 Expr *UBVal = UB;
5876 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
5877 // max(LB(MinVal), LB(MaxVal))
5878 if (InitDependOnLC) {
5879 const LoopIterationSpace &IS =
5880 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5881 InitDependOnLC.getValueOr(
5882 CondDependOnLC.getValueOr(0))];
5883 if (!IS.MinValue || !IS.MaxValue)
5884 return nullptr;
5885 // OuterVar = Min
5886 ExprResult MinValue =
5887 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5888 if (!MinValue.isUsable())
5889 return nullptr;
5890
5891 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5892 IS.CounterVar, MinValue.get());
5893 if (!LBMinVal.isUsable())
5894 return nullptr;
5895 // OuterVar = Min, LBVal
5896 LBMinVal =
5897 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
5898 if (!LBMinVal.isUsable())
5899 return nullptr;
5900 // (OuterVar = Min, LBVal)
5901 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
5902 if (!LBMinVal.isUsable())
5903 return nullptr;
5904
5905 // OuterVar = Max
5906 ExprResult MaxValue =
5907 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5908 if (!MaxValue.isUsable())
5909 return nullptr;
5910
5911 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5912 IS.CounterVar, MaxValue.get());
5913 if (!LBMaxVal.isUsable())
5914 return nullptr;
5915 // OuterVar = Max, LBVal
5916 LBMaxVal =
5917 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
5918 if (!LBMaxVal.isUsable())
5919 return nullptr;
5920 // (OuterVar = Max, LBVal)
5921 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
5922 if (!LBMaxVal.isUsable())
5923 return nullptr;
5924
5925 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
5926 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
5927 if (!LBMin || !LBMax)
5928 return nullptr;
5929 // LB(MinVal) < LB(MaxVal)
5930 ExprResult MinLessMaxRes =
5931 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
5932 if (!MinLessMaxRes.isUsable())
5933 return nullptr;
5934 Expr *MinLessMax =
5935 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
5936 if (!MinLessMax)
5937 return nullptr;
5938 if (TestIsLessOp.getValue()) {
5939 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
5940 // LB(MaxVal))
5941 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
5942 MinLessMax, LBMin, LBMax);
5943 if (!MinLB.isUsable())
5944 return nullptr;
5945 LBVal = MinLB.get();
5946 } else {
5947 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
5948 // LB(MaxVal))
5949 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
5950 MinLessMax, LBMax, LBMin);
5951 if (!MaxLB.isUsable())
5952 return nullptr;
5953 LBVal = MaxLB.get();
5954 }
5955 }
5956 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
5957 // min(UB(MinVal), UB(MaxVal))
5958 if (CondDependOnLC) {
5959 const LoopIterationSpace &IS =
5960 ResultIterSpaces[ResultIterSpaces.size() - 1 -
5961 InitDependOnLC.getValueOr(
5962 CondDependOnLC.getValueOr(0))];
5963 if (!IS.MinValue || !IS.MaxValue)
5964 return nullptr;
5965 // OuterVar = Min
5966 ExprResult MinValue =
5967 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
5968 if (!MinValue.isUsable())
5969 return nullptr;
5970
5971 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5972 IS.CounterVar, MinValue.get());
5973 if (!UBMinVal.isUsable())
5974 return nullptr;
5975 // OuterVar = Min, UBVal
5976 UBMinVal =
5977 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
5978 if (!UBMinVal.isUsable())
5979 return nullptr;
5980 // (OuterVar = Min, UBVal)
5981 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
5982 if (!UBMinVal.isUsable())
5983 return nullptr;
5984
5985 // OuterVar = Max
5986 ExprResult MaxValue =
5987 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
5988 if (!MaxValue.isUsable())
5989 return nullptr;
5990
5991 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
5992 IS.CounterVar, MaxValue.get());
5993 if (!UBMaxVal.isUsable())
5994 return nullptr;
5995 // OuterVar = Max, UBVal
5996 UBMaxVal =
5997 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
5998 if (!UBMaxVal.isUsable())
5999 return nullptr;
6000 // (OuterVar = Max, UBVal)
6001 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6002 if (!UBMaxVal.isUsable())
6003 return nullptr;
6004
6005 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6006 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6007 if (!UBMin || !UBMax)
6008 return nullptr;
6009 // UB(MinVal) > UB(MaxVal)
6010 ExprResult MinGreaterMaxRes =
6011 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6012 if (!MinGreaterMaxRes.isUsable())
6013 return nullptr;
6014 Expr *MinGreaterMax =
6015 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6016 if (!MinGreaterMax)
6017 return nullptr;
6018 if (TestIsLessOp.getValue()) {
6019 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6020 // UB(MaxVal))
6021 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6022 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6023 if (!MaxUB.isUsable())
6024 return nullptr;
6025 UBVal = MaxUB.get();
6026 } else {
6027 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6028 // UB(MaxVal))
6029 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6030 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6031 if (!MinUB.isUsable())
6032 return nullptr;
6033 UBVal = MinUB.get();
6034 }
6035 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006036 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006037 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6038 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006039 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6040 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006041 if (!Upper || !Lower)
6042 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006043
6044 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6045
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006046 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006047 // BuildBinOp already emitted error, this one is to point user to upper
6048 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006049 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006050 << Upper->getSourceRange() << Lower->getSourceRange();
6051 return nullptr;
6052 }
6053 }
6054
6055 if (!Diff.isUsable())
6056 return nullptr;
6057
6058 // Upper - Lower [- 1]
6059 if (TestIsStrictOp)
6060 Diff = SemaRef.BuildBinOp(
6061 S, DefaultLoc, BO_Sub, Diff.get(),
6062 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6063 if (!Diff.isUsable())
6064 return nullptr;
6065
6066 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006067 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006068 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006069 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006070 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006071 if (!Diff.isUsable())
6072 return nullptr;
6073
6074 // Parentheses (for dumping/debugging purposes only).
6075 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6076 if (!Diff.isUsable())
6077 return nullptr;
6078
6079 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006080 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006081 if (!Diff.isUsable())
6082 return nullptr;
6083
Alexander Musman174b3ca2014-10-06 11:16:29 +00006084 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006085 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006086 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006087 bool UseVarType = VarType->hasIntegerRepresentation() &&
6088 C.getTypeSize(Type) > C.getTypeSize(VarType);
6089 if (!Type->isIntegerType() || UseVarType) {
6090 unsigned NewSize =
6091 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6092 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6093 : Type->hasSignedIntegerRepresentation();
6094 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006095 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6096 Diff = SemaRef.PerformImplicitConversion(
6097 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6098 if (!Diff.isUsable())
6099 return nullptr;
6100 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006101 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006102 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006103 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6104 if (NewSize != C.getTypeSize(Type)) {
6105 if (NewSize < C.getTypeSize(Type)) {
6106 assert(NewSize == 64 && "incorrect loop var size");
6107 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6108 << InitSrcRange << ConditionSrcRange;
6109 }
6110 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006111 NewSize, Type->hasSignedIntegerRepresentation() ||
6112 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006113 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6114 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6115 Sema::AA_Converting, true);
6116 if (!Diff.isUsable())
6117 return nullptr;
6118 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006119 }
6120 }
6121
Alexander Musmana5f070a2014-10-01 06:03:56 +00006122 return Diff.get();
6123}
6124
Alexey Bataevf8be4762019-08-14 19:30:06 +00006125std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6126 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6127 // Do not build for iterators, they cannot be used in non-rectangular loop
6128 // nests.
6129 if (LCDecl->getType()->isRecordType())
6130 return std::make_pair(nullptr, nullptr);
6131 // If we subtract, the min is in the condition, otherwise the min is in the
6132 // init value.
6133 Expr *MinExpr = nullptr;
6134 Expr *MaxExpr = nullptr;
6135 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6136 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6137 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6138 : CondDependOnLC.hasValue();
6139 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6140 : InitDependOnLC.hasValue();
6141 Expr *Lower =
6142 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6143 Expr *Upper =
6144 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6145 if (!Upper || !Lower)
6146 return std::make_pair(nullptr, nullptr);
6147
6148 if (TestIsLessOp.getValue())
6149 MinExpr = Lower;
6150 else
6151 MaxExpr = Upper;
6152
6153 // Build minimum/maximum value based on number of iterations.
6154 ExprResult Diff;
6155 QualType VarType = LCDecl->getType().getNonReferenceType();
6156
6157 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6158 if (!Diff.isUsable())
6159 return std::make_pair(nullptr, nullptr);
6160
6161 // Upper - Lower [- 1]
6162 if (TestIsStrictOp)
6163 Diff = SemaRef.BuildBinOp(
6164 S, DefaultLoc, BO_Sub, Diff.get(),
6165 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6166 if (!Diff.isUsable())
6167 return std::make_pair(nullptr, nullptr);
6168
6169 // Upper - Lower [- 1] + Step
6170 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6171 if (!NewStep.isUsable())
6172 return std::make_pair(nullptr, nullptr);
6173
6174 // Parentheses (for dumping/debugging purposes only).
6175 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6176 if (!Diff.isUsable())
6177 return std::make_pair(nullptr, nullptr);
6178
6179 // (Upper - Lower [- 1]) / Step
6180 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6181 if (!Diff.isUsable())
6182 return std::make_pair(nullptr, nullptr);
6183
6184 // ((Upper - Lower [- 1]) / Step) * Step
6185 // Parentheses (for dumping/debugging purposes only).
6186 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6187 if (!Diff.isUsable())
6188 return std::make_pair(nullptr, nullptr);
6189
6190 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6191 if (!Diff.isUsable())
6192 return std::make_pair(nullptr, nullptr);
6193
6194 // Convert to the original type or ptrdiff_t, if original type is pointer.
6195 if (!VarType->isAnyPointerType() &&
6196 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6197 Diff = SemaRef.PerformImplicitConversion(
6198 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6199 } else if (VarType->isAnyPointerType() &&
6200 !SemaRef.Context.hasSameType(
6201 Diff.get()->getType(),
6202 SemaRef.Context.getUnsignedPointerDiffType())) {
6203 Diff = SemaRef.PerformImplicitConversion(
6204 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6205 Sema::AA_Converting, /*AllowExplicit=*/true);
6206 }
6207 if (!Diff.isUsable())
6208 return std::make_pair(nullptr, nullptr);
6209
6210 // Parentheses (for dumping/debugging purposes only).
6211 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6212 if (!Diff.isUsable())
6213 return std::make_pair(nullptr, nullptr);
6214
6215 if (TestIsLessOp.getValue()) {
6216 // MinExpr = Lower;
6217 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6218 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6219 if (!Diff.isUsable())
6220 return std::make_pair(nullptr, nullptr);
6221 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6222 if (!Diff.isUsable())
6223 return std::make_pair(nullptr, nullptr);
6224 MaxExpr = Diff.get();
6225 } else {
6226 // MaxExpr = Upper;
6227 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6228 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6229 if (!Diff.isUsable())
6230 return std::make_pair(nullptr, nullptr);
6231 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6232 if (!Diff.isUsable())
6233 return std::make_pair(nullptr, nullptr);
6234 MinExpr = Diff.get();
6235 }
6236
6237 return std::make_pair(MinExpr, MaxExpr);
6238}
6239
6240Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6241 if (InitDependOnLC || CondDependOnLC)
6242 return Condition;
6243 return nullptr;
6244}
6245
Alexey Bataeve3727102018-04-18 15:57:46 +00006246Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006247 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006248 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006249 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006250 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006251
Alexey Bataevf8be4762019-08-14 19:30:06 +00006252 ExprResult NewLB =
6253 InitDependOnLC ? LB : tryBuildCapture(SemaRef, LB, Captures);
6254 ExprResult NewUB =
6255 CondDependOnLC ? UB : tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006256 if (!NewLB.isUsable() || !NewUB.isUsable())
6257 return nullptr;
6258
Alexey Bataeve3727102018-04-18 15:57:46 +00006259 ExprResult CondExpr =
6260 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006261 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006262 (TestIsStrictOp ? BO_LT : BO_LE) :
6263 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006264 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006265 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006266 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6267 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006268 CondExpr = SemaRef.PerformImplicitConversion(
6269 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6270 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006271 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006272
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006273 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006274 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6275}
6276
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006277/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006278DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006279 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6280 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006281 auto *VD = dyn_cast<VarDecl>(LCDecl);
6282 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006283 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6284 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006285 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006286 const DSAStackTy::DSAVarData Data =
6287 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006288 // If the loop control decl is explicitly marked as private, do not mark it
6289 // as captured again.
6290 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6291 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006292 return Ref;
6293 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006294 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006295}
6296
Alexey Bataeve3727102018-04-18 15:57:46 +00006297Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006298 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006299 QualType Type = LCDecl->getType().getNonReferenceType();
6300 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006301 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6302 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6303 isa<VarDecl>(LCDecl)
6304 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6305 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006306 if (PrivateVar->isInvalidDecl())
6307 return nullptr;
6308 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6309 }
6310 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006311}
6312
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006313/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006314Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006315
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006316/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006317Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006318
Alexey Bataevf138fda2018-08-13 19:04:24 +00006319Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6320 Scope *S, Expr *Counter,
6321 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6322 Expr *Inc, OverloadedOperatorKind OOK) {
6323 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6324 if (!Cnt)
6325 return nullptr;
6326 if (Inc) {
6327 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6328 "Expected only + or - operations for depend clauses.");
6329 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6330 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6331 if (!Cnt)
6332 return nullptr;
6333 }
6334 ExprResult Diff;
6335 QualType VarType = LCDecl->getType().getNonReferenceType();
6336 if (VarType->isIntegerType() || VarType->isPointerType() ||
6337 SemaRef.getLangOpts().CPlusPlus) {
6338 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006339 Expr *Upper = TestIsLessOp.getValue()
6340 ? Cnt
6341 : tryBuildCapture(SemaRef, UB, Captures).get();
6342 Expr *Lower = TestIsLessOp.getValue()
6343 ? tryBuildCapture(SemaRef, LB, Captures).get()
6344 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006345 if (!Upper || !Lower)
6346 return nullptr;
6347
6348 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6349
6350 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6351 // BuildBinOp already emitted error, this one is to point user to upper
6352 // and lower bound, and to tell what is passed to 'operator-'.
6353 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6354 << Upper->getSourceRange() << Lower->getSourceRange();
6355 return nullptr;
6356 }
6357 }
6358
6359 if (!Diff.isUsable())
6360 return nullptr;
6361
6362 // Parentheses (for dumping/debugging purposes only).
6363 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6364 if (!Diff.isUsable())
6365 return nullptr;
6366
6367 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6368 if (!NewStep.isUsable())
6369 return nullptr;
6370 // (Upper - Lower) / Step
6371 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6372 if (!Diff.isUsable())
6373 return nullptr;
6374
6375 return Diff.get();
6376}
Alexey Bataev23b69422014-06-18 07:08:49 +00006377} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006378
Alexey Bataev9c821032015-04-30 04:23:23 +00006379void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6380 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6381 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006382 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6383 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006384 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006385 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006386 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006387 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6388 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006389 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006390 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006391 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006392 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006393 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006395 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6396 /*WithInit=*/false);
6397 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006398 }
6399 }
6400 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006401 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6402 if (LD != D->getCanonicalDecl()) {
6403 DSAStack->resetPossibleLoopCounter();
6404 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6405 MarkDeclarationsReferencedInExpr(
6406 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6407 Var->getType().getNonLValueExprType(Context),
6408 ForLoc, /*RefersToCapture=*/true));
6409 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006410 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6411 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6412 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6413 // associated for-loop of a simd construct with just one associated
6414 // for-loop may be listed in a linear clause with a constant-linear-step
6415 // that is the increment of the associated for-loop. The loop iteration
6416 // variable(s) in the associated for-loop(s) of a for or parallel for
6417 // construct may be listed in a private or lastprivate clause.
6418 DSAStackTy::DSAVarData DVar =
6419 DSAStack->getTopDSA(D, /*FromParent=*/false);
6420 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6421 // is declared in the loop and it is predetermined as a private.
6422 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6423 OpenMPClauseKind PredeterminedCKind =
6424 isOpenMPSimdDirective(DKind)
6425 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6426 : OMPC_private;
6427 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6428 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6429 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6430 DVar.CKind != OMPC_private))) ||
6431 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
6432 isOpenMPDistributeDirective(DKind)) &&
6433 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6434 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6435 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6436 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6437 << getOpenMPClauseName(DVar.CKind)
6438 << getOpenMPDirectiveName(DKind)
6439 << getOpenMPClauseName(PredeterminedCKind);
6440 if (DVar.RefExpr == nullptr)
6441 DVar.CKind = PredeterminedCKind;
6442 reportOriginalDsa(*this, DSAStack, D, DVar,
6443 /*IsLoopIterVar=*/true);
6444 } else if (LoopDeclRefExpr) {
6445 // Make the loop iteration variable private (for worksharing
6446 // constructs), linear (for simd directives with the only one
6447 // associated loop) or lastprivate (for simd directives with several
6448 // collapsed or ordered loops).
6449 if (DVar.CKind == OMPC_unknown)
6450 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6451 PrivateRef);
6452 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006453 }
6454 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006455 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006456 }
6457}
6458
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006459/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006460/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006461static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006462 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6463 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006464 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
6465 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00006466 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006467 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00006468 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006469 // OpenMP [2.6, Canonical Loop Form]
6470 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00006471 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006472 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006473 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006474 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00006475 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00006476 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006477 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00006478 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
6479 SemaRef.Diag(DSA.getConstructLoc(),
6480 diag::note_omp_collapse_ordered_expr)
6481 << 2 << CollapseLoopCountExpr->getSourceRange()
6482 << OrderedLoopCountExpr->getSourceRange();
6483 else if (CollapseLoopCountExpr)
6484 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6485 diag::note_omp_collapse_ordered_expr)
6486 << 0 << CollapseLoopCountExpr->getSourceRange();
6487 else
6488 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6489 diag::note_omp_collapse_ordered_expr)
6490 << 1 << OrderedLoopCountExpr->getSourceRange();
6491 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006492 return true;
6493 }
6494 assert(For->getBody());
6495
Alexey Bataev622af1d2019-04-24 19:58:30 +00006496 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006497
6498 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00006499 Stmt *Init = For->getInit();
6500 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006501 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006502
6503 bool HasErrors = false;
6504
6505 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006506 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006507 // OpenMP [2.6, Canonical Loop Form]
6508 // Var is one of the following:
6509 // A variable of signed or unsigned integer type.
6510 // For C++, a variable of a random access iterator type.
6511 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00006512 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006513 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
6514 !VarType->isPointerType() &&
6515 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006516 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006517 << SemaRef.getLangOpts().CPlusPlus;
6518 HasErrors = true;
6519 }
6520
6521 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
6522 // a Construct
6523 // The loop iteration variable(s) in the associated for-loop(s) of a for or
6524 // parallel for construct is (are) private.
6525 // The loop iteration variable in the associated for-loop of a simd
6526 // construct with just one associated for-loop is linear with a
6527 // constant-linear-step that is the increment of the associated for-loop.
6528 // Exclude loop var from the list of variables with implicitly defined data
6529 // sharing attributes.
6530 VarsWithImplicitDSA.erase(LCDecl);
6531
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006532 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
6533
6534 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00006535 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006536
6537 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00006538 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006539 }
6540
Alexey Bataeve3727102018-04-18 15:57:46 +00006541 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006542 return HasErrors;
6543
Alexander Musmana5f070a2014-10-01 06:03:56 +00006544 // Build the loop's iteration space representation.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006545 ResultIterSpaces[CurrentNestedLoopCount].PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00006546 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00006547 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
6548 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
6549 (isOpenMPWorksharingDirective(DKind) ||
6550 isOpenMPTaskLoopDirective(DKind) ||
6551 isOpenMPDistributeDirective(DKind)),
6552 Captures);
6553 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
6554 ISC.buildCounterVar(Captures, DSA);
6555 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
6556 ISC.buildPrivateCounterVar();
6557 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
6558 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
6559 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
6560 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
6561 ISC.getConditionSrcRange();
6562 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
6563 ISC.getIncrementSrcRange();
6564 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
6565 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
6566 ISC.isStrictTestOp();
6567 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
6568 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
6569 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
6570 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
6571 ISC.buildFinalCondition(DSA.getCurScope());
6572 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
6573 ISC.doesInitDependOnLC();
6574 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
6575 ISC.doesCondDependOnLC();
6576 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
6577 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006578
Alexey Bataevf8be4762019-08-14 19:30:06 +00006579 HasErrors |=
6580 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
6581 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
6582 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
6583 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
6584 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
6585 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006586 if (!HasErrors && DSA.isOrderedRegion()) {
6587 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
6588 if (CurrentNestedLoopCount <
6589 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
6590 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006591 CurrentNestedLoopCount,
6592 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006593 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006594 CurrentNestedLoopCount,
6595 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00006596 }
6597 }
6598 for (auto &Pair : DSA.getDoacrossDependClauses()) {
6599 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
6600 // Erroneous case - clause has some problems.
6601 continue;
6602 }
6603 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
6604 Pair.second.size() <= CurrentNestedLoopCount) {
6605 // Erroneous case - clause has some problems.
6606 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
6607 continue;
6608 }
6609 Expr *CntValue;
6610 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
6611 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006612 DSA.getCurScope(),
6613 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006614 Pair.first->getDependencyLoc());
6615 else
6616 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006617 DSA.getCurScope(),
6618 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006619 Pair.first->getDependencyLoc(),
6620 Pair.second[CurrentNestedLoopCount].first,
6621 Pair.second[CurrentNestedLoopCount].second);
6622 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
6623 }
6624 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006625
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006626 return HasErrors;
6627}
6628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006629/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00006630static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00006631buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006632 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006633 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006634 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006635 ExprResult NewStart = IsNonRectangularLB
6636 ? Start.get()
6637 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006638 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006639 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00006640 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00006641 VarRef.get()->getType())) {
6642 NewStart = SemaRef.PerformImplicitConversion(
6643 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
6644 /*AllowExplicit=*/true);
6645 if (!NewStart.isUsable())
6646 return ExprError();
6647 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006648
Alexey Bataeve3727102018-04-18 15:57:46 +00006649 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006650 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6651 return Init;
6652}
6653
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006654/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00006655static ExprResult buildCounterUpdate(
6656 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
6657 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006658 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00006659 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006660 // Add parentheses (for debugging purposes only).
6661 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
6662 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
6663 !Step.isUsable())
6664 return ExprError();
6665
Alexey Bataev5a3af132016-03-29 08:58:54 +00006666 ExprResult NewStep = Step;
6667 if (Captures)
6668 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006669 if (NewStep.isInvalid())
6670 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006671 ExprResult Update =
6672 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006673 if (!Update.isUsable())
6674 return ExprError();
6675
Alexey Bataevc0214e02016-02-16 12:13:49 +00006676 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
6677 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00006678 if (!Start.isUsable())
6679 return ExprError();
6680 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
6681 if (!NewStart.isUsable())
6682 return ExprError();
6683 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006684 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006685 if (NewStart.isInvalid())
6686 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006687
Alexey Bataevc0214e02016-02-16 12:13:49 +00006688 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
6689 ExprResult SavedUpdate = Update;
6690 ExprResult UpdateVal;
6691 if (VarRef.get()->getType()->isOverloadableType() ||
6692 NewStart.get()->getType()->isOverloadableType() ||
6693 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006694 Sema::TentativeAnalysisScope Trap(SemaRef);
6695
Alexey Bataevc0214e02016-02-16 12:13:49 +00006696 Update =
6697 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
6698 if (Update.isUsable()) {
6699 UpdateVal =
6700 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
6701 VarRef.get(), SavedUpdate.get());
6702 if (UpdateVal.isUsable()) {
6703 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
6704 UpdateVal.get());
6705 }
6706 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006707 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006708
Alexey Bataevc0214e02016-02-16 12:13:49 +00006709 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
6710 if (!Update.isUsable() || !UpdateVal.isUsable()) {
6711 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
6712 NewStart.get(), SavedUpdate.get());
6713 if (!Update.isUsable())
6714 return ExprError();
6715
Alexey Bataev11481f52016-02-17 10:29:05 +00006716 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
6717 VarRef.get()->getType())) {
6718 Update = SemaRef.PerformImplicitConversion(
6719 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
6720 if (!Update.isUsable())
6721 return ExprError();
6722 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00006723
6724 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
6725 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006726 return Update;
6727}
6728
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006729/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006730/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006731static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006732 if (E == nullptr)
6733 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006734 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006735 QualType OldType = E->getType();
6736 unsigned HasBits = C.getTypeSize(OldType);
6737 if (HasBits >= Bits)
6738 return ExprResult(E);
6739 // OK to convert to signed, because new type has more bits than old.
6740 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
6741 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
6742 true);
6743}
6744
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006745/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00006746/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00006747static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006748 if (E == nullptr)
6749 return false;
6750 llvm::APSInt Result;
6751 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
6752 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
6753 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006754}
6755
Alexey Bataev5a3af132016-03-29 08:58:54 +00006756/// Build preinits statement for the given declarations.
6757static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00006758 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006759 if (!PreInits.empty()) {
6760 return new (Context) DeclStmt(
6761 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
6762 SourceLocation(), SourceLocation());
6763 }
6764 return nullptr;
6765}
6766
6767/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00006768static Stmt *
6769buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00006770 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006771 if (!Captures.empty()) {
6772 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00006773 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00006774 PreInits.push_back(Pair.second->getDecl());
6775 return buildPreInits(Context, PreInits);
6776 }
6777 return nullptr;
6778}
6779
6780/// Build postupdate expression for the given list of postupdates expressions.
6781static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
6782 Expr *PostUpdate = nullptr;
6783 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006784 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006785 Expr *ConvE = S.BuildCStyleCastExpr(
6786 E->getExprLoc(),
6787 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
6788 E->getExprLoc(), E)
6789 .get();
6790 PostUpdate = PostUpdate
6791 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
6792 PostUpdate, ConvE)
6793 .get()
6794 : ConvE;
6795 }
6796 }
6797 return PostUpdate;
6798}
6799
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006800/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00006801/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
6802/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006803static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00006804checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00006805 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
6806 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00006807 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00006808 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006809 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006810 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006811 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006812 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006813 if (!CollapseLoopCountExpr->isValueDependent() &&
6814 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006815 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006816 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006817 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006818 return 1;
6819 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00006820 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006821 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006822 if (OrderedLoopCountExpr) {
6823 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00006824 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006825 if (!OrderedLoopCountExpr->isValueDependent() &&
6826 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
6827 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00006828 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006829 if (Result.getLimitedValue() < NestedLoopCount) {
6830 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
6831 diag::err_omp_wrong_ordered_loop_count)
6832 << OrderedLoopCountExpr->getSourceRange();
6833 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
6834 diag::note_collapse_loop_count)
6835 << CollapseLoopCountExpr->getSourceRange();
6836 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006837 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006838 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00006839 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00006840 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00006841 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006842 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006843 // This is helper routine for loop directives (e.g., 'for', 'simd',
6844 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00006845 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00006846 SmallVector<LoopIterationSpace, 4> IterSpaces(
6847 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00006848 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006849 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006850 if (checkOpenMPIterationSpace(
6851 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6852 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006853 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00006854 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006855 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006856 // OpenMP [2.8.1, simd construct, Restrictions]
6857 // All loops associated with the construct must be perfectly nested; that
6858 // is, there must be no intervening code nor any OpenMP directive between
6859 // any two loops.
6860 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006861 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00006862 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
6863 if (checkOpenMPIterationSpace(
6864 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
6865 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00006866 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00006867 return 0;
6868 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
6869 // Handle initialization of captured loop iterator variables.
6870 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
6871 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
6872 Captures[DRE] = DRE;
6873 }
6874 }
6875 // Move on to the next nested for loop, or to the loop body.
6876 // OpenMP [2.8.1, simd construct, Restrictions]
6877 // All loops associated with the construct must be perfectly nested; that
6878 // is, there must be no intervening code nor any OpenMP directive between
6879 // any two loops.
6880 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
6881 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006882
Alexander Musmana5f070a2014-10-01 06:03:56 +00006883 Built.clear(/* size */ NestedLoopCount);
6884
6885 if (SemaRef.CurContext->isDependentContext())
6886 return NestedLoopCount;
6887
6888 // An example of what is generated for the following code:
6889 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00006890 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006891 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00006892 // for (k = 0; k < NK; ++k)
6893 // for (j = J0; j < NJ; j+=2) {
6894 // <loop body>
6895 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006896 //
6897 // We generate the code below.
6898 // Note: the loop body may be outlined in CodeGen.
6899 // Note: some counters may be C++ classes, operator- is used to find number of
6900 // iterations and operator+= to calculate counter value.
6901 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
6902 // or i64 is currently supported).
6903 //
6904 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
6905 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
6906 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
6907 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
6908 // // similar updates for vars in clauses (e.g. 'linear')
6909 // <loop body (using local i and j)>
6910 // }
6911 // i = NI; // assign final values of counters
6912 // j = NJ;
6913 //
6914
6915 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
6916 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006917 // Precondition tests if there is at least one iteration (all conditions are
6918 // true).
6919 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00006920 Expr *N0 = IterSpaces[0].NumIterations;
6921 ExprResult LastIteration32 =
6922 widenIterationCount(/*Bits=*/32,
6923 SemaRef
6924 .PerformImplicitConversion(
6925 N0->IgnoreImpCasts(), N0->getType(),
6926 Sema::AA_Converting, /*AllowExplicit=*/true)
6927 .get(),
6928 SemaRef);
6929 ExprResult LastIteration64 = widenIterationCount(
6930 /*Bits=*/64,
6931 SemaRef
6932 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
6933 Sema::AA_Converting,
6934 /*AllowExplicit=*/true)
6935 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006936 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006937
6938 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
6939 return NestedLoopCount;
6940
Alexey Bataeve3727102018-04-18 15:57:46 +00006941 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006942 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
6943
6944 Scope *CurScope = DSA.getCurScope();
6945 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00006946 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00006947 PreCond =
6948 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
6949 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00006950 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006951 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00006952 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006953 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
6954 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006955 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006956 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006957 SemaRef
6958 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6959 Sema::AA_Converting,
6960 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006961 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006962 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006963 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00006964 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00006965 SemaRef
6966 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
6967 Sema::AA_Converting,
6968 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006969 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006970 }
6971
6972 // Choose either the 32-bit or 64-bit version.
6973 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006974 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
6975 (LastIteration32.isUsable() &&
6976 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
6977 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
6978 fitsInto(
6979 /*Bits=*/32,
6980 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
6981 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00006982 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00006983 QualType VType = LastIteration.get()->getType();
6984 QualType RealVType = VType;
6985 QualType StrideVType = VType;
6986 if (isOpenMPTaskLoopDirective(DKind)) {
6987 VType =
6988 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
6989 StrideVType =
6990 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
6991 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006992
6993 if (!LastIteration.isUsable())
6994 return 0;
6995
6996 // Save the number of iterations.
6997 ExprResult NumIterations = LastIteration;
6998 {
6999 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007000 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7001 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007002 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7003 if (!LastIteration.isUsable())
7004 return 0;
7005 }
7006
7007 // Calculate the last iteration number beforehand instead of doing this on
7008 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7009 llvm::APSInt Result;
7010 bool IsConstant =
7011 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7012 ExprResult CalcLastIteration;
7013 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007014 ExprResult SaveRef =
7015 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007016 LastIteration = SaveRef;
7017
7018 // Prepare SaveRef + 1.
7019 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007020 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007021 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7022 if (!NumIterations.isUsable())
7023 return 0;
7024 }
7025
7026 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7027
David Majnemer9d168222016-08-05 17:44:54 +00007028 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007029 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007030 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7031 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007032 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007033 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7034 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007035 SemaRef.AddInitializerToDecl(LBDecl,
7036 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7037 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007038
7039 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007040 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7041 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007042 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007043 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007044
7045 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7046 // This will be used to implement clause 'lastprivate'.
7047 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007048 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7049 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007050 SemaRef.AddInitializerToDecl(ILDecl,
7051 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7052 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007053
7054 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007055 VarDecl *STDecl =
7056 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7057 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007058 SemaRef.AddInitializerToDecl(STDecl,
7059 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7060 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007061
7062 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007063 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007064 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7065 UB.get(), LastIteration.get());
7066 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007067 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7068 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007069 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7070 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007071 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007072
7073 // If we have a combined directive that combines 'distribute', 'for' or
7074 // 'simd' we need to be able to access the bounds of the schedule of the
7075 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7076 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7077 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007078 // Lower bound variable, initialized with zero.
7079 VarDecl *CombLBDecl =
7080 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7081 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7082 SemaRef.AddInitializerToDecl(
7083 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7084 /*DirectInit*/ false);
7085
7086 // Upper bound variable, initialized with last iteration number.
7087 VarDecl *CombUBDecl =
7088 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7089 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7090 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7091 /*DirectInit*/ false);
7092
7093 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7094 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7095 ExprResult CombCondOp =
7096 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7097 LastIteration.get(), CombUB.get());
7098 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7099 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007100 CombEUB =
7101 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007102
Alexey Bataeve3727102018-04-18 15:57:46 +00007103 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007104 // We expect to have at least 2 more parameters than the 'parallel'
7105 // directive does - the lower and upper bounds of the previous schedule.
7106 assert(CD->getNumParams() >= 4 &&
7107 "Unexpected number of parameters in loop combined directive");
7108
7109 // Set the proper type for the bounds given what we learned from the
7110 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007111 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7112 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007113
7114 // Previous lower and upper bounds are obtained from the region
7115 // parameters.
7116 PrevLB =
7117 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7118 PrevUB =
7119 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7120 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007121 }
7122
7123 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007124 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007125 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007126 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007127 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7128 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007129 Expr *RHS =
7130 (isOpenMPWorksharingDirective(DKind) ||
7131 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7132 ? LB.get()
7133 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007134 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007135 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007136
7137 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7138 Expr *CombRHS =
7139 (isOpenMPWorksharingDirective(DKind) ||
7140 isOpenMPTaskLoopDirective(DKind) ||
7141 isOpenMPDistributeDirective(DKind))
7142 ? CombLB.get()
7143 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7144 CombInit =
7145 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007146 CombInit =
7147 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007148 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007149 }
7150
Alexey Bataev316ccf62019-01-29 18:51:58 +00007151 bool UseStrictCompare =
7152 RealVType->hasUnsignedIntegerRepresentation() &&
7153 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7154 return LIS.IsStrictCompare;
7155 });
7156 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7157 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007158 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007159 Expr *BoundUB = UB.get();
7160 if (UseStrictCompare) {
7161 BoundUB =
7162 SemaRef
7163 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7164 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7165 .get();
7166 BoundUB =
7167 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7168 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007169 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007170 (isOpenMPWorksharingDirective(DKind) ||
7171 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007172 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7173 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7174 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007175 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7176 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007177 ExprResult CombDistCond;
7178 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007179 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7180 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007181 }
7182
Carlo Bertolliffafe102017-04-20 00:39:39 +00007183 ExprResult CombCond;
7184 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007185 Expr *BoundCombUB = CombUB.get();
7186 if (UseStrictCompare) {
7187 BoundCombUB =
7188 SemaRef
7189 .BuildBinOp(
7190 CurScope, CondLoc, BO_Add, BoundCombUB,
7191 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7192 .get();
7193 BoundCombUB =
7194 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7195 .get();
7196 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007197 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007198 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7199 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007200 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007201 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007202 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007203 ExprResult Inc =
7204 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7205 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7206 if (!Inc.isUsable())
7207 return 0;
7208 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007209 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007210 if (!Inc.isUsable())
7211 return 0;
7212
7213 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7214 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007215 // In combined construct, add combined version that use CombLB and CombUB
7216 // base variables for the update
7217 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007218 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7219 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007220 // LB + ST
7221 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7222 if (!NextLB.isUsable())
7223 return 0;
7224 // LB = LB + ST
7225 NextLB =
7226 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007227 NextLB =
7228 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007229 if (!NextLB.isUsable())
7230 return 0;
7231 // UB + ST
7232 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7233 if (!NextUB.isUsable())
7234 return 0;
7235 // UB = UB + ST
7236 NextUB =
7237 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007238 NextUB =
7239 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007240 if (!NextUB.isUsable())
7241 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007242 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7243 CombNextLB =
7244 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7245 if (!NextLB.isUsable())
7246 return 0;
7247 // LB = LB + ST
7248 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7249 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007250 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7251 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007252 if (!CombNextLB.isUsable())
7253 return 0;
7254 // UB + ST
7255 CombNextUB =
7256 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7257 if (!CombNextUB.isUsable())
7258 return 0;
7259 // UB = UB + ST
7260 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7261 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007262 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7263 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007264 if (!CombNextUB.isUsable())
7265 return 0;
7266 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007267 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007268
Carlo Bertolliffafe102017-04-20 00:39:39 +00007269 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007270 // directive with for as IV = IV + ST; ensure upper bound expression based
7271 // on PrevUB instead of NumIterations - used to implement 'for' when found
7272 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007273 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007274 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007275 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007276 DistCond = SemaRef.BuildBinOp(
7277 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007278 assert(DistCond.isUsable() && "distribute cond expr was not built");
7279
7280 DistInc =
7281 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7282 assert(DistInc.isUsable() && "distribute inc expr was not built");
7283 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7284 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007285 DistInc =
7286 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007287 assert(DistInc.isUsable() && "distribute inc expr was not built");
7288
7289 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7290 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007291 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007292 ExprResult IsUBGreater =
7293 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7294 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7295 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7296 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7297 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007298 PrevEUB =
7299 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007300
Alexey Bataev316ccf62019-01-29 18:51:58 +00007301 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7302 // parallel for is in combination with a distribute directive with
7303 // schedule(static, 1)
7304 Expr *BoundPrevUB = PrevUB.get();
7305 if (UseStrictCompare) {
7306 BoundPrevUB =
7307 SemaRef
7308 .BuildBinOp(
7309 CurScope, CondLoc, BO_Add, BoundPrevUB,
7310 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7311 .get();
7312 BoundPrevUB =
7313 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7314 .get();
7315 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007316 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007317 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7318 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007319 }
7320
Alexander Musmana5f070a2014-10-01 06:03:56 +00007321 // Build updates and final values of the loop counters.
7322 bool HasErrors = false;
7323 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007324 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007325 Built.Updates.resize(NestedLoopCount);
7326 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007327 Built.DependentCounters.resize(NestedLoopCount);
7328 Built.DependentInits.resize(NestedLoopCount);
7329 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007330 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007331 // We implement the following algorithm for obtaining the
7332 // original loop iteration variable values based on the
7333 // value of the collapsed loop iteration variable IV.
7334 //
7335 // Let n+1 be the number of collapsed loops in the nest.
7336 // Iteration variables (I0, I1, .... In)
7337 // Iteration counts (N0, N1, ... Nn)
7338 //
7339 // Acc = IV;
7340 //
7341 // To compute Ik for loop k, 0 <= k <= n, generate:
7342 // Prod = N(k+1) * N(k+2) * ... * Nn;
7343 // Ik = Acc / Prod;
7344 // Acc -= Ik * Prod;
7345 //
7346 ExprResult Acc = IV;
7347 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007348 LoopIterationSpace &IS = IterSpaces[Cnt];
7349 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007350 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007351
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007352 // Compute prod
7353 ExprResult Prod =
7354 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7355 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7356 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7357 IterSpaces[K].NumIterations);
7358
7359 // Iter = Acc / Prod
7360 // If there is at least one more inner loop to avoid
7361 // multiplication by 1.
7362 if (Cnt + 1 < NestedLoopCount)
7363 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7364 Acc.get(), Prod.get());
7365 else
7366 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007367 if (!Iter.isUsable()) {
7368 HasErrors = true;
7369 break;
7370 }
7371
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007372 // Update Acc:
7373 // Acc -= Iter * Prod
7374 // Check if there is at least one more inner loop to avoid
7375 // multiplication by 1.
7376 if (Cnt + 1 < NestedLoopCount)
7377 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7378 Iter.get(), Prod.get());
7379 else
7380 Prod = Iter;
7381 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7382 Acc.get(), Prod.get());
7383
Alexey Bataev39f915b82015-05-08 10:41:21 +00007384 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007385 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007386 DeclRefExpr *CounterVar = buildDeclRefExpr(
7387 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7388 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007389 ExprResult Init =
7390 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7391 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007392 if (!Init.isUsable()) {
7393 HasErrors = true;
7394 break;
7395 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007396 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007397 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007398 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007399 if (!Update.isUsable()) {
7400 HasErrors = true;
7401 break;
7402 }
7403
7404 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007405 ExprResult Final =
7406 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7407 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7408 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007409 if (!Final.isUsable()) {
7410 HasErrors = true;
7411 break;
7412 }
7413
Alexander Musmana5f070a2014-10-01 06:03:56 +00007414 if (!Update.isUsable() || !Final.isUsable()) {
7415 HasErrors = true;
7416 break;
7417 }
7418 // Save results
7419 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007420 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007421 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007422 Built.Updates[Cnt] = Update.get();
7423 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007424 Built.DependentCounters[Cnt] = nullptr;
7425 Built.DependentInits[Cnt] = nullptr;
7426 Built.FinalsConditions[Cnt] = nullptr;
7427 if (IS.IsNonRectangularLB) {
7428 Built.DependentCounters[Cnt] =
7429 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7430 Built.DependentInits[Cnt] =
7431 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7432 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7433 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007434 }
7435 }
7436
7437 if (HasErrors)
7438 return 0;
7439
7440 // Save results
7441 Built.IterationVarRef = IV.get();
7442 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007443 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007444 Built.CalcLastIteration = SemaRef
7445 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00007446 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007447 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007448 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00007449 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007450 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007451 Built.Init = Init.get();
7452 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007453 Built.LB = LB.get();
7454 Built.UB = UB.get();
7455 Built.IL = IL.get();
7456 Built.ST = ST.get();
7457 Built.EUB = EUB.get();
7458 Built.NLB = NextLB.get();
7459 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007460 Built.PrevLB = PrevLB.get();
7461 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007462 Built.DistInc = DistInc.get();
7463 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00007464 Built.DistCombinedFields.LB = CombLB.get();
7465 Built.DistCombinedFields.UB = CombUB.get();
7466 Built.DistCombinedFields.EUB = CombEUB.get();
7467 Built.DistCombinedFields.Init = CombInit.get();
7468 Built.DistCombinedFields.Cond = CombCond.get();
7469 Built.DistCombinedFields.NLB = CombNextLB.get();
7470 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007471 Built.DistCombinedFields.DistCond = CombDistCond.get();
7472 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007473
Alexey Bataevabfc0692014-06-25 06:52:00 +00007474 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007475}
7476
Alexey Bataev10e775f2015-07-30 11:36:16 +00007477static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007478 auto CollapseClauses =
7479 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
7480 if (CollapseClauses.begin() != CollapseClauses.end())
7481 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007482 return nullptr;
7483}
7484
Alexey Bataev10e775f2015-07-30 11:36:16 +00007485static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00007486 auto OrderedClauses =
7487 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
7488 if (OrderedClauses.begin() != OrderedClauses.end())
7489 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00007490 return nullptr;
7491}
7492
Kelvin Lic5609492016-07-15 04:39:07 +00007493static bool checkSimdlenSafelenSpecified(Sema &S,
7494 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007495 const OMPSafelenClause *Safelen = nullptr;
7496 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00007497
Alexey Bataeve3727102018-04-18 15:57:46 +00007498 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00007499 if (Clause->getClauseKind() == OMPC_safelen)
7500 Safelen = cast<OMPSafelenClause>(Clause);
7501 else if (Clause->getClauseKind() == OMPC_simdlen)
7502 Simdlen = cast<OMPSimdlenClause>(Clause);
7503 if (Safelen && Simdlen)
7504 break;
7505 }
7506
7507 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007508 const Expr *SimdlenLength = Simdlen->getSimdlen();
7509 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00007510 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
7511 SimdlenLength->isInstantiationDependent() ||
7512 SimdlenLength->containsUnexpandedParameterPack())
7513 return false;
7514 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
7515 SafelenLength->isInstantiationDependent() ||
7516 SafelenLength->containsUnexpandedParameterPack())
7517 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00007518 Expr::EvalResult SimdlenResult, SafelenResult;
7519 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
7520 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
7521 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
7522 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00007523 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
7524 // If both simdlen and safelen clauses are specified, the value of the
7525 // simdlen parameter must be less than or equal to the value of the safelen
7526 // parameter.
7527 if (SimdlenRes > SafelenRes) {
7528 S.Diag(SimdlenLength->getExprLoc(),
7529 diag::err_omp_wrong_simdlen_safelen_values)
7530 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
7531 return true;
7532 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00007533 }
7534 return false;
7535}
7536
Alexey Bataeve3727102018-04-18 15:57:46 +00007537StmtResult
7538Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7539 SourceLocation StartLoc, SourceLocation EndLoc,
7540 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007541 if (!AStmt)
7542 return StmtError();
7543
7544 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007545 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007546 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7547 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007548 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007549 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7550 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007551 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007552 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007553
Alexander Musmana5f070a2014-10-01 06:03:56 +00007554 assert((CurContext->isDependentContext() || B.builtAll()) &&
7555 "omp simd loop exprs were not built");
7556
Alexander Musman3276a272015-03-21 10:12:56 +00007557 if (!CurContext->isDependentContext()) {
7558 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007559 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007560 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00007561 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007562 B.NumIterations, *this, CurScope,
7563 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00007564 return StmtError();
7565 }
7566 }
7567
Kelvin Lic5609492016-07-15 04:39:07 +00007568 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007569 return StmtError();
7570
Reid Kleckner87a31802018-03-12 21:43:02 +00007571 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007572 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7573 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00007574}
7575
Alexey Bataeve3727102018-04-18 15:57:46 +00007576StmtResult
7577Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
7578 SourceLocation StartLoc, SourceLocation EndLoc,
7579 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007580 if (!AStmt)
7581 return StmtError();
7582
7583 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007584 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007585 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7586 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007587 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00007588 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
7589 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00007590 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00007591 return StmtError();
7592
Alexander Musmana5f070a2014-10-01 06:03:56 +00007593 assert((CurContext->isDependentContext() || B.builtAll()) &&
7594 "omp for loop exprs were not built");
7595
Alexey Bataev54acd402015-08-04 11:18:19 +00007596 if (!CurContext->isDependentContext()) {
7597 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007598 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007599 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007600 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007601 B.NumIterations, *this, CurScope,
7602 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007603 return StmtError();
7604 }
7605 }
7606
Reid Kleckner87a31802018-03-12 21:43:02 +00007607 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007608 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007609 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00007610}
7611
Alexander Musmanf82886e2014-09-18 05:12:34 +00007612StmtResult Sema::ActOnOpenMPForSimdDirective(
7613 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007614 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007615 if (!AStmt)
7616 return StmtError();
7617
7618 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00007619 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007620 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7621 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00007622 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007623 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007624 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7625 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007626 if (NestedLoopCount == 0)
7627 return StmtError();
7628
Alexander Musmanc6388682014-12-15 07:07:06 +00007629 assert((CurContext->isDependentContext() || B.builtAll()) &&
7630 "omp for simd loop exprs were not built");
7631
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007632 if (!CurContext->isDependentContext()) {
7633 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007634 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007635 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007636 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007637 B.NumIterations, *this, CurScope,
7638 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00007639 return StmtError();
7640 }
7641 }
7642
Kelvin Lic5609492016-07-15 04:39:07 +00007643 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007644 return StmtError();
7645
Reid Kleckner87a31802018-03-12 21:43:02 +00007646 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007647 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
7648 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00007649}
7650
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007651StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
7652 Stmt *AStmt,
7653 SourceLocation StartLoc,
7654 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007655 if (!AStmt)
7656 return StmtError();
7657
7658 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007659 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007660 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007661 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007662 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007663 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007664 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007665 return StmtError();
7666 // All associated statements must be '#pragma omp section' except for
7667 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007668 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007669 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7670 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007671 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007672 diag::err_omp_sections_substmt_not_section);
7673 return StmtError();
7674 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007675 cast<OMPSectionDirective>(SectionStmt)
7676 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007677 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007678 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007679 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007680 return StmtError();
7681 }
7682
Reid Kleckner87a31802018-03-12 21:43:02 +00007683 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007684
Alexey Bataev25e5b442015-09-15 12:52:43 +00007685 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7686 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00007687}
7688
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007689StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
7690 SourceLocation StartLoc,
7691 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007692 if (!AStmt)
7693 return StmtError();
7694
7695 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007696
Reid Kleckner87a31802018-03-12 21:43:02 +00007697 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00007698 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007699
Alexey Bataev25e5b442015-09-15 12:52:43 +00007700 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
7701 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00007702}
7703
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007704StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
7705 Stmt *AStmt,
7706 SourceLocation StartLoc,
7707 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007708 if (!AStmt)
7709 return StmtError();
7710
7711 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00007712
Reid Kleckner87a31802018-03-12 21:43:02 +00007713 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00007714
Alexey Bataev3255bf32015-01-19 05:20:46 +00007715 // OpenMP [2.7.3, single Construct, Restrictions]
7716 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00007717 const OMPClause *Nowait = nullptr;
7718 const OMPClause *Copyprivate = nullptr;
7719 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00007720 if (Clause->getClauseKind() == OMPC_nowait)
7721 Nowait = Clause;
7722 else if (Clause->getClauseKind() == OMPC_copyprivate)
7723 Copyprivate = Clause;
7724 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007725 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00007726 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007727 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00007728 return StmtError();
7729 }
7730 }
7731
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00007732 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7733}
7734
Alexander Musman80c22892014-07-17 08:54:58 +00007735StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
7736 SourceLocation StartLoc,
7737 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007738 if (!AStmt)
7739 return StmtError();
7740
7741 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00007742
Reid Kleckner87a31802018-03-12 21:43:02 +00007743 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00007744
7745 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
7746}
7747
Alexey Bataev28c75412015-12-15 08:19:24 +00007748StmtResult Sema::ActOnOpenMPCriticalDirective(
7749 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
7750 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007751 if (!AStmt)
7752 return StmtError();
7753
7754 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007755
Alexey Bataev28c75412015-12-15 08:19:24 +00007756 bool ErrorFound = false;
7757 llvm::APSInt Hint;
7758 SourceLocation HintLoc;
7759 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007760 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007761 if (C->getClauseKind() == OMPC_hint) {
7762 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007763 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00007764 ErrorFound = true;
7765 }
7766 Expr *E = cast<OMPHintClause>(C)->getHint();
7767 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00007768 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00007769 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007770 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00007771 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007772 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00007773 }
7774 }
7775 }
7776 if (ErrorFound)
7777 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007778 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00007779 if (Pair.first && DirName.getName() && !DependentHint) {
7780 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
7781 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00007782 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00007783 Diag(HintLoc, diag::note_omp_critical_hint_here)
7784 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007785 else
Alexey Bataev28c75412015-12-15 08:19:24 +00007786 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00007787 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007788 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00007789 << 1
7790 << C->getHint()->EvaluateKnownConstInt(Context).toString(
7791 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00007792 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007793 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00007794 }
Alexey Bataev28c75412015-12-15 08:19:24 +00007795 }
7796 }
7797
Reid Kleckner87a31802018-03-12 21:43:02 +00007798 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007799
Alexey Bataev28c75412015-12-15 08:19:24 +00007800 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
7801 Clauses, AStmt);
7802 if (!Pair.first && DirName.getName() && !DependentHint)
7803 DSAStack->addCriticalWithHint(Dir, Hint);
7804 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00007805}
7806
Alexey Bataev4acb8592014-07-07 13:01:15 +00007807StmtResult Sema::ActOnOpenMPParallelForDirective(
7808 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007809 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007810 if (!AStmt)
7811 return StmtError();
7812
Alexey Bataeve3727102018-04-18 15:57:46 +00007813 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007814 // 1.2.2 OpenMP Language Terminology
7815 // Structured block - An executable statement with a single entry at the
7816 // top and a single exit at the bottom.
7817 // The point of exit cannot be a branch out of the structured block.
7818 // longjmp() and throw() must not violate the entry/exit criteria.
7819 CS->getCapturedDecl()->setNothrow();
7820
Alexander Musmanc6388682014-12-15 07:07:06 +00007821 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007822 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7823 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007824 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007825 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007826 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7827 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00007828 if (NestedLoopCount == 0)
7829 return StmtError();
7830
Alexander Musmana5f070a2014-10-01 06:03:56 +00007831 assert((CurContext->isDependentContext() || B.builtAll()) &&
7832 "omp parallel for loop exprs were not built");
7833
Alexey Bataev54acd402015-08-04 11:18:19 +00007834 if (!CurContext->isDependentContext()) {
7835 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007836 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007837 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00007838 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007839 B.NumIterations, *this, CurScope,
7840 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00007841 return StmtError();
7842 }
7843 }
7844
Reid Kleckner87a31802018-03-12 21:43:02 +00007845 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00007846 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00007847 NestedLoopCount, Clauses, AStmt, B,
7848 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00007849}
7850
Alexander Musmane4e893b2014-09-23 09:33:00 +00007851StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
7852 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007853 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007854 if (!AStmt)
7855 return StmtError();
7856
Alexey Bataeve3727102018-04-18 15:57:46 +00007857 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007858 // 1.2.2 OpenMP Language Terminology
7859 // Structured block - An executable statement with a single entry at the
7860 // top and a single exit at the bottom.
7861 // The point of exit cannot be a branch out of the structured block.
7862 // longjmp() and throw() must not violate the entry/exit criteria.
7863 CS->getCapturedDecl()->setNothrow();
7864
Alexander Musmanc6388682014-12-15 07:07:06 +00007865 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007866 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7867 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00007868 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007869 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00007870 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
7871 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007872 if (NestedLoopCount == 0)
7873 return StmtError();
7874
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007875 if (!CurContext->isDependentContext()) {
7876 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007877 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007878 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007879 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007880 B.NumIterations, *this, CurScope,
7881 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00007882 return StmtError();
7883 }
7884 }
7885
Kelvin Lic5609492016-07-15 04:39:07 +00007886 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00007887 return StmtError();
7888
Reid Kleckner87a31802018-03-12 21:43:02 +00007889 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007890 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00007891 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00007892}
7893
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007894StmtResult
7895Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
7896 Stmt *AStmt, SourceLocation StartLoc,
7897 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007898 if (!AStmt)
7899 return StmtError();
7900
7901 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007902 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00007903 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007904 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00007905 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007906 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00007907 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007908 return StmtError();
7909 // All associated statements must be '#pragma omp section' except for
7910 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00007911 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007912 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
7913 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007914 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007915 diag::err_omp_parallel_sections_substmt_not_section);
7916 return StmtError();
7917 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007918 cast<OMPSectionDirective>(SectionStmt)
7919 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007920 }
7921 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007922 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007923 diag::err_omp_parallel_sections_not_compound_stmt);
7924 return StmtError();
7925 }
7926
Reid Kleckner87a31802018-03-12 21:43:02 +00007927 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007928
Alexey Bataev25e5b442015-09-15 12:52:43 +00007929 return OMPParallelSectionsDirective::Create(
7930 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00007931}
7932
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007933StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
7934 Stmt *AStmt, SourceLocation StartLoc,
7935 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007936 if (!AStmt)
7937 return StmtError();
7938
David Majnemer9d168222016-08-05 17:44:54 +00007939 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007940 // 1.2.2 OpenMP Language Terminology
7941 // Structured block - An executable statement with a single entry at the
7942 // top and a single exit at the bottom.
7943 // The point of exit cannot be a branch out of the structured block.
7944 // longjmp() and throw() must not violate the entry/exit criteria.
7945 CS->getCapturedDecl()->setNothrow();
7946
Reid Kleckner87a31802018-03-12 21:43:02 +00007947 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007948
Alexey Bataev25e5b442015-09-15 12:52:43 +00007949 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
7950 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00007951}
7952
Alexey Bataev68446b72014-07-18 07:47:19 +00007953StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
7954 SourceLocation EndLoc) {
7955 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
7956}
7957
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00007958StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
7959 SourceLocation EndLoc) {
7960 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
7961}
7962
Alexey Bataev2df347a2014-07-18 10:17:07 +00007963StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
7964 SourceLocation EndLoc) {
7965 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
7966}
7967
Alexey Bataev169d96a2017-07-18 20:17:46 +00007968StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
7969 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007970 SourceLocation StartLoc,
7971 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007972 if (!AStmt)
7973 return StmtError();
7974
7975 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007976
Reid Kleckner87a31802018-03-12 21:43:02 +00007977 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007978
Alexey Bataev169d96a2017-07-18 20:17:46 +00007979 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00007980 AStmt,
7981 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00007982}
7983
Alexey Bataev6125da92014-07-21 11:26:11 +00007984StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
7985 SourceLocation StartLoc,
7986 SourceLocation EndLoc) {
7987 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
7988 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
7989}
7990
Alexey Bataev346265e2015-09-25 10:37:12 +00007991StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
7992 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007993 SourceLocation StartLoc,
7994 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007995 const OMPClause *DependFound = nullptr;
7996 const OMPClause *DependSourceClause = nullptr;
7997 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00007998 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007999 const OMPThreadsClause *TC = nullptr;
8000 const OMPSIMDClause *SC = nullptr;
8001 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008002 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8003 DependFound = C;
8004 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8005 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008006 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008007 << getOpenMPDirectiveName(OMPD_ordered)
8008 << getOpenMPClauseName(OMPC_depend) << 2;
8009 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008010 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008011 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008012 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008013 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008014 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008015 << 0;
8016 ErrorFound = true;
8017 }
8018 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8019 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008020 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008021 << 1;
8022 ErrorFound = true;
8023 }
8024 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008025 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008026 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008027 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008028 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008029 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008030 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008031 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008032 if (!ErrorFound && !SC &&
8033 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008034 // OpenMP [2.8.1,simd Construct, Restrictions]
8035 // An ordered construct with the simd clause is the only OpenMP construct
8036 // that can appear in the simd region.
8037 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00008038 ErrorFound = true;
8039 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008040 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008041 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8042 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008043 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008044 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008045 diag::err_omp_ordered_directive_without_param);
8046 ErrorFound = true;
8047 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008048 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008049 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008050 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8051 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008052 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00008053 ErrorFound = true;
8054 }
8055 }
8056 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008057 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008058
8059 if (AStmt) {
8060 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8061
Reid Kleckner87a31802018-03-12 21:43:02 +00008062 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008063 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008064
8065 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008066}
8067
Alexey Bataev1d160b12015-03-13 12:27:31 +00008068namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008069/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008070/// construct.
8071class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008072 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008073 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008074 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008075 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008076 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008077 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008078 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008079 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008080 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008081 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008082 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008083 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008084 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008085 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008086 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008087 /// expression.
8088 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008089 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008090 /// part.
8091 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008092 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008093 NoError
8094 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008095 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008096 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008097 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008098 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008099 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008100 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008101 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008102 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008103 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008104 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8105 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8106 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008107 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008108 /// important for non-associative operations.
8109 bool IsXLHSInRHSPart;
8110 BinaryOperatorKind Op;
8111 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008112 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008113 /// if it is a prefix unary operation.
8114 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008115
8116public:
8117 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008118 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008119 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008120 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008121 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008122 /// expression. If DiagId and NoteId == 0, then only check is performed
8123 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008124 /// \param DiagId Diagnostic which should be emitted if error is found.
8125 /// \param NoteId Diagnostic note for the main error message.
8126 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008127 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008128 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008129 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008130 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008131 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008132 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008133 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8134 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8135 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008136 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008137 /// false otherwise.
8138 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8139
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008140 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008141 /// if it is a prefix unary operation.
8142 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8143
Alexey Bataev1d160b12015-03-13 12:27:31 +00008144private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008145 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8146 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008147};
8148} // namespace
8149
8150bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8151 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8152 ExprAnalysisErrorCode ErrorFound = NoError;
8153 SourceLocation ErrorLoc, NoteLoc;
8154 SourceRange ErrorRange, NoteRange;
8155 // Allowed constructs are:
8156 // x = x binop expr;
8157 // x = expr binop x;
8158 if (AtomicBinOp->getOpcode() == BO_Assign) {
8159 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008160 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008161 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8162 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8163 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8164 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008165 Op = AtomicInnerBinOp->getOpcode();
8166 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008167 Expr *LHS = AtomicInnerBinOp->getLHS();
8168 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008169 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8170 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8171 /*Canonical=*/true);
8172 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8173 /*Canonical=*/true);
8174 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8175 /*Canonical=*/true);
8176 if (XId == LHSId) {
8177 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008178 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008179 } else if (XId == RHSId) {
8180 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008181 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008182 } else {
8183 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8184 ErrorRange = AtomicInnerBinOp->getSourceRange();
8185 NoteLoc = X->getExprLoc();
8186 NoteRange = X->getSourceRange();
8187 ErrorFound = NotAnUpdateExpression;
8188 }
8189 } else {
8190 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8191 ErrorRange = AtomicInnerBinOp->getSourceRange();
8192 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8193 NoteRange = SourceRange(NoteLoc, NoteLoc);
8194 ErrorFound = NotABinaryOperator;
8195 }
8196 } else {
8197 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8198 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8199 ErrorFound = NotABinaryExpression;
8200 }
8201 } else {
8202 ErrorLoc = AtomicBinOp->getExprLoc();
8203 ErrorRange = AtomicBinOp->getSourceRange();
8204 NoteLoc = AtomicBinOp->getOperatorLoc();
8205 NoteRange = SourceRange(NoteLoc, NoteLoc);
8206 ErrorFound = NotAnAssignmentOp;
8207 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008208 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008209 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8210 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8211 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008212 }
8213 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008214 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008215 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008216}
8217
8218bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8219 unsigned NoteId) {
8220 ExprAnalysisErrorCode ErrorFound = NoError;
8221 SourceLocation ErrorLoc, NoteLoc;
8222 SourceRange ErrorRange, NoteRange;
8223 // Allowed constructs are:
8224 // x++;
8225 // x--;
8226 // ++x;
8227 // --x;
8228 // x binop= expr;
8229 // x = x binop expr;
8230 // x = expr binop x;
8231 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8232 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8233 if (AtomicBody->getType()->isScalarType() ||
8234 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008235 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008236 AtomicBody->IgnoreParenImpCasts())) {
8237 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008238 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008239 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008240 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008241 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008242 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008243 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008244 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8245 AtomicBody->IgnoreParenImpCasts())) {
8246 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008247 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008248 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008249 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008250 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008251 // Check for Unary Operation
8252 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008253 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008254 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8255 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008256 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008257 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8258 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008259 } else {
8260 ErrorFound = NotAnUnaryIncDecExpression;
8261 ErrorLoc = AtomicUnaryOp->getExprLoc();
8262 ErrorRange = AtomicUnaryOp->getSourceRange();
8263 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8264 NoteRange = SourceRange(NoteLoc, NoteLoc);
8265 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008266 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008267 ErrorFound = NotABinaryOrUnaryExpression;
8268 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8269 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8270 }
8271 } else {
8272 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008273 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008274 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8275 }
8276 } else {
8277 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008278 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008279 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8280 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008281 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008282 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8283 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8284 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008285 }
8286 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008287 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008288 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008289 // Build an update expression of form 'OpaqueValueExpr(x) binop
8290 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8291 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8292 auto *OVEX = new (SemaRef.getASTContext())
8293 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8294 auto *OVEExpr = new (SemaRef.getASTContext())
8295 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008296 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008297 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8298 IsXLHSInRHSPart ? OVEExpr : OVEX);
8299 if (Update.isInvalid())
8300 return true;
8301 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8302 Sema::AA_Casting);
8303 if (Update.isInvalid())
8304 return true;
8305 UpdateExpr = Update.get();
8306 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008307 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008308}
8309
Alexey Bataev0162e452014-07-22 10:10:35 +00008310StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8311 Stmt *AStmt,
8312 SourceLocation StartLoc,
8313 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008314 if (!AStmt)
8315 return StmtError();
8316
David Majnemer9d168222016-08-05 17:44:54 +00008317 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008318 // 1.2.2 OpenMP Language Terminology
8319 // Structured block - An executable statement with a single entry at the
8320 // top and a single exit at the bottom.
8321 // The point of exit cannot be a branch out of the structured block.
8322 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008323 OpenMPClauseKind AtomicKind = OMPC_unknown;
8324 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008325 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008326 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008327 C->getClauseKind() == OMPC_update ||
8328 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008329 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008330 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008331 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008332 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8333 << getOpenMPClauseName(AtomicKind);
8334 } else {
8335 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008336 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008337 }
8338 }
8339 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008340
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008342 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8343 Body = EWC->getSubExpr();
8344
Alexey Bataev62cec442014-11-18 10:14:22 +00008345 Expr *X = nullptr;
8346 Expr *V = nullptr;
8347 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008348 Expr *UE = nullptr;
8349 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008350 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008351 // OpenMP [2.12.6, atomic Construct]
8352 // In the next expressions:
8353 // * x and v (as applicable) are both l-value expressions with scalar type.
8354 // * During the execution of an atomic region, multiple syntactic
8355 // occurrences of x must designate the same storage location.
8356 // * Neither of v and expr (as applicable) may access the storage location
8357 // designated by x.
8358 // * Neither of x and expr (as applicable) may access the storage location
8359 // designated by v.
8360 // * expr is an expression with scalar type.
8361 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8362 // * binop, binop=, ++, and -- are not overloaded operators.
8363 // * The expression x binop expr must be numerically equivalent to x binop
8364 // (expr). This requirement is satisfied if the operators in expr have
8365 // precedence greater than binop, or by using parentheses around expr or
8366 // subexpressions of expr.
8367 // * The expression expr binop x must be numerically equivalent to (expr)
8368 // binop x. This requirement is satisfied if the operators in expr have
8369 // precedence equal to or greater than binop, or by using parentheses around
8370 // expr or subexpressions of expr.
8371 // * For forms that allow multiple occurrences of x, the number of times
8372 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008373 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008374 enum {
8375 NotAnExpression,
8376 NotAnAssignmentOp,
8377 NotAScalarType,
8378 NotAnLValue,
8379 NoError
8380 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008381 SourceLocation ErrorLoc, NoteLoc;
8382 SourceRange ErrorRange, NoteRange;
8383 // If clause is read:
8384 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008385 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8386 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008387 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8388 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8389 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8390 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8391 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8392 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8393 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008394 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008395 ErrorFound = NotAnLValue;
8396 ErrorLoc = AtomicBinOp->getExprLoc();
8397 ErrorRange = AtomicBinOp->getSourceRange();
8398 NoteLoc = NotLValueExpr->getExprLoc();
8399 NoteRange = NotLValueExpr->getSourceRange();
8400 }
8401 } else if (!X->isInstantiationDependent() ||
8402 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008403 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008404 (X->isInstantiationDependent() || X->getType()->isScalarType())
8405 ? V
8406 : X;
8407 ErrorFound = NotAScalarType;
8408 ErrorLoc = AtomicBinOp->getExprLoc();
8409 ErrorRange = AtomicBinOp->getSourceRange();
8410 NoteLoc = NotScalarExpr->getExprLoc();
8411 NoteRange = NotScalarExpr->getSourceRange();
8412 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008413 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008414 ErrorFound = NotAnAssignmentOp;
8415 ErrorLoc = AtomicBody->getExprLoc();
8416 ErrorRange = AtomicBody->getSourceRange();
8417 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8418 : AtomicBody->getExprLoc();
8419 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8420 : AtomicBody->getSourceRange();
8421 }
8422 } else {
8423 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008424 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00008425 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008426 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008427 if (ErrorFound != NoError) {
8428 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
8429 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008430 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8431 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00008432 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008433 }
8434 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00008435 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00008436 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008437 enum {
8438 NotAnExpression,
8439 NotAnAssignmentOp,
8440 NotAScalarType,
8441 NotAnLValue,
8442 NoError
8443 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00008444 SourceLocation ErrorLoc, NoteLoc;
8445 SourceRange ErrorRange, NoteRange;
8446 // If clause is write:
8447 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00008448 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8449 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008450 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8451 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00008452 X = AtomicBinOp->getLHS();
8453 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008454 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8455 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
8456 if (!X->isLValue()) {
8457 ErrorFound = NotAnLValue;
8458 ErrorLoc = AtomicBinOp->getExprLoc();
8459 ErrorRange = AtomicBinOp->getSourceRange();
8460 NoteLoc = X->getExprLoc();
8461 NoteRange = X->getSourceRange();
8462 }
8463 } else if (!X->isInstantiationDependent() ||
8464 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008465 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00008466 (X->isInstantiationDependent() || X->getType()->isScalarType())
8467 ? E
8468 : X;
8469 ErrorFound = NotAScalarType;
8470 ErrorLoc = AtomicBinOp->getExprLoc();
8471 ErrorRange = AtomicBinOp->getSourceRange();
8472 NoteLoc = NotScalarExpr->getExprLoc();
8473 NoteRange = NotScalarExpr->getSourceRange();
8474 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008475 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00008476 ErrorFound = NotAnAssignmentOp;
8477 ErrorLoc = AtomicBody->getExprLoc();
8478 ErrorRange = AtomicBody->getSourceRange();
8479 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8480 : AtomicBody->getExprLoc();
8481 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8482 : AtomicBody->getSourceRange();
8483 }
8484 } else {
8485 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008486 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00008487 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00008488 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00008489 if (ErrorFound != NoError) {
8490 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
8491 << ErrorRange;
8492 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
8493 << NoteRange;
8494 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008495 }
8496 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00008497 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008498 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008499 // If clause is update:
8500 // x++;
8501 // x--;
8502 // ++x;
8503 // --x;
8504 // x binop= expr;
8505 // x = x binop expr;
8506 // x = expr binop x;
8507 OpenMPAtomicUpdateChecker Checker(*this);
8508 if (Checker.checkStatement(
8509 Body, (AtomicKind == OMPC_update)
8510 ? diag::err_omp_atomic_update_not_expression_statement
8511 : diag::err_omp_atomic_not_expression_statement,
8512 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00008513 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008514 if (!CurContext->isDependentContext()) {
8515 E = Checker.getExpr();
8516 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008517 UE = Checker.getUpdateExpr();
8518 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00008519 }
Alexey Bataev459dec02014-07-24 06:46:57 +00008520 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008521 enum {
8522 NotAnAssignmentOp,
8523 NotACompoundStatement,
8524 NotTwoSubstatements,
8525 NotASpecificExpression,
8526 NoError
8527 } ErrorFound = NoError;
8528 SourceLocation ErrorLoc, NoteLoc;
8529 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00008530 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008531 // If clause is a capture:
8532 // v = x++;
8533 // v = x--;
8534 // v = ++x;
8535 // v = --x;
8536 // v = x binop= expr;
8537 // v = x = x binop expr;
8538 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008539 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00008540 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8541 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8542 V = AtomicBinOp->getLHS();
8543 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8544 OpenMPAtomicUpdateChecker Checker(*this);
8545 if (Checker.checkStatement(
8546 Body, diag::err_omp_atomic_capture_not_expression_statement,
8547 diag::note_omp_atomic_update))
8548 return StmtError();
8549 E = Checker.getExpr();
8550 X = Checker.getX();
8551 UE = Checker.getUpdateExpr();
8552 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
8553 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00008554 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008555 ErrorLoc = AtomicBody->getExprLoc();
8556 ErrorRange = AtomicBody->getSourceRange();
8557 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8558 : AtomicBody->getExprLoc();
8559 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8560 : AtomicBody->getSourceRange();
8561 ErrorFound = NotAnAssignmentOp;
8562 }
8563 if (ErrorFound != NoError) {
8564 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
8565 << ErrorRange;
8566 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8567 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008568 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008569 if (CurContext->isDependentContext())
8570 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008571 } else {
8572 // If clause is a capture:
8573 // { v = x; x = expr; }
8574 // { v = x; x++; }
8575 // { v = x; x--; }
8576 // { v = x; ++x; }
8577 // { v = x; --x; }
8578 // { v = x; x binop= expr; }
8579 // { v = x; x = x binop expr; }
8580 // { v = x; x = expr binop x; }
8581 // { x++; v = x; }
8582 // { x--; v = x; }
8583 // { ++x; v = x; }
8584 // { --x; v = x; }
8585 // { x binop= expr; v = x; }
8586 // { x = x binop expr; v = x; }
8587 // { x = expr binop x; v = x; }
8588 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
8589 // Check that this is { expr1; expr2; }
8590 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008591 Stmt *First = CS->body_front();
8592 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008593 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
8594 First = EWC->getSubExpr()->IgnoreParenImpCasts();
8595 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
8596 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
8597 // Need to find what subexpression is 'v' and what is 'x'.
8598 OpenMPAtomicUpdateChecker Checker(*this);
8599 bool IsUpdateExprFound = !Checker.checkStatement(Second);
8600 BinaryOperator *BinOp = nullptr;
8601 if (IsUpdateExprFound) {
8602 BinOp = dyn_cast<BinaryOperator>(First);
8603 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8604 }
8605 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8606 // { v = x; x++; }
8607 // { v = x; x--; }
8608 // { v = x; ++x; }
8609 // { v = x; --x; }
8610 // { v = x; x binop= expr; }
8611 // { v = x; x = x binop expr; }
8612 // { v = x; x = expr binop x; }
8613 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008614 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008615 llvm::FoldingSetNodeID XId, PossibleXId;
8616 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8617 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8618 IsUpdateExprFound = XId == PossibleXId;
8619 if (IsUpdateExprFound) {
8620 V = BinOp->getLHS();
8621 X = Checker.getX();
8622 E = Checker.getExpr();
8623 UE = Checker.getUpdateExpr();
8624 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008625 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008626 }
8627 }
8628 if (!IsUpdateExprFound) {
8629 IsUpdateExprFound = !Checker.checkStatement(First);
8630 BinOp = nullptr;
8631 if (IsUpdateExprFound) {
8632 BinOp = dyn_cast<BinaryOperator>(Second);
8633 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
8634 }
8635 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
8636 // { x++; v = x; }
8637 // { x--; v = x; }
8638 // { ++x; v = x; }
8639 // { --x; v = x; }
8640 // { x binop= expr; v = x; }
8641 // { x = x binop expr; v = x; }
8642 // { x = expr binop x; v = x; }
8643 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00008644 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008645 llvm::FoldingSetNodeID XId, PossibleXId;
8646 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
8647 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
8648 IsUpdateExprFound = XId == PossibleXId;
8649 if (IsUpdateExprFound) {
8650 V = BinOp->getLHS();
8651 X = Checker.getX();
8652 E = Checker.getExpr();
8653 UE = Checker.getUpdateExpr();
8654 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00008655 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008656 }
8657 }
8658 }
8659 if (!IsUpdateExprFound) {
8660 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00008661 auto *FirstExpr = dyn_cast<Expr>(First);
8662 auto *SecondExpr = dyn_cast<Expr>(Second);
8663 if (!FirstExpr || !SecondExpr ||
8664 !(FirstExpr->isInstantiationDependent() ||
8665 SecondExpr->isInstantiationDependent())) {
8666 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
8667 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008668 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00008669 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008670 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008671 NoteRange = ErrorRange = FirstBinOp
8672 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00008673 : SourceRange(ErrorLoc, ErrorLoc);
8674 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00008675 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
8676 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
8677 ErrorFound = NotAnAssignmentOp;
8678 NoteLoc = ErrorLoc = SecondBinOp
8679 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008680 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00008681 NoteRange = ErrorRange =
8682 SecondBinOp ? SecondBinOp->getSourceRange()
8683 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00008684 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008685 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00008686 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00008687 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00008688 SecondBinOp->getLHS()->IgnoreParenImpCasts();
8689 llvm::FoldingSetNodeID X1Id, X2Id;
8690 PossibleXRHSInFirst->Profile(X1Id, Context,
8691 /*Canonical=*/true);
8692 PossibleXLHSInSecond->Profile(X2Id, Context,
8693 /*Canonical=*/true);
8694 IsUpdateExprFound = X1Id == X2Id;
8695 if (IsUpdateExprFound) {
8696 V = FirstBinOp->getLHS();
8697 X = SecondBinOp->getLHS();
8698 E = SecondBinOp->getRHS();
8699 UE = nullptr;
8700 IsXLHSInRHSPart = false;
8701 IsPostfixUpdate = true;
8702 } else {
8703 ErrorFound = NotASpecificExpression;
8704 ErrorLoc = FirstBinOp->getExprLoc();
8705 ErrorRange = FirstBinOp->getSourceRange();
8706 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
8707 NoteRange = SecondBinOp->getRHS()->getSourceRange();
8708 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008709 }
8710 }
8711 }
8712 }
8713 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008714 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008715 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008716 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008717 ErrorFound = NotTwoSubstatements;
8718 }
8719 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008720 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008721 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008722 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00008723 ErrorFound = NotACompoundStatement;
8724 }
8725 if (ErrorFound != NoError) {
8726 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
8727 << ErrorRange;
8728 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
8729 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00008730 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008731 if (CurContext->isDependentContext())
8732 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00008733 }
Alexey Bataevdea47612014-07-23 07:46:59 +00008734 }
Alexey Bataev0162e452014-07-22 10:10:35 +00008735
Reid Kleckner87a31802018-03-12 21:43:02 +00008736 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00008737
Alexey Bataev62cec442014-11-18 10:14:22 +00008738 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00008739 X, V, E, UE, IsXLHSInRHSPart,
8740 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00008741}
8742
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008743StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
8744 Stmt *AStmt,
8745 SourceLocation StartLoc,
8746 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008747 if (!AStmt)
8748 return StmtError();
8749
Alexey Bataeve3727102018-04-18 15:57:46 +00008750 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00008751 // 1.2.2 OpenMP Language Terminology
8752 // Structured block - An executable statement with a single entry at the
8753 // top and a single exit at the bottom.
8754 // The point of exit cannot be a branch out of the structured block.
8755 // longjmp() and throw() must not violate the entry/exit criteria.
8756 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008757 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
8758 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8759 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8760 // 1.2.2 OpenMP Language Terminology
8761 // Structured block - An executable statement with a single entry at the
8762 // top and a single exit at the bottom.
8763 // The point of exit cannot be a branch out of the structured block.
8764 // longjmp() and throw() must not violate the entry/exit criteria.
8765 CS->getCapturedDecl()->setNothrow();
8766 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008767
Alexey Bataev13314bf2014-10-09 04:18:56 +00008768 // OpenMP [2.16, Nesting of Regions]
8769 // If specified, a teams construct must be contained within a target
8770 // construct. That target construct must contain no statements or directives
8771 // outside of the teams construct.
8772 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008773 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00008774 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008775 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00008776 auto I = CS->body_begin();
8777 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008778 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00008779 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
8780 OMPTeamsFound) {
8781
Alexey Bataev13314bf2014-10-09 04:18:56 +00008782 OMPTeamsFound = false;
8783 break;
8784 }
8785 ++I;
8786 }
8787 assert(I != CS->body_end() && "Not found statement");
8788 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00008789 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00008790 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00008791 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00008792 }
8793 if (!OMPTeamsFound) {
8794 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
8795 Diag(DSAStack->getInnerTeamsRegionLoc(),
8796 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008797 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00008798 << isa<OMPExecutableDirective>(S);
8799 return StmtError();
8800 }
8801 }
8802
Reid Kleckner87a31802018-03-12 21:43:02 +00008803 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00008804
8805 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8806}
8807
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008808StmtResult
8809Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
8810 Stmt *AStmt, SourceLocation StartLoc,
8811 SourceLocation EndLoc) {
8812 if (!AStmt)
8813 return StmtError();
8814
Alexey Bataeve3727102018-04-18 15:57:46 +00008815 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008816 // 1.2.2 OpenMP Language Terminology
8817 // Structured block - An executable statement with a single entry at the
8818 // top and a single exit at the bottom.
8819 // The point of exit cannot be a branch out of the structured block.
8820 // longjmp() and throw() must not violate the entry/exit criteria.
8821 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00008822 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
8823 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8824 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8825 // 1.2.2 OpenMP Language Terminology
8826 // Structured block - An executable statement with a single entry at the
8827 // top and a single exit at the bottom.
8828 // The point of exit cannot be a branch out of the structured block.
8829 // longjmp() and throw() must not violate the entry/exit criteria.
8830 CS->getCapturedDecl()->setNothrow();
8831 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008832
Reid Kleckner87a31802018-03-12 21:43:02 +00008833 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00008834
8835 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8836 AStmt);
8837}
8838
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008839StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
8840 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008841 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008842 if (!AStmt)
8843 return StmtError();
8844
Alexey Bataeve3727102018-04-18 15:57:46 +00008845 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008846 // 1.2.2 OpenMP Language Terminology
8847 // Structured block - An executable statement with a single entry at the
8848 // top and a single exit at the bottom.
8849 // The point of exit cannot be a branch out of the structured block.
8850 // longjmp() and throw() must not violate the entry/exit criteria.
8851 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008852 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8853 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8854 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8855 // 1.2.2 OpenMP Language Terminology
8856 // Structured block - An executable statement with a single entry at the
8857 // top and a single exit at the bottom.
8858 // The point of exit cannot be a branch out of the structured block.
8859 // longjmp() and throw() must not violate the entry/exit criteria.
8860 CS->getCapturedDecl()->setNothrow();
8861 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008862
8863 OMPLoopDirective::HelperExprs B;
8864 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8865 // define the nested loops number.
8866 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008867 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008868 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008869 VarsWithImplicitDSA, B);
8870 if (NestedLoopCount == 0)
8871 return StmtError();
8872
8873 assert((CurContext->isDependentContext() || B.builtAll()) &&
8874 "omp target parallel for loop exprs were not built");
8875
8876 if (!CurContext->isDependentContext()) {
8877 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008878 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008879 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008880 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008881 B.NumIterations, *this, CurScope,
8882 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008883 return StmtError();
8884 }
8885 }
8886
Reid Kleckner87a31802018-03-12 21:43:02 +00008887 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00008888 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
8889 NestedLoopCount, Clauses, AStmt,
8890 B, DSAStack->isCancelRegion());
8891}
8892
Alexey Bataev95b64a92017-05-30 16:00:04 +00008893/// Check for existence of a map clause in the list of clauses.
8894static bool hasClauses(ArrayRef<OMPClause *> Clauses,
8895 const OpenMPClauseKind K) {
8896 return llvm::any_of(
8897 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
8898}
Samuel Antaodf67fc42016-01-19 19:15:56 +00008899
Alexey Bataev95b64a92017-05-30 16:00:04 +00008900template <typename... Params>
8901static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
8902 const Params... ClauseTypes) {
8903 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008904}
8905
Michael Wong65f367f2015-07-21 13:44:28 +00008906StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
8907 Stmt *AStmt,
8908 SourceLocation StartLoc,
8909 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008910 if (!AStmt)
8911 return StmtError();
8912
8913 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8914
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008915 // OpenMP [2.10.1, Restrictions, p. 97]
8916 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008917 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
8918 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8919 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00008920 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00008921 return StmtError();
8922 }
8923
Reid Kleckner87a31802018-03-12 21:43:02 +00008924 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00008925
8926 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8927 AStmt);
8928}
8929
Samuel Antaodf67fc42016-01-19 19:15:56 +00008930StmtResult
8931Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
8932 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008933 SourceLocation EndLoc, Stmt *AStmt) {
8934 if (!AStmt)
8935 return StmtError();
8936
Alexey Bataeve3727102018-04-18 15:57:46 +00008937 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008938 // 1.2.2 OpenMP Language Terminology
8939 // Structured block - An executable statement with a single entry at the
8940 // top and a single exit at the bottom.
8941 // The point of exit cannot be a branch out of the structured block.
8942 // longjmp() and throw() must not violate the entry/exit criteria.
8943 CS->getCapturedDecl()->setNothrow();
8944 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
8945 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8946 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8947 // 1.2.2 OpenMP Language Terminology
8948 // Structured block - An executable statement with a single entry at the
8949 // top and a single exit at the bottom.
8950 // The point of exit cannot be a branch out of the structured block.
8951 // longjmp() and throw() must not violate the entry/exit criteria.
8952 CS->getCapturedDecl()->setNothrow();
8953 }
8954
Samuel Antaodf67fc42016-01-19 19:15:56 +00008955 // OpenMP [2.10.2, Restrictions, p. 99]
8956 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008957 if (!hasClauses(Clauses, OMPC_map)) {
8958 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8959 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008960 return StmtError();
8961 }
8962
Alexey Bataev7828b252017-11-21 17:08:48 +00008963 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
8964 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00008965}
8966
Samuel Antao72590762016-01-19 20:04:50 +00008967StmtResult
8968Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
8969 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00008970 SourceLocation EndLoc, Stmt *AStmt) {
8971 if (!AStmt)
8972 return StmtError();
8973
Alexey Bataeve3727102018-04-18 15:57:46 +00008974 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00008975 // 1.2.2 OpenMP Language Terminology
8976 // Structured block - An executable statement with a single entry at the
8977 // top and a single exit at the bottom.
8978 // The point of exit cannot be a branch out of the structured block.
8979 // longjmp() and throw() must not violate the entry/exit criteria.
8980 CS->getCapturedDecl()->setNothrow();
8981 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
8982 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8983 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8984 // 1.2.2 OpenMP Language Terminology
8985 // Structured block - An executable statement with a single entry at the
8986 // top and a single exit at the bottom.
8987 // The point of exit cannot be a branch out of the structured block.
8988 // longjmp() and throw() must not violate the entry/exit criteria.
8989 CS->getCapturedDecl()->setNothrow();
8990 }
8991
Samuel Antao72590762016-01-19 20:04:50 +00008992 // OpenMP [2.10.3, Restrictions, p. 102]
8993 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00008994 if (!hasClauses(Clauses, OMPC_map)) {
8995 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
8996 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00008997 return StmtError();
8998 }
8999
Alexey Bataev7828b252017-11-21 17:08:48 +00009000 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9001 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009002}
9003
Samuel Antao686c70c2016-05-26 17:30:50 +00009004StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9005 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009006 SourceLocation EndLoc,
9007 Stmt *AStmt) {
9008 if (!AStmt)
9009 return StmtError();
9010
Alexey Bataeve3727102018-04-18 15:57:46 +00009011 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009012 // 1.2.2 OpenMP Language Terminology
9013 // Structured block - An executable statement with a single entry at the
9014 // top and a single exit at the bottom.
9015 // The point of exit cannot be a branch out of the structured block.
9016 // longjmp() and throw() must not violate the entry/exit criteria.
9017 CS->getCapturedDecl()->setNothrow();
9018 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9019 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9020 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9021 // 1.2.2 OpenMP Language Terminology
9022 // Structured block - An executable statement with a single entry at the
9023 // top and a single exit at the bottom.
9024 // The point of exit cannot be a branch out of the structured block.
9025 // longjmp() and throw() must not violate the entry/exit criteria.
9026 CS->getCapturedDecl()->setNothrow();
9027 }
9028
Alexey Bataev95b64a92017-05-30 16:00:04 +00009029 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009030 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9031 return StmtError();
9032 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009033 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9034 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009035}
9036
Alexey Bataev13314bf2014-10-09 04:18:56 +00009037StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9038 Stmt *AStmt, SourceLocation StartLoc,
9039 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009040 if (!AStmt)
9041 return StmtError();
9042
Alexey Bataeve3727102018-04-18 15:57:46 +00009043 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009044 // 1.2.2 OpenMP Language Terminology
9045 // Structured block - An executable statement with a single entry at the
9046 // top and a single exit at the bottom.
9047 // The point of exit cannot be a branch out of the structured block.
9048 // longjmp() and throw() must not violate the entry/exit criteria.
9049 CS->getCapturedDecl()->setNothrow();
9050
Reid Kleckner87a31802018-03-12 21:43:02 +00009051 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009052
Alexey Bataevceabd412017-11-30 18:01:54 +00009053 DSAStack->setParentTeamsRegionLoc(StartLoc);
9054
Alexey Bataev13314bf2014-10-09 04:18:56 +00009055 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9056}
9057
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009058StmtResult
9059Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9060 SourceLocation EndLoc,
9061 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009062 if (DSAStack->isParentNowaitRegion()) {
9063 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9064 return StmtError();
9065 }
9066 if (DSAStack->isParentOrderedRegion()) {
9067 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9068 return StmtError();
9069 }
9070 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9071 CancelRegion);
9072}
9073
Alexey Bataev87933c72015-09-18 08:07:34 +00009074StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9075 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009076 SourceLocation EndLoc,
9077 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009078 if (DSAStack->isParentNowaitRegion()) {
9079 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9080 return StmtError();
9081 }
9082 if (DSAStack->isParentOrderedRegion()) {
9083 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9084 return StmtError();
9085 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009086 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009087 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9088 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009089}
9090
Alexey Bataev382967a2015-12-08 12:06:20 +00009091static bool checkGrainsizeNumTasksClauses(Sema &S,
9092 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009093 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009094 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009095 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009096 if (C->getClauseKind() == OMPC_grainsize ||
9097 C->getClauseKind() == OMPC_num_tasks) {
9098 if (!PrevClause)
9099 PrevClause = C;
9100 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009101 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009102 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9103 << getOpenMPClauseName(C->getClauseKind())
9104 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009105 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009106 diag::note_omp_previous_grainsize_num_tasks)
9107 << getOpenMPClauseName(PrevClause->getClauseKind());
9108 ErrorFound = true;
9109 }
9110 }
9111 }
9112 return ErrorFound;
9113}
9114
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009115static bool checkReductionClauseWithNogroup(Sema &S,
9116 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009117 const OMPClause *ReductionClause = nullptr;
9118 const OMPClause *NogroupClause = nullptr;
9119 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009120 if (C->getClauseKind() == OMPC_reduction) {
9121 ReductionClause = C;
9122 if (NogroupClause)
9123 break;
9124 continue;
9125 }
9126 if (C->getClauseKind() == OMPC_nogroup) {
9127 NogroupClause = C;
9128 if (ReductionClause)
9129 break;
9130 continue;
9131 }
9132 }
9133 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009134 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9135 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009136 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009137 return true;
9138 }
9139 return false;
9140}
9141
Alexey Bataev49f6e782015-12-01 04:18:41 +00009142StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9143 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009144 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009145 if (!AStmt)
9146 return StmtError();
9147
9148 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9149 OMPLoopDirective::HelperExprs B;
9150 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9151 // define the nested loops number.
9152 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009153 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009154 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009155 VarsWithImplicitDSA, B);
9156 if (NestedLoopCount == 0)
9157 return StmtError();
9158
9159 assert((CurContext->isDependentContext() || B.builtAll()) &&
9160 "omp for loop exprs were not built");
9161
Alexey Bataev382967a2015-12-08 12:06:20 +00009162 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9163 // The grainsize clause and num_tasks clause are mutually exclusive and may
9164 // not appear on the same taskloop directive.
9165 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9166 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009167 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9168 // If a reduction clause is present on the taskloop directive, the nogroup
9169 // clause must not be specified.
9170 if (checkReductionClauseWithNogroup(*this, Clauses))
9171 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009172
Reid Kleckner87a31802018-03-12 21:43:02 +00009173 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009174 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9175 NestedLoopCount, Clauses, AStmt, B);
9176}
9177
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009178StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9179 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009180 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009181 if (!AStmt)
9182 return StmtError();
9183
9184 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9185 OMPLoopDirective::HelperExprs B;
9186 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9187 // define the nested loops number.
9188 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009189 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009190 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9191 VarsWithImplicitDSA, B);
9192 if (NestedLoopCount == 0)
9193 return StmtError();
9194
9195 assert((CurContext->isDependentContext() || B.builtAll()) &&
9196 "omp for loop exprs were not built");
9197
Alexey Bataev5a3af132016-03-29 08:58:54 +00009198 if (!CurContext->isDependentContext()) {
9199 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009200 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009201 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009202 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009203 B.NumIterations, *this, CurScope,
9204 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009205 return StmtError();
9206 }
9207 }
9208
Alexey Bataev382967a2015-12-08 12:06:20 +00009209 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9210 // The grainsize clause and num_tasks clause are mutually exclusive and may
9211 // not appear on the same taskloop directive.
9212 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9213 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009214 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9215 // If a reduction clause is present on the taskloop directive, the nogroup
9216 // clause must not be specified.
9217 if (checkReductionClauseWithNogroup(*this, Clauses))
9218 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009219 if (checkSimdlenSafelenSpecified(*this, Clauses))
9220 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009221
Reid Kleckner87a31802018-03-12 21:43:02 +00009222 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009223 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9224 NestedLoopCount, Clauses, AStmt, B);
9225}
9226
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009227StmtResult Sema::ActOnOpenMPDistributeDirective(
9228 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009229 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009230 if (!AStmt)
9231 return StmtError();
9232
9233 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9234 OMPLoopDirective::HelperExprs B;
9235 // In presence of clause 'collapse' with number of loops, it will
9236 // define the nested loops number.
9237 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009238 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009239 nullptr /*ordered not a clause on distribute*/, AStmt,
9240 *this, *DSAStack, VarsWithImplicitDSA, B);
9241 if (NestedLoopCount == 0)
9242 return StmtError();
9243
9244 assert((CurContext->isDependentContext() || B.builtAll()) &&
9245 "omp for loop exprs were not built");
9246
Reid Kleckner87a31802018-03-12 21:43:02 +00009247 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009248 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
9249 NestedLoopCount, Clauses, AStmt, B);
9250}
9251
Carlo Bertolli9925f152016-06-27 14:55:37 +00009252StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
9253 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009254 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00009255 if (!AStmt)
9256 return StmtError();
9257
Alexey Bataeve3727102018-04-18 15:57:46 +00009258 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00009259 // 1.2.2 OpenMP Language Terminology
9260 // Structured block - An executable statement with a single entry at the
9261 // top and a single exit at the bottom.
9262 // The point of exit cannot be a branch out of the structured block.
9263 // longjmp() and throw() must not violate the entry/exit criteria.
9264 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00009265 for (int ThisCaptureLevel =
9266 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
9267 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9268 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9269 // 1.2.2 OpenMP Language Terminology
9270 // Structured block - An executable statement with a single entry at the
9271 // top and a single exit at the bottom.
9272 // The point of exit cannot be a branch out of the structured block.
9273 // longjmp() and throw() must not violate the entry/exit criteria.
9274 CS->getCapturedDecl()->setNothrow();
9275 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00009276
9277 OMPLoopDirective::HelperExprs B;
9278 // In presence of clause 'collapse' with number of loops, it will
9279 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009280 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00009281 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00009282 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00009283 VarsWithImplicitDSA, B);
9284 if (NestedLoopCount == 0)
9285 return StmtError();
9286
9287 assert((CurContext->isDependentContext() || B.builtAll()) &&
9288 "omp for loop exprs were not built");
9289
Reid Kleckner87a31802018-03-12 21:43:02 +00009290 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00009291 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009292 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9293 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00009294}
9295
Kelvin Li4a39add2016-07-05 05:00:15 +00009296StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
9297 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009298 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00009299 if (!AStmt)
9300 return StmtError();
9301
Alexey Bataeve3727102018-04-18 15:57:46 +00009302 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00009303 // 1.2.2 OpenMP Language Terminology
9304 // Structured block - An executable statement with a single entry at the
9305 // top and a single exit at the bottom.
9306 // The point of exit cannot be a branch out of the structured block.
9307 // longjmp() and throw() must not violate the entry/exit criteria.
9308 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00009309 for (int ThisCaptureLevel =
9310 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
9311 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9312 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9313 // 1.2.2 OpenMP Language Terminology
9314 // Structured block - An executable statement with a single entry at the
9315 // top and a single exit at the bottom.
9316 // The point of exit cannot be a branch out of the structured block.
9317 // longjmp() and throw() must not violate the entry/exit criteria.
9318 CS->getCapturedDecl()->setNothrow();
9319 }
Kelvin Li4a39add2016-07-05 05:00:15 +00009320
9321 OMPLoopDirective::HelperExprs B;
9322 // In presence of clause 'collapse' with number of loops, it will
9323 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009324 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00009325 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00009326 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00009327 VarsWithImplicitDSA, B);
9328 if (NestedLoopCount == 0)
9329 return StmtError();
9330
9331 assert((CurContext->isDependentContext() || B.builtAll()) &&
9332 "omp for loop exprs were not built");
9333
Alexey Bataev438388c2017-11-22 18:34:02 +00009334 if (!CurContext->isDependentContext()) {
9335 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009336 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009337 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9338 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9339 B.NumIterations, *this, CurScope,
9340 DSAStack))
9341 return StmtError();
9342 }
9343 }
9344
Kelvin Lic5609492016-07-15 04:39:07 +00009345 if (checkSimdlenSafelenSpecified(*this, Clauses))
9346 return StmtError();
9347
Reid Kleckner87a31802018-03-12 21:43:02 +00009348 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00009349 return OMPDistributeParallelForSimdDirective::Create(
9350 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9351}
9352
Kelvin Li787f3fc2016-07-06 04:45:38 +00009353StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
9354 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009355 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00009356 if (!AStmt)
9357 return StmtError();
9358
Alexey Bataeve3727102018-04-18 15:57:46 +00009359 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009360 // 1.2.2 OpenMP Language Terminology
9361 // Structured block - An executable statement with a single entry at the
9362 // top and a single exit at the bottom.
9363 // The point of exit cannot be a branch out of the structured block.
9364 // longjmp() and throw() must not violate the entry/exit criteria.
9365 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00009366 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
9367 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9368 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9369 // 1.2.2 OpenMP Language Terminology
9370 // Structured block - An executable statement with a single entry at the
9371 // top and a single exit at the bottom.
9372 // The point of exit cannot be a branch out of the structured block.
9373 // longjmp() and throw() must not violate the entry/exit criteria.
9374 CS->getCapturedDecl()->setNothrow();
9375 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00009376
9377 OMPLoopDirective::HelperExprs B;
9378 // In presence of clause 'collapse' with number of loops, it will
9379 // define the nested loops number.
9380 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009381 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00009382 nullptr /*ordered not a clause on distribute*/, CS, *this,
9383 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00009384 if (NestedLoopCount == 0)
9385 return StmtError();
9386
9387 assert((CurContext->isDependentContext() || B.builtAll()) &&
9388 "omp for loop exprs were not built");
9389
Alexey Bataev438388c2017-11-22 18:34:02 +00009390 if (!CurContext->isDependentContext()) {
9391 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009392 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009393 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9394 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9395 B.NumIterations, *this, CurScope,
9396 DSAStack))
9397 return StmtError();
9398 }
9399 }
9400
Kelvin Lic5609492016-07-15 04:39:07 +00009401 if (checkSimdlenSafelenSpecified(*this, Clauses))
9402 return StmtError();
9403
Reid Kleckner87a31802018-03-12 21:43:02 +00009404 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00009405 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
9406 NestedLoopCount, Clauses, AStmt, B);
9407}
9408
Kelvin Lia579b912016-07-14 02:54:56 +00009409StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
9410 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009411 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00009412 if (!AStmt)
9413 return StmtError();
9414
Alexey Bataeve3727102018-04-18 15:57:46 +00009415 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00009416 // 1.2.2 OpenMP Language Terminology
9417 // Structured block - An executable statement with a single entry at the
9418 // top and a single exit at the bottom.
9419 // The point of exit cannot be a branch out of the structured block.
9420 // longjmp() and throw() must not violate the entry/exit criteria.
9421 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009422 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9423 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9424 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9425 // 1.2.2 OpenMP Language Terminology
9426 // Structured block - An executable statement with a single entry at the
9427 // top and a single exit at the bottom.
9428 // The point of exit cannot be a branch out of the structured block.
9429 // longjmp() and throw() must not violate the entry/exit criteria.
9430 CS->getCapturedDecl()->setNothrow();
9431 }
Kelvin Lia579b912016-07-14 02:54:56 +00009432
9433 OMPLoopDirective::HelperExprs B;
9434 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9435 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009436 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00009437 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009438 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00009439 VarsWithImplicitDSA, B);
9440 if (NestedLoopCount == 0)
9441 return StmtError();
9442
9443 assert((CurContext->isDependentContext() || B.builtAll()) &&
9444 "omp target parallel for simd loop exprs were not built");
9445
9446 if (!CurContext->isDependentContext()) {
9447 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009448 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009449 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00009450 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9451 B.NumIterations, *this, CurScope,
9452 DSAStack))
9453 return StmtError();
9454 }
9455 }
Kelvin Lic5609492016-07-15 04:39:07 +00009456 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00009457 return StmtError();
9458
Reid Kleckner87a31802018-03-12 21:43:02 +00009459 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00009460 return OMPTargetParallelForSimdDirective::Create(
9461 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9462}
9463
Kelvin Li986330c2016-07-20 22:57:10 +00009464StmtResult Sema::ActOnOpenMPTargetSimdDirective(
9465 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009466 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00009467 if (!AStmt)
9468 return StmtError();
9469
Alexey Bataeve3727102018-04-18 15:57:46 +00009470 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00009471 // 1.2.2 OpenMP Language Terminology
9472 // Structured block - An executable statement with a single entry at the
9473 // top and a single exit at the bottom.
9474 // The point of exit cannot be a branch out of the structured block.
9475 // longjmp() and throw() must not violate the entry/exit criteria.
9476 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00009477 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
9478 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9479 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9480 // 1.2.2 OpenMP Language Terminology
9481 // Structured block - An executable statement with a single entry at the
9482 // top and a single exit at the bottom.
9483 // The point of exit cannot be a branch out of the structured block.
9484 // longjmp() and throw() must not violate the entry/exit criteria.
9485 CS->getCapturedDecl()->setNothrow();
9486 }
9487
Kelvin Li986330c2016-07-20 22:57:10 +00009488 OMPLoopDirective::HelperExprs B;
9489 // In presence of clause 'collapse' with number of loops, it will define the
9490 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00009491 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009492 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00009493 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00009494 VarsWithImplicitDSA, B);
9495 if (NestedLoopCount == 0)
9496 return StmtError();
9497
9498 assert((CurContext->isDependentContext() || B.builtAll()) &&
9499 "omp target simd loop exprs were not built");
9500
9501 if (!CurContext->isDependentContext()) {
9502 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009503 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009504 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00009505 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9506 B.NumIterations, *this, CurScope,
9507 DSAStack))
9508 return StmtError();
9509 }
9510 }
9511
9512 if (checkSimdlenSafelenSpecified(*this, Clauses))
9513 return StmtError();
9514
Reid Kleckner87a31802018-03-12 21:43:02 +00009515 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00009516 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
9517 NestedLoopCount, Clauses, AStmt, B);
9518}
9519
Kelvin Li02532872016-08-05 14:37:37 +00009520StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
9521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009522 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00009523 if (!AStmt)
9524 return StmtError();
9525
Alexey Bataeve3727102018-04-18 15:57:46 +00009526 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00009527 // 1.2.2 OpenMP Language Terminology
9528 // Structured block - An executable statement with a single entry at the
9529 // top and a single exit at the bottom.
9530 // The point of exit cannot be a branch out of the structured block.
9531 // longjmp() and throw() must not violate the entry/exit criteria.
9532 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009533 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
9534 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9535 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9536 // 1.2.2 OpenMP Language Terminology
9537 // Structured block - An executable statement with a single entry at the
9538 // top and a single exit at the bottom.
9539 // The point of exit cannot be a branch out of the structured block.
9540 // longjmp() and throw() must not violate the entry/exit criteria.
9541 CS->getCapturedDecl()->setNothrow();
9542 }
Kelvin Li02532872016-08-05 14:37:37 +00009543
9544 OMPLoopDirective::HelperExprs B;
9545 // In presence of clause 'collapse' with number of loops, it will
9546 // define the nested loops number.
9547 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009548 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00009549 nullptr /*ordered not a clause on distribute*/, CS, *this,
9550 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00009551 if (NestedLoopCount == 0)
9552 return StmtError();
9553
9554 assert((CurContext->isDependentContext() || B.builtAll()) &&
9555 "omp teams distribute loop exprs were not built");
9556
Reid Kleckner87a31802018-03-12 21:43:02 +00009557 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009558
9559 DSAStack->setParentTeamsRegionLoc(StartLoc);
9560
David Majnemer9d168222016-08-05 17:44:54 +00009561 return OMPTeamsDistributeDirective::Create(
9562 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00009563}
9564
Kelvin Li4e325f72016-10-25 12:50:55 +00009565StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
9566 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009567 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009568 if (!AStmt)
9569 return StmtError();
9570
Alexey Bataeve3727102018-04-18 15:57:46 +00009571 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00009572 // 1.2.2 OpenMP Language Terminology
9573 // Structured block - An executable statement with a single entry at the
9574 // top and a single exit at the bottom.
9575 // The point of exit cannot be a branch out of the structured block.
9576 // longjmp() and throw() must not violate the entry/exit criteria.
9577 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00009578 for (int ThisCaptureLevel =
9579 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
9580 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9581 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9582 // 1.2.2 OpenMP Language Terminology
9583 // Structured block - An executable statement with a single entry at the
9584 // top and a single exit at the bottom.
9585 // The point of exit cannot be a branch out of the structured block.
9586 // longjmp() and throw() must not violate the entry/exit criteria.
9587 CS->getCapturedDecl()->setNothrow();
9588 }
9589
Kelvin Li4e325f72016-10-25 12:50:55 +00009590
9591 OMPLoopDirective::HelperExprs B;
9592 // In presence of clause 'collapse' with number of loops, it will
9593 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009594 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00009595 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00009596 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00009597 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00009598
9599 if (NestedLoopCount == 0)
9600 return StmtError();
9601
9602 assert((CurContext->isDependentContext() || B.builtAll()) &&
9603 "omp teams distribute simd loop exprs were not built");
9604
9605 if (!CurContext->isDependentContext()) {
9606 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009607 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00009608 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9609 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9610 B.NumIterations, *this, CurScope,
9611 DSAStack))
9612 return StmtError();
9613 }
9614 }
9615
9616 if (checkSimdlenSafelenSpecified(*this, Clauses))
9617 return StmtError();
9618
Reid Kleckner87a31802018-03-12 21:43:02 +00009619 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009620
9621 DSAStack->setParentTeamsRegionLoc(StartLoc);
9622
Kelvin Li4e325f72016-10-25 12:50:55 +00009623 return OMPTeamsDistributeSimdDirective::Create(
9624 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9625}
9626
Kelvin Li579e41c2016-11-30 23:51:03 +00009627StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
9628 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009629 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009630 if (!AStmt)
9631 return StmtError();
9632
Alexey Bataeve3727102018-04-18 15:57:46 +00009633 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00009634 // 1.2.2 OpenMP Language Terminology
9635 // Structured block - An executable statement with a single entry at the
9636 // top and a single exit at the bottom.
9637 // The point of exit cannot be a branch out of the structured block.
9638 // longjmp() and throw() must not violate the entry/exit criteria.
9639 CS->getCapturedDecl()->setNothrow();
9640
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009641 for (int ThisCaptureLevel =
9642 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
9643 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9644 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9645 // 1.2.2 OpenMP Language Terminology
9646 // Structured block - An executable statement with a single entry at the
9647 // top and a single exit at the bottom.
9648 // The point of exit cannot be a branch out of the structured block.
9649 // longjmp() and throw() must not violate the entry/exit criteria.
9650 CS->getCapturedDecl()->setNothrow();
9651 }
9652
Kelvin Li579e41c2016-11-30 23:51:03 +00009653 OMPLoopDirective::HelperExprs B;
9654 // In presence of clause 'collapse' with number of loops, it will
9655 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009656 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00009657 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00009658 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00009659 VarsWithImplicitDSA, B);
9660
9661 if (NestedLoopCount == 0)
9662 return StmtError();
9663
9664 assert((CurContext->isDependentContext() || B.builtAll()) &&
9665 "omp for loop exprs were not built");
9666
9667 if (!CurContext->isDependentContext()) {
9668 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009669 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00009670 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9671 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9672 B.NumIterations, *this, CurScope,
9673 DSAStack))
9674 return StmtError();
9675 }
9676 }
9677
9678 if (checkSimdlenSafelenSpecified(*this, Clauses))
9679 return StmtError();
9680
Reid Kleckner87a31802018-03-12 21:43:02 +00009681 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009682
9683 DSAStack->setParentTeamsRegionLoc(StartLoc);
9684
Kelvin Li579e41c2016-11-30 23:51:03 +00009685 return OMPTeamsDistributeParallelForSimdDirective::Create(
9686 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9687}
9688
Kelvin Li7ade93f2016-12-09 03:24:30 +00009689StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
9690 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009691 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00009692 if (!AStmt)
9693 return StmtError();
9694
Alexey Bataeve3727102018-04-18 15:57:46 +00009695 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00009696 // 1.2.2 OpenMP Language Terminology
9697 // Structured block - An executable statement with a single entry at the
9698 // top and a single exit at the bottom.
9699 // The point of exit cannot be a branch out of the structured block.
9700 // longjmp() and throw() must not violate the entry/exit criteria.
9701 CS->getCapturedDecl()->setNothrow();
9702
Carlo Bertolli62fae152017-11-20 20:46:39 +00009703 for (int ThisCaptureLevel =
9704 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
9705 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9706 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9707 // 1.2.2 OpenMP Language Terminology
9708 // Structured block - An executable statement with a single entry at the
9709 // top and a single exit at the bottom.
9710 // The point of exit cannot be a branch out of the structured block.
9711 // longjmp() and throw() must not violate the entry/exit criteria.
9712 CS->getCapturedDecl()->setNothrow();
9713 }
9714
Kelvin Li7ade93f2016-12-09 03:24:30 +00009715 OMPLoopDirective::HelperExprs B;
9716 // In presence of clause 'collapse' with number of loops, it will
9717 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009718 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00009719 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00009720 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00009721 VarsWithImplicitDSA, B);
9722
9723 if (NestedLoopCount == 0)
9724 return StmtError();
9725
9726 assert((CurContext->isDependentContext() || B.builtAll()) &&
9727 "omp for loop exprs were not built");
9728
Reid Kleckner87a31802018-03-12 21:43:02 +00009729 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00009730
9731 DSAStack->setParentTeamsRegionLoc(StartLoc);
9732
Kelvin Li7ade93f2016-12-09 03:24:30 +00009733 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00009734 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9735 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00009736}
9737
Kelvin Libf594a52016-12-17 05:48:59 +00009738StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
9739 Stmt *AStmt,
9740 SourceLocation StartLoc,
9741 SourceLocation EndLoc) {
9742 if (!AStmt)
9743 return StmtError();
9744
Alexey Bataeve3727102018-04-18 15:57:46 +00009745 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00009746 // 1.2.2 OpenMP Language Terminology
9747 // Structured block - An executable statement with a single entry at the
9748 // top and a single exit at the bottom.
9749 // The point of exit cannot be a branch out of the structured block.
9750 // longjmp() and throw() must not violate the entry/exit criteria.
9751 CS->getCapturedDecl()->setNothrow();
9752
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00009753 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
9754 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9755 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9756 // 1.2.2 OpenMP Language Terminology
9757 // Structured block - An executable statement with a single entry at the
9758 // top and a single exit at the bottom.
9759 // The point of exit cannot be a branch out of the structured block.
9760 // longjmp() and throw() must not violate the entry/exit criteria.
9761 CS->getCapturedDecl()->setNothrow();
9762 }
Reid Kleckner87a31802018-03-12 21:43:02 +00009763 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00009764
9765 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
9766 AStmt);
9767}
9768
Kelvin Li83c451e2016-12-25 04:52:54 +00009769StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
9770 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009771 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00009772 if (!AStmt)
9773 return StmtError();
9774
Alexey Bataeve3727102018-04-18 15:57:46 +00009775 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00009776 // 1.2.2 OpenMP Language Terminology
9777 // Structured block - An executable statement with a single entry at the
9778 // top and a single exit at the bottom.
9779 // The point of exit cannot be a branch out of the structured block.
9780 // longjmp() and throw() must not violate the entry/exit criteria.
9781 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00009782 for (int ThisCaptureLevel =
9783 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
9784 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9785 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9786 // 1.2.2 OpenMP Language Terminology
9787 // Structured block - An executable statement with a single entry at the
9788 // top and a single exit at the bottom.
9789 // The point of exit cannot be a branch out of the structured block.
9790 // longjmp() and throw() must not violate the entry/exit criteria.
9791 CS->getCapturedDecl()->setNothrow();
9792 }
Kelvin Li83c451e2016-12-25 04:52:54 +00009793
9794 OMPLoopDirective::HelperExprs B;
9795 // In presence of clause 'collapse' with number of loops, it will
9796 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009797 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00009798 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
9799 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00009800 VarsWithImplicitDSA, B);
9801 if (NestedLoopCount == 0)
9802 return StmtError();
9803
9804 assert((CurContext->isDependentContext() || B.builtAll()) &&
9805 "omp target teams distribute loop exprs were not built");
9806
Reid Kleckner87a31802018-03-12 21:43:02 +00009807 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00009808 return OMPTargetTeamsDistributeDirective::Create(
9809 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9810}
9811
Kelvin Li80e8f562016-12-29 22:16:30 +00009812StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
9813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009814 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00009815 if (!AStmt)
9816 return StmtError();
9817
Alexey Bataeve3727102018-04-18 15:57:46 +00009818 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00009819 // 1.2.2 OpenMP Language Terminology
9820 // Structured block - An executable statement with a single entry at the
9821 // top and a single exit at the bottom.
9822 // The point of exit cannot be a branch out of the structured block.
9823 // longjmp() and throw() must not violate the entry/exit criteria.
9824 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00009825 for (int ThisCaptureLevel =
9826 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
9827 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9828 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9829 // 1.2.2 OpenMP Language Terminology
9830 // Structured block - An executable statement with a single entry at the
9831 // top and a single exit at the bottom.
9832 // The point of exit cannot be a branch out of the structured block.
9833 // longjmp() and throw() must not violate the entry/exit criteria.
9834 CS->getCapturedDecl()->setNothrow();
9835 }
9836
Kelvin Li80e8f562016-12-29 22:16:30 +00009837 OMPLoopDirective::HelperExprs B;
9838 // In presence of clause 'collapse' with number of loops, it will
9839 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009840 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00009841 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
9842 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00009843 VarsWithImplicitDSA, B);
9844 if (NestedLoopCount == 0)
9845 return StmtError();
9846
9847 assert((CurContext->isDependentContext() || B.builtAll()) &&
9848 "omp target teams distribute parallel for loop exprs were not built");
9849
Alexey Bataev647dd842018-01-15 20:59:40 +00009850 if (!CurContext->isDependentContext()) {
9851 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009852 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00009853 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9854 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9855 B.NumIterations, *this, CurScope,
9856 DSAStack))
9857 return StmtError();
9858 }
9859 }
9860
Reid Kleckner87a31802018-03-12 21:43:02 +00009861 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00009862 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00009863 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
9864 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00009865}
9866
Kelvin Li1851df52017-01-03 05:23:48 +00009867StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
9868 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009869 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00009870 if (!AStmt)
9871 return StmtError();
9872
Alexey Bataeve3727102018-04-18 15:57:46 +00009873 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00009874 // 1.2.2 OpenMP Language Terminology
9875 // Structured block - An executable statement with a single entry at the
9876 // top and a single exit at the bottom.
9877 // The point of exit cannot be a branch out of the structured block.
9878 // longjmp() and throw() must not violate the entry/exit criteria.
9879 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00009880 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
9881 OMPD_target_teams_distribute_parallel_for_simd);
9882 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9883 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9884 // 1.2.2 OpenMP Language Terminology
9885 // Structured block - An executable statement with a single entry at the
9886 // top and a single exit at the bottom.
9887 // The point of exit cannot be a branch out of the structured block.
9888 // longjmp() and throw() must not violate the entry/exit criteria.
9889 CS->getCapturedDecl()->setNothrow();
9890 }
Kelvin Li1851df52017-01-03 05:23:48 +00009891
9892 OMPLoopDirective::HelperExprs B;
9893 // In presence of clause 'collapse' with number of loops, it will
9894 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009895 unsigned NestedLoopCount =
9896 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00009897 getCollapseNumberExpr(Clauses),
9898 nullptr /*ordered not a clause on distribute*/, CS, *this,
9899 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00009900 if (NestedLoopCount == 0)
9901 return StmtError();
9902
9903 assert((CurContext->isDependentContext() || B.builtAll()) &&
9904 "omp target teams distribute parallel for simd loop exprs were not "
9905 "built");
9906
9907 if (!CurContext->isDependentContext()) {
9908 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009909 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00009910 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9911 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9912 B.NumIterations, *this, CurScope,
9913 DSAStack))
9914 return StmtError();
9915 }
9916 }
9917
Alexey Bataev438388c2017-11-22 18:34:02 +00009918 if (checkSimdlenSafelenSpecified(*this, Clauses))
9919 return StmtError();
9920
Reid Kleckner87a31802018-03-12 21:43:02 +00009921 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00009922 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
9923 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9924}
9925
Kelvin Lida681182017-01-10 18:08:18 +00009926StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
9927 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009928 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00009929 if (!AStmt)
9930 return StmtError();
9931
9932 auto *CS = cast<CapturedStmt>(AStmt);
9933 // 1.2.2 OpenMP Language Terminology
9934 // Structured block - An executable statement with a single entry at the
9935 // top and a single exit at the bottom.
9936 // The point of exit cannot be a branch out of the structured block.
9937 // longjmp() and throw() must not violate the entry/exit criteria.
9938 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009939 for (int ThisCaptureLevel =
9940 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
9941 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9942 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9943 // 1.2.2 OpenMP Language Terminology
9944 // Structured block - An executable statement with a single entry at the
9945 // top and a single exit at the bottom.
9946 // The point of exit cannot be a branch out of the structured block.
9947 // longjmp() and throw() must not violate the entry/exit criteria.
9948 CS->getCapturedDecl()->setNothrow();
9949 }
Kelvin Lida681182017-01-10 18:08:18 +00009950
9951 OMPLoopDirective::HelperExprs B;
9952 // In presence of clause 'collapse' with number of loops, it will
9953 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00009954 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00009955 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00009956 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00009957 VarsWithImplicitDSA, B);
9958 if (NestedLoopCount == 0)
9959 return StmtError();
9960
9961 assert((CurContext->isDependentContext() || B.builtAll()) &&
9962 "omp target teams distribute simd loop exprs were not built");
9963
Alexey Bataev438388c2017-11-22 18:34:02 +00009964 if (!CurContext->isDependentContext()) {
9965 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009966 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00009967 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9968 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9969 B.NumIterations, *this, CurScope,
9970 DSAStack))
9971 return StmtError();
9972 }
9973 }
9974
9975 if (checkSimdlenSafelenSpecified(*this, Clauses))
9976 return StmtError();
9977
Reid Kleckner87a31802018-03-12 21:43:02 +00009978 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00009979 return OMPTargetTeamsDistributeSimdDirective::Create(
9980 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9981}
9982
Alexey Bataeved09d242014-05-28 05:53:51 +00009983OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009984 SourceLocation StartLoc,
9985 SourceLocation LParenLoc,
9986 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009987 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009988 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00009989 case OMPC_final:
9990 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
9991 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00009992 case OMPC_num_threads:
9993 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
9994 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009995 case OMPC_safelen:
9996 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
9997 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00009998 case OMPC_simdlen:
9999 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10000 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010001 case OMPC_allocator:
10002 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10003 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010004 case OMPC_collapse:
10005 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10006 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010007 case OMPC_ordered:
10008 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10009 break;
Michael Wonge710d542015-08-07 16:16:36 +000010010 case OMPC_device:
10011 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10012 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010013 case OMPC_num_teams:
10014 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10015 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010016 case OMPC_thread_limit:
10017 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10018 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010019 case OMPC_priority:
10020 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10021 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010022 case OMPC_grainsize:
10023 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10024 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010025 case OMPC_num_tasks:
10026 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10027 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010028 case OMPC_hint:
10029 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10030 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010031 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010032 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010033 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010034 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010035 case OMPC_private:
10036 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010037 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010038 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010039 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010040 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010041 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010042 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010043 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010044 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010045 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010046 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010047 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010048 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010049 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010050 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010051 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010052 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010053 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010054 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010055 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010056 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010057 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010058 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010059 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010060 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010061 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010062 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010063 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010064 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010065 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010066 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010067 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010068 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010069 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010070 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010071 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010072 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010073 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010074 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010075 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010076 case OMPC_match:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010077 llvm_unreachable("Clause is not allowed.");
10078 }
10079 return Res;
10080}
10081
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010082// An OpenMP directive such as 'target parallel' has two captured regions:
10083// for the 'target' and 'parallel' respectively. This function returns
10084// the region in which to capture expressions associated with a clause.
10085// A return value of OMPD_unknown signifies that the expression should not
10086// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010087static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
10088 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
10089 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010090 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010091 switch (CKind) {
10092 case OMPC_if:
10093 switch (DKind) {
10094 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010095 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010096 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010097 // If this clause applies to the nested 'parallel' region, capture within
10098 // the 'target' region, otherwise do not capture.
10099 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10100 CaptureRegion = OMPD_target;
10101 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010102 case OMPD_target_teams_distribute_parallel_for:
10103 case OMPD_target_teams_distribute_parallel_for_simd:
10104 // If this clause applies to the nested 'parallel' region, capture within
10105 // the 'teams' region, otherwise do not capture.
10106 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10107 CaptureRegion = OMPD_teams;
10108 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010109 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010110 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010111 CaptureRegion = OMPD_teams;
10112 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010113 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010114 case OMPD_target_enter_data:
10115 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010116 CaptureRegion = OMPD_task;
10117 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010118 case OMPD_cancel:
10119 case OMPD_parallel:
10120 case OMPD_parallel_sections:
10121 case OMPD_parallel_for:
10122 case OMPD_parallel_for_simd:
10123 case OMPD_target:
10124 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010125 case OMPD_target_teams:
10126 case OMPD_target_teams_distribute:
10127 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010128 case OMPD_distribute_parallel_for:
10129 case OMPD_distribute_parallel_for_simd:
10130 case OMPD_task:
10131 case OMPD_taskloop:
10132 case OMPD_taskloop_simd:
10133 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010134 // Do not capture if-clause expressions.
10135 break;
10136 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010137 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010138 case OMPD_taskyield:
10139 case OMPD_barrier:
10140 case OMPD_taskwait:
10141 case OMPD_cancellation_point:
10142 case OMPD_flush:
10143 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010144 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010145 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010146 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010147 case OMPD_declare_target:
10148 case OMPD_end_declare_target:
10149 case OMPD_teams:
10150 case OMPD_simd:
10151 case OMPD_for:
10152 case OMPD_for_simd:
10153 case OMPD_sections:
10154 case OMPD_section:
10155 case OMPD_single:
10156 case OMPD_master:
10157 case OMPD_critical:
10158 case OMPD_taskgroup:
10159 case OMPD_distribute:
10160 case OMPD_ordered:
10161 case OMPD_atomic:
10162 case OMPD_distribute_simd:
10163 case OMPD_teams_distribute:
10164 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010165 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010166 llvm_unreachable("Unexpected OpenMP directive with if-clause");
10167 case OMPD_unknown:
10168 llvm_unreachable("Unknown OpenMP directive");
10169 }
10170 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010171 case OMPC_num_threads:
10172 switch (DKind) {
10173 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010174 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010175 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010176 CaptureRegion = OMPD_target;
10177 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000010178 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010179 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010180 case OMPD_target_teams_distribute_parallel_for:
10181 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010182 CaptureRegion = OMPD_teams;
10183 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010184 case OMPD_parallel:
10185 case OMPD_parallel_sections:
10186 case OMPD_parallel_for:
10187 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010188 case OMPD_distribute_parallel_for:
10189 case OMPD_distribute_parallel_for_simd:
10190 // Do not capture num_threads-clause expressions.
10191 break;
10192 case OMPD_target_data:
10193 case OMPD_target_enter_data:
10194 case OMPD_target_exit_data:
10195 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010196 case OMPD_target:
10197 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010198 case OMPD_target_teams:
10199 case OMPD_target_teams_distribute:
10200 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010201 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010202 case OMPD_task:
10203 case OMPD_taskloop:
10204 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010205 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010206 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010207 case OMPD_taskyield:
10208 case OMPD_barrier:
10209 case OMPD_taskwait:
10210 case OMPD_cancellation_point:
10211 case OMPD_flush:
10212 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010213 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010214 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010215 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010216 case OMPD_declare_target:
10217 case OMPD_end_declare_target:
10218 case OMPD_teams:
10219 case OMPD_simd:
10220 case OMPD_for:
10221 case OMPD_for_simd:
10222 case OMPD_sections:
10223 case OMPD_section:
10224 case OMPD_single:
10225 case OMPD_master:
10226 case OMPD_critical:
10227 case OMPD_taskgroup:
10228 case OMPD_distribute:
10229 case OMPD_ordered:
10230 case OMPD_atomic:
10231 case OMPD_distribute_simd:
10232 case OMPD_teams_distribute:
10233 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010234 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010235 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
10236 case OMPD_unknown:
10237 llvm_unreachable("Unknown OpenMP directive");
10238 }
10239 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010240 case OMPC_num_teams:
10241 switch (DKind) {
10242 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010243 case OMPD_target_teams_distribute:
10244 case OMPD_target_teams_distribute_simd:
10245 case OMPD_target_teams_distribute_parallel_for:
10246 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010247 CaptureRegion = OMPD_target;
10248 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010249 case OMPD_teams_distribute_parallel_for:
10250 case OMPD_teams_distribute_parallel_for_simd:
10251 case OMPD_teams:
10252 case OMPD_teams_distribute:
10253 case OMPD_teams_distribute_simd:
10254 // Do not capture num_teams-clause expressions.
10255 break;
10256 case OMPD_distribute_parallel_for:
10257 case OMPD_distribute_parallel_for_simd:
10258 case OMPD_task:
10259 case OMPD_taskloop:
10260 case OMPD_taskloop_simd:
10261 case OMPD_target_data:
10262 case OMPD_target_enter_data:
10263 case OMPD_target_exit_data:
10264 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010265 case OMPD_cancel:
10266 case OMPD_parallel:
10267 case OMPD_parallel_sections:
10268 case OMPD_parallel_for:
10269 case OMPD_parallel_for_simd:
10270 case OMPD_target:
10271 case OMPD_target_simd:
10272 case OMPD_target_parallel:
10273 case OMPD_target_parallel_for:
10274 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010275 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010276 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010277 case OMPD_taskyield:
10278 case OMPD_barrier:
10279 case OMPD_taskwait:
10280 case OMPD_cancellation_point:
10281 case OMPD_flush:
10282 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010283 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010284 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010285 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010286 case OMPD_declare_target:
10287 case OMPD_end_declare_target:
10288 case OMPD_simd:
10289 case OMPD_for:
10290 case OMPD_for_simd:
10291 case OMPD_sections:
10292 case OMPD_section:
10293 case OMPD_single:
10294 case OMPD_master:
10295 case OMPD_critical:
10296 case OMPD_taskgroup:
10297 case OMPD_distribute:
10298 case OMPD_ordered:
10299 case OMPD_atomic:
10300 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010301 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000010302 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10303 case OMPD_unknown:
10304 llvm_unreachable("Unknown OpenMP directive");
10305 }
10306 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010307 case OMPC_thread_limit:
10308 switch (DKind) {
10309 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010310 case OMPD_target_teams_distribute:
10311 case OMPD_target_teams_distribute_simd:
10312 case OMPD_target_teams_distribute_parallel_for:
10313 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010314 CaptureRegion = OMPD_target;
10315 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010316 case OMPD_teams_distribute_parallel_for:
10317 case OMPD_teams_distribute_parallel_for_simd:
10318 case OMPD_teams:
10319 case OMPD_teams_distribute:
10320 case OMPD_teams_distribute_simd:
10321 // Do not capture thread_limit-clause expressions.
10322 break;
10323 case OMPD_distribute_parallel_for:
10324 case OMPD_distribute_parallel_for_simd:
10325 case OMPD_task:
10326 case OMPD_taskloop:
10327 case OMPD_taskloop_simd:
10328 case OMPD_target_data:
10329 case OMPD_target_enter_data:
10330 case OMPD_target_exit_data:
10331 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010332 case OMPD_cancel:
10333 case OMPD_parallel:
10334 case OMPD_parallel_sections:
10335 case OMPD_parallel_for:
10336 case OMPD_parallel_for_simd:
10337 case OMPD_target:
10338 case OMPD_target_simd:
10339 case OMPD_target_parallel:
10340 case OMPD_target_parallel_for:
10341 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010342 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010343 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010344 case OMPD_taskyield:
10345 case OMPD_barrier:
10346 case OMPD_taskwait:
10347 case OMPD_cancellation_point:
10348 case OMPD_flush:
10349 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010350 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010351 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010352 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010353 case OMPD_declare_target:
10354 case OMPD_end_declare_target:
10355 case OMPD_simd:
10356 case OMPD_for:
10357 case OMPD_for_simd:
10358 case OMPD_sections:
10359 case OMPD_section:
10360 case OMPD_single:
10361 case OMPD_master:
10362 case OMPD_critical:
10363 case OMPD_taskgroup:
10364 case OMPD_distribute:
10365 case OMPD_ordered:
10366 case OMPD_atomic:
10367 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010368 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000010369 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
10370 case OMPD_unknown:
10371 llvm_unreachable("Unknown OpenMP directive");
10372 }
10373 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010374 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010375 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000010376 case OMPD_parallel_for:
10377 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010378 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000010379 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010380 case OMPD_teams_distribute_parallel_for:
10381 case OMPD_teams_distribute_parallel_for_simd:
10382 case OMPD_target_parallel_for:
10383 case OMPD_target_parallel_for_simd:
10384 case OMPD_target_teams_distribute_parallel_for:
10385 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000010386 CaptureRegion = OMPD_parallel;
10387 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010388 case OMPD_for:
10389 case OMPD_for_simd:
10390 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010391 break;
10392 case OMPD_task:
10393 case OMPD_taskloop:
10394 case OMPD_taskloop_simd:
10395 case OMPD_target_data:
10396 case OMPD_target_enter_data:
10397 case OMPD_target_exit_data:
10398 case OMPD_target_update:
10399 case OMPD_teams:
10400 case OMPD_teams_distribute:
10401 case OMPD_teams_distribute_simd:
10402 case OMPD_target_teams_distribute:
10403 case OMPD_target_teams_distribute_simd:
10404 case OMPD_target:
10405 case OMPD_target_simd:
10406 case OMPD_target_parallel:
10407 case OMPD_cancel:
10408 case OMPD_parallel:
10409 case OMPD_parallel_sections:
10410 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010411 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010412 case OMPD_taskyield:
10413 case OMPD_barrier:
10414 case OMPD_taskwait:
10415 case OMPD_cancellation_point:
10416 case OMPD_flush:
10417 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010418 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010419 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010420 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010421 case OMPD_declare_target:
10422 case OMPD_end_declare_target:
10423 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010424 case OMPD_sections:
10425 case OMPD_section:
10426 case OMPD_single:
10427 case OMPD_master:
10428 case OMPD_critical:
10429 case OMPD_taskgroup:
10430 case OMPD_distribute:
10431 case OMPD_ordered:
10432 case OMPD_atomic:
10433 case OMPD_distribute_simd:
10434 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010435 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010436 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10437 case OMPD_unknown:
10438 llvm_unreachable("Unknown OpenMP directive");
10439 }
10440 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010441 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010442 switch (DKind) {
10443 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010444 case OMPD_teams_distribute_parallel_for_simd:
10445 case OMPD_teams_distribute:
10446 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010447 case OMPD_target_teams_distribute_parallel_for:
10448 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010449 case OMPD_target_teams_distribute:
10450 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000010451 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010452 break;
10453 case OMPD_distribute_parallel_for:
10454 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010455 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010456 case OMPD_distribute_simd:
10457 // Do not capture thread_limit-clause expressions.
10458 break;
10459 case OMPD_parallel_for:
10460 case OMPD_parallel_for_simd:
10461 case OMPD_target_parallel_for_simd:
10462 case OMPD_target_parallel_for:
10463 case OMPD_task:
10464 case OMPD_taskloop:
10465 case OMPD_taskloop_simd:
10466 case OMPD_target_data:
10467 case OMPD_target_enter_data:
10468 case OMPD_target_exit_data:
10469 case OMPD_target_update:
10470 case OMPD_teams:
10471 case OMPD_target:
10472 case OMPD_target_simd:
10473 case OMPD_target_parallel:
10474 case OMPD_cancel:
10475 case OMPD_parallel:
10476 case OMPD_parallel_sections:
10477 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010478 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010479 case OMPD_taskyield:
10480 case OMPD_barrier:
10481 case OMPD_taskwait:
10482 case OMPD_cancellation_point:
10483 case OMPD_flush:
10484 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010485 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010486 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010487 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010488 case OMPD_declare_target:
10489 case OMPD_end_declare_target:
10490 case OMPD_simd:
10491 case OMPD_for:
10492 case OMPD_for_simd:
10493 case OMPD_sections:
10494 case OMPD_section:
10495 case OMPD_single:
10496 case OMPD_master:
10497 case OMPD_critical:
10498 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010499 case OMPD_ordered:
10500 case OMPD_atomic:
10501 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000010502 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010503 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
10504 case OMPD_unknown:
10505 llvm_unreachable("Unknown OpenMP directive");
10506 }
10507 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010508 case OMPC_device:
10509 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010510 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010511 case OMPD_target_enter_data:
10512 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000010513 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000010514 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000010515 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000010516 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000010517 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000010518 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000010519 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000010520 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000010521 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000010522 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010523 CaptureRegion = OMPD_task;
10524 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010525 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010526 // Do not capture device-clause expressions.
10527 break;
10528 case OMPD_teams_distribute_parallel_for:
10529 case OMPD_teams_distribute_parallel_for_simd:
10530 case OMPD_teams:
10531 case OMPD_teams_distribute:
10532 case OMPD_teams_distribute_simd:
10533 case OMPD_distribute_parallel_for:
10534 case OMPD_distribute_parallel_for_simd:
10535 case OMPD_task:
10536 case OMPD_taskloop:
10537 case OMPD_taskloop_simd:
10538 case OMPD_cancel:
10539 case OMPD_parallel:
10540 case OMPD_parallel_sections:
10541 case OMPD_parallel_for:
10542 case OMPD_parallel_for_simd:
10543 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010544 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010545 case OMPD_taskyield:
10546 case OMPD_barrier:
10547 case OMPD_taskwait:
10548 case OMPD_cancellation_point:
10549 case OMPD_flush:
10550 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010551 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010552 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010553 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010554 case OMPD_declare_target:
10555 case OMPD_end_declare_target:
10556 case OMPD_simd:
10557 case OMPD_for:
10558 case OMPD_for_simd:
10559 case OMPD_sections:
10560 case OMPD_section:
10561 case OMPD_single:
10562 case OMPD_master:
10563 case OMPD_critical:
10564 case OMPD_taskgroup:
10565 case OMPD_distribute:
10566 case OMPD_ordered:
10567 case OMPD_atomic:
10568 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000010569 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000010570 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
10571 case OMPD_unknown:
10572 llvm_unreachable("Unknown OpenMP directive");
10573 }
10574 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010575 case OMPC_firstprivate:
10576 case OMPC_lastprivate:
10577 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010578 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010579 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010580 case OMPC_linear:
10581 case OMPC_default:
10582 case OMPC_proc_bind:
10583 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010584 case OMPC_safelen:
10585 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010586 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010587 case OMPC_collapse:
10588 case OMPC_private:
10589 case OMPC_shared:
10590 case OMPC_aligned:
10591 case OMPC_copyin:
10592 case OMPC_copyprivate:
10593 case OMPC_ordered:
10594 case OMPC_nowait:
10595 case OMPC_untied:
10596 case OMPC_mergeable:
10597 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010598 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010599 case OMPC_flush:
10600 case OMPC_read:
10601 case OMPC_write:
10602 case OMPC_update:
10603 case OMPC_capture:
10604 case OMPC_seq_cst:
10605 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010606 case OMPC_threads:
10607 case OMPC_simd:
10608 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010609 case OMPC_priority:
10610 case OMPC_grainsize:
10611 case OMPC_nogroup:
10612 case OMPC_num_tasks:
10613 case OMPC_hint:
10614 case OMPC_defaultmap:
10615 case OMPC_unknown:
10616 case OMPC_uniform:
10617 case OMPC_to:
10618 case OMPC_from:
10619 case OMPC_use_device_ptr:
10620 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010621 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010622 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010623 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010624 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010625 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010626 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010627 case OMPC_match:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010628 llvm_unreachable("Unexpected OpenMP clause.");
10629 }
10630 return CaptureRegion;
10631}
10632
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010633OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
10634 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010635 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010636 SourceLocation NameModifierLoc,
10637 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010638 SourceLocation EndLoc) {
10639 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010640 Stmt *HelperValStmt = nullptr;
10641 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010642 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10643 !Condition->isInstantiationDependent() &&
10644 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010645 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010646 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010647 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010648
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010649 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010650
10651 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
10652 CaptureRegion =
10653 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000010654 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010655 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010656 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010657 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10658 HelperValStmt = buildPreInits(Context, Captures);
10659 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010660 }
10661
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010662 return new (Context)
10663 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
10664 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010665}
10666
Alexey Bataev3778b602014-07-17 07:32:53 +000010667OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
10668 SourceLocation StartLoc,
10669 SourceLocation LParenLoc,
10670 SourceLocation EndLoc) {
10671 Expr *ValExpr = Condition;
10672 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
10673 !Condition->isInstantiationDependent() &&
10674 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000010675 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000010676 if (Val.isInvalid())
10677 return nullptr;
10678
Richard Smith03a4aa32016-06-23 19:02:52 +000010679 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +000010680 }
10681
10682 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
10683}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010684ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
10685 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000010686 if (!Op)
10687 return ExprError();
10688
10689 class IntConvertDiagnoser : public ICEConvertDiagnoser {
10690 public:
10691 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000010692 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000010693 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10694 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010695 return S.Diag(Loc, diag::err_omp_not_integral) << T;
10696 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010697 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
10698 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010699 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
10700 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010701 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
10702 QualType T,
10703 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010704 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
10705 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010706 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
10707 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010708 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000010709 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000010710 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010711 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10712 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010713 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
10714 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010715 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
10716 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010717 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000010718 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000010719 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010720 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
10721 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000010722 llvm_unreachable("conversion functions are permitted");
10723 }
10724 } ConvertDiagnoser;
10725 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
10726}
10727
Alexey Bataeve3727102018-04-18 15:57:46 +000010728static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +000010729 OpenMPClauseKind CKind,
10730 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010731 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
10732 !ValExpr->isInstantiationDependent()) {
10733 SourceLocation Loc = ValExpr->getExprLoc();
10734 ExprResult Value =
10735 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
10736 if (Value.isInvalid())
10737 return false;
10738
10739 ValExpr = Value.get();
10740 // The expression must evaluate to a non-negative integer value.
10741 llvm::APSInt Result;
10742 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000010743 Result.isSigned() &&
10744 !((!StrictlyPositive && Result.isNonNegative()) ||
10745 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010746 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000010747 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
10748 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010749 return false;
10750 }
10751 }
10752 return true;
10753}
10754
Alexey Bataev568a8332014-03-06 06:15:19 +000010755OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
10756 SourceLocation StartLoc,
10757 SourceLocation LParenLoc,
10758 SourceLocation EndLoc) {
10759 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010760 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000010761
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010762 // OpenMP [2.5, Restrictions]
10763 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000010764 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000010765 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010766 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000010767
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010768 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000010769 OpenMPDirectiveKind CaptureRegion =
10770 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
10771 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010772 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010773 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010774 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10775 HelperValStmt = buildPreInits(Context, Captures);
10776 }
10777
10778 return new (Context) OMPNumThreadsClause(
10779 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000010780}
10781
Alexey Bataev62c87d22014-03-21 04:51:18 +000010782ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010783 OpenMPClauseKind CKind,
10784 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000010785 if (!E)
10786 return ExprError();
10787 if (E->isValueDependent() || E->isTypeDependent() ||
10788 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000010789 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010790 llvm::APSInt Result;
10791 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
10792 if (ICE.isInvalid())
10793 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010794 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
10795 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000010796 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010797 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
10798 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000010799 return ExprError();
10800 }
Alexander Musman09184fe2014-09-30 05:29:28 +000010801 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
10802 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
10803 << E->getSourceRange();
10804 return ExprError();
10805 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010806 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
10807 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000010808 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000010809 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000010810 return ICE;
10811}
10812
10813OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
10814 SourceLocation LParenLoc,
10815 SourceLocation EndLoc) {
10816 // OpenMP [2.8.1, simd construct, Description]
10817 // The parameter of the safelen clause must be a constant
10818 // positive integer expression.
10819 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
10820 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010821 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010822 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010823 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000010824}
10825
Alexey Bataev66b15b52015-08-21 11:14:16 +000010826OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
10827 SourceLocation LParenLoc,
10828 SourceLocation EndLoc) {
10829 // OpenMP [2.8.1, simd construct, Description]
10830 // The parameter of the simdlen clause must be a constant
10831 // positive integer expression.
10832 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
10833 if (Simdlen.isInvalid())
10834 return nullptr;
10835 return new (Context)
10836 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
10837}
10838
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010839/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010840static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
10841 DSAStackTy *Stack) {
10842 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010843 if (!OMPAllocatorHandleT.isNull())
10844 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010845 // Build the predefined allocator expressions.
10846 bool ErrorFound = false;
10847 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
10848 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
10849 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
10850 StringRef Allocator =
10851 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
10852 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
10853 auto *VD = dyn_cast_or_null<ValueDecl>(
10854 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
10855 if (!VD) {
10856 ErrorFound = true;
10857 break;
10858 }
10859 QualType AllocatorType =
10860 VD->getType().getNonLValueExprType(S.getASTContext());
10861 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
10862 if (!Res.isUsable()) {
10863 ErrorFound = true;
10864 break;
10865 }
10866 if (OMPAllocatorHandleT.isNull())
10867 OMPAllocatorHandleT = AllocatorType;
10868 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
10869 ErrorFound = true;
10870 break;
10871 }
10872 Stack->setAllocator(AllocatorKind, Res.get());
10873 }
10874 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010875 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
10876 return false;
10877 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000010878 OMPAllocatorHandleT.addConst();
10879 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010880 return true;
10881}
10882
10883OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
10884 SourceLocation LParenLoc,
10885 SourceLocation EndLoc) {
10886 // OpenMP [2.11.3, allocate Directive, Description]
10887 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000010888 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010889 return nullptr;
10890
10891 ExprResult Allocator = DefaultLvalueConversion(A);
10892 if (Allocator.isInvalid())
10893 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000010894 Allocator = PerformImplicitConversion(Allocator.get(),
10895 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010896 Sema::AA_Initializing,
10897 /*AllowExplicit=*/true);
10898 if (Allocator.isInvalid())
10899 return nullptr;
10900 return new (Context)
10901 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
10902}
10903
Alexander Musman64d33f12014-06-04 07:53:32 +000010904OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
10905 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000010906 SourceLocation LParenLoc,
10907 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000010908 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010909 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000010910 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000010911 // The parameter of the collapse clause must be a constant
10912 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000010913 ExprResult NumForLoopsResult =
10914 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
10915 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000010916 return nullptr;
10917 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000010918 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000010919}
10920
Alexey Bataev10e775f2015-07-30 11:36:16 +000010921OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
10922 SourceLocation EndLoc,
10923 SourceLocation LParenLoc,
10924 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000010925 // OpenMP [2.7.1, loop construct, Description]
10926 // OpenMP [2.8.1, simd construct, Description]
10927 // OpenMP [2.9.6, distribute construct, Description]
10928 // The parameter of the ordered clause must be a constant
10929 // positive integer expression if any.
10930 if (NumForLoops && LParenLoc.isValid()) {
10931 ExprResult NumForLoopsResult =
10932 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
10933 if (NumForLoopsResult.isInvalid())
10934 return nullptr;
10935 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010936 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000010937 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010938 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000010939 auto *Clause = OMPOrderedClause::Create(
10940 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
10941 StartLoc, LParenLoc, EndLoc);
10942 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
10943 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010944}
10945
Alexey Bataeved09d242014-05-28 05:53:51 +000010946OMPClause *Sema::ActOnOpenMPSimpleClause(
10947 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
10948 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010949 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010950 switch (Kind) {
10951 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010952 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000010953 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
10954 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010955 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010956 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +000010957 Res = ActOnOpenMPProcBindClause(
10958 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
10959 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010960 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010961 case OMPC_atomic_default_mem_order:
10962 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
10963 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
10964 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
10965 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010966 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010967 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010968 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010969 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010970 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010971 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010972 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010973 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010974 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010975 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010976 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000010977 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010978 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010979 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010980 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010981 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010982 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010983 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010984 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010985 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010986 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010987 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010988 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010989 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010990 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010991 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010992 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010993 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010994 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010995 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010996 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010997 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010998 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010999 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011000 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011001 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011002 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011003 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011004 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011005 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011006 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011007 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011008 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011009 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011010 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011011 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011012 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011013 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011014 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011015 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011016 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011017 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011018 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011019 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011020 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000011021 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011022 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011023 llvm_unreachable("Clause is not allowed.");
11024 }
11025 return Res;
11026}
11027
Alexey Bataev6402bca2015-12-28 07:25:51 +000011028static std::string
11029getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
11030 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011031 SmallString<256> Buffer;
11032 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000011033 unsigned Bound = Last >= 2 ? Last - 2 : 0;
11034 unsigned Skipped = Exclude.size();
11035 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000011036 for (unsigned I = First; I < Last; ++I) {
11037 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011038 --Skipped;
11039 continue;
11040 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011041 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
11042 if (I == Bound - Skipped)
11043 Out << " or ";
11044 else if (I != Bound + 1 - Skipped)
11045 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000011046 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011047 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +000011048}
11049
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011050OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
11051 SourceLocation KindKwLoc,
11052 SourceLocation StartLoc,
11053 SourceLocation LParenLoc,
11054 SourceLocation EndLoc) {
11055 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000011056 static_assert(OMPC_DEFAULT_unknown > 0,
11057 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011058 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011059 << getListOfPossibleValues(OMPC_default, /*First=*/0,
11060 /*Last=*/OMPC_DEFAULT_unknown)
11061 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011062 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011063 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000011064 switch (Kind) {
11065 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011066 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011067 break;
11068 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011069 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011070 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011071 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011072 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000011073 break;
11074 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011075 return new (Context)
11076 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011077}
11078
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011079OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
11080 SourceLocation KindKwLoc,
11081 SourceLocation StartLoc,
11082 SourceLocation LParenLoc,
11083 SourceLocation EndLoc) {
11084 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011085 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011086 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
11087 /*Last=*/OMPC_PROC_BIND_unknown)
11088 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011089 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011090 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011091 return new (Context)
11092 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011093}
11094
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011095OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
11096 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
11097 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
11098 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
11099 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
11100 << getListOfPossibleValues(
11101 OMPC_atomic_default_mem_order, /*First=*/0,
11102 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
11103 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
11104 return nullptr;
11105 }
11106 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
11107 LParenLoc, EndLoc);
11108}
11109
Alexey Bataev56dafe82014-06-20 07:16:17 +000011110OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011111 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011112 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011113 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011114 SourceLocation EndLoc) {
11115 OMPClause *Res = nullptr;
11116 switch (Kind) {
11117 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011118 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
11119 assert(Argument.size() == NumberOfElements &&
11120 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011121 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011122 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
11123 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
11124 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
11125 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
11126 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011127 break;
11128 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000011129 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
11130 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
11131 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
11132 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011133 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000011134 case OMPC_dist_schedule:
11135 Res = ActOnOpenMPDistScheduleClause(
11136 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
11137 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
11138 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011139 case OMPC_defaultmap:
11140 enum { Modifier, DefaultmapKind };
11141 Res = ActOnOpenMPDefaultmapClause(
11142 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
11143 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000011144 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
11145 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011146 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000011147 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011148 case OMPC_num_threads:
11149 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011150 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011151 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011152 case OMPC_collapse:
11153 case OMPC_default:
11154 case OMPC_proc_bind:
11155 case OMPC_private:
11156 case OMPC_firstprivate:
11157 case OMPC_lastprivate:
11158 case OMPC_shared:
11159 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011160 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011161 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011162 case OMPC_linear:
11163 case OMPC_aligned:
11164 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011165 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011166 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011167 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011168 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011169 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011170 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011171 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011172 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011173 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011174 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011175 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011176 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011177 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011178 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011179 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011180 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011181 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011182 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011183 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011184 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011185 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011186 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011187 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011188 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011189 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011190 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011191 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011192 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011193 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011194 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011195 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011196 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011197 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011198 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011199 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011200 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011201 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011202 case OMPC_match:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011203 llvm_unreachable("Clause is not allowed.");
11204 }
11205 return Res;
11206}
11207
Alexey Bataev6402bca2015-12-28 07:25:51 +000011208static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
11209 OpenMPScheduleClauseModifier M2,
11210 SourceLocation M1Loc, SourceLocation M2Loc) {
11211 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
11212 SmallVector<unsigned, 2> Excluded;
11213 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
11214 Excluded.push_back(M2);
11215 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
11216 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
11217 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
11218 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
11219 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
11220 << getListOfPossibleValues(OMPC_schedule,
11221 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
11222 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11223 Excluded)
11224 << getOpenMPClauseName(OMPC_schedule);
11225 return true;
11226 }
11227 return false;
11228}
11229
Alexey Bataev56dafe82014-06-20 07:16:17 +000011230OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000011231 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000011232 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000011233 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11234 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
11235 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
11236 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
11237 return nullptr;
11238 // OpenMP, 2.7.1, Loop Construct, Restrictions
11239 // Either the monotonic modifier or the nonmonotonic modifier can be specified
11240 // but not both.
11241 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
11242 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
11243 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
11244 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
11245 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
11246 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
11247 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
11248 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
11249 return nullptr;
11250 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011251 if (Kind == OMPC_SCHEDULE_unknown) {
11252 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000011253 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
11254 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
11255 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11256 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
11257 Exclude);
11258 } else {
11259 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
11260 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011261 }
11262 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
11263 << Values << getOpenMPClauseName(OMPC_schedule);
11264 return nullptr;
11265 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000011266 // OpenMP, 2.7.1, Loop Construct, Restrictions
11267 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
11268 // schedule(guided).
11269 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
11270 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
11271 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
11272 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
11273 diag::err_omp_schedule_nonmonotonic_static);
11274 return nullptr;
11275 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000011276 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000011277 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000011278 if (ChunkSize) {
11279 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
11280 !ChunkSize->isInstantiationDependent() &&
11281 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011282 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000011283 ExprResult Val =
11284 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
11285 if (Val.isInvalid())
11286 return nullptr;
11287
11288 ValExpr = Val.get();
11289
11290 // OpenMP [2.7.1, Restrictions]
11291 // chunk_size must be a loop invariant integer expression with a positive
11292 // value.
11293 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000011294 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
11295 if (Result.isSigned() && !Result.isStrictlyPositive()) {
11296 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011297 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000011298 return nullptr;
11299 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000011300 } else if (getOpenMPCaptureRegionForClause(
11301 DSAStack->getCurrentDirective(), OMPC_schedule) !=
11302 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000011303 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011304 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011305 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000011306 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11307 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011308 }
11309 }
11310 }
11311
Alexey Bataev6402bca2015-12-28 07:25:51 +000011312 return new (Context)
11313 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000011314 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000011315}
11316
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011317OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
11318 SourceLocation StartLoc,
11319 SourceLocation EndLoc) {
11320 OMPClause *Res = nullptr;
11321 switch (Kind) {
11322 case OMPC_ordered:
11323 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
11324 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000011325 case OMPC_nowait:
11326 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
11327 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011328 case OMPC_untied:
11329 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
11330 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011331 case OMPC_mergeable:
11332 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
11333 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011334 case OMPC_read:
11335 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
11336 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000011337 case OMPC_write:
11338 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
11339 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000011340 case OMPC_update:
11341 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
11342 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000011343 case OMPC_capture:
11344 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
11345 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011346 case OMPC_seq_cst:
11347 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
11348 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000011349 case OMPC_threads:
11350 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
11351 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011352 case OMPC_simd:
11353 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
11354 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000011355 case OMPC_nogroup:
11356 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
11357 break;
Kelvin Li1408f912018-09-26 04:28:39 +000011358 case OMPC_unified_address:
11359 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
11360 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000011361 case OMPC_unified_shared_memory:
11362 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11363 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011364 case OMPC_reverse_offload:
11365 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
11366 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011367 case OMPC_dynamic_allocators:
11368 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
11369 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011370 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011371 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011372 case OMPC_num_threads:
11373 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011374 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011375 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011376 case OMPC_collapse:
11377 case OMPC_schedule:
11378 case OMPC_private:
11379 case OMPC_firstprivate:
11380 case OMPC_lastprivate:
11381 case OMPC_shared:
11382 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011383 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011384 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011385 case OMPC_linear:
11386 case OMPC_aligned:
11387 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011388 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011389 case OMPC_default:
11390 case OMPC_proc_bind:
11391 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011392 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011393 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011394 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011395 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011396 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011397 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011398 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011399 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011400 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000011401 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011402 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011403 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011404 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011405 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011406 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011407 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011408 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011409 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011410 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011411 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011412 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011413 case OMPC_match:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011414 llvm_unreachable("Clause is not allowed.");
11415 }
11416 return Res;
11417}
11418
Alexey Bataev236070f2014-06-20 11:19:47 +000011419OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11420 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000011421 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000011422 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
11423}
11424
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011425OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11426 SourceLocation EndLoc) {
11427 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
11428}
11429
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011430OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11431 SourceLocation EndLoc) {
11432 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
11433}
11434
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011435OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
11436 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011437 return new (Context) OMPReadClause(StartLoc, EndLoc);
11438}
11439
Alexey Bataevdea47612014-07-23 07:46:59 +000011440OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
11441 SourceLocation EndLoc) {
11442 return new (Context) OMPWriteClause(StartLoc, EndLoc);
11443}
11444
Alexey Bataev67a4f222014-07-23 10:25:33 +000011445OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11446 SourceLocation EndLoc) {
11447 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
11448}
11449
Alexey Bataev459dec02014-07-24 06:46:57 +000011450OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11451 SourceLocation EndLoc) {
11452 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
11453}
11454
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011455OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11456 SourceLocation EndLoc) {
11457 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
11458}
11459
Alexey Bataev346265e2015-09-25 10:37:12 +000011460OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11461 SourceLocation EndLoc) {
11462 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
11463}
11464
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011465OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11466 SourceLocation EndLoc) {
11467 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
11468}
11469
Alexey Bataevb825de12015-12-07 10:51:44 +000011470OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11471 SourceLocation EndLoc) {
11472 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
11473}
11474
Kelvin Li1408f912018-09-26 04:28:39 +000011475OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11476 SourceLocation EndLoc) {
11477 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
11478}
11479
Patrick Lyster4a370b92018-10-01 13:47:43 +000011480OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11481 SourceLocation EndLoc) {
11482 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
11483}
11484
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011485OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11486 SourceLocation EndLoc) {
11487 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
11488}
11489
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011490OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11491 SourceLocation EndLoc) {
11492 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
11493}
11494
Alexey Bataevc5e02582014-06-16 07:08:35 +000011495OMPClause *Sema::ActOnOpenMPVarListClause(
11496 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011497 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11498 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11499 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000011500 OpenMPLinearClauseKind LinKind,
11501 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011502 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
11503 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
11504 SourceLocation StartLoc = Locs.StartLoc;
11505 SourceLocation LParenLoc = Locs.LParenLoc;
11506 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011507 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011508 switch (Kind) {
11509 case OMPC_private:
11510 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11511 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011512 case OMPC_firstprivate:
11513 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11514 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011515 case OMPC_lastprivate:
11516 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11517 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011518 case OMPC_shared:
11519 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
11520 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011521 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000011522 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011523 EndLoc, ReductionOrMapperIdScopeSpec,
11524 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011525 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000011526 case OMPC_task_reduction:
11527 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000011528 EndLoc, ReductionOrMapperIdScopeSpec,
11529 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000011530 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000011531 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011532 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
11533 EndLoc, ReductionOrMapperIdScopeSpec,
11534 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000011535 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000011536 case OMPC_linear:
11537 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011538 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000011539 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011540 case OMPC_aligned:
11541 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
11542 ColonLoc, EndLoc);
11543 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011544 case OMPC_copyin:
11545 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
11546 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011547 case OMPC_copyprivate:
11548 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
11549 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000011550 case OMPC_flush:
11551 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
11552 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011553 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000011554 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000011555 StartLoc, LParenLoc, EndLoc);
11556 break;
11557 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011558 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
11559 ReductionOrMapperIdScopeSpec,
11560 ReductionOrMapperId, MapType, IsMapTypeImplicit,
11561 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011562 break;
Samuel Antao661c0902016-05-26 17:39:58 +000011563 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000011564 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
11565 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000011566 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000011567 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000011568 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
11569 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000011570 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000011571 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011572 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000011573 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000011574 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000011575 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000011576 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000011577 case OMPC_allocate:
11578 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
11579 ColonLoc, EndLoc);
11580 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011581 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011582 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011583 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011584 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011585 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011586 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011587 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011588 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011589 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011590 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011591 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011592 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011593 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011594 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011595 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011596 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011597 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011598 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011599 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011600 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000011601 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011602 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011603 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011604 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011605 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011606 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011607 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011608 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011609 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011610 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011611 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011612 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011613 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011614 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000011615 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011616 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011617 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011618 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011619 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011620 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011621 case OMPC_match:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011622 llvm_unreachable("Clause is not allowed.");
11623 }
11624 return Res;
11625}
11626
Alexey Bataev90c228f2016-02-08 09:29:13 +000011627ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000011628 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000011629 ExprResult Res = BuildDeclRefExpr(
11630 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
11631 if (!Res.isUsable())
11632 return ExprError();
11633 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
11634 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
11635 if (!Res.isUsable())
11636 return ExprError();
11637 }
11638 if (VK != VK_LValue && Res.get()->isGLValue()) {
11639 Res = DefaultLvalueConversion(Res.get());
11640 if (!Res.isUsable())
11641 return ExprError();
11642 }
11643 return Res;
11644}
11645
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011646OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11647 SourceLocation StartLoc,
11648 SourceLocation LParenLoc,
11649 SourceLocation EndLoc) {
11650 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000011651 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000011652 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011653 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011654 SourceLocation ELoc;
11655 SourceRange ERange;
11656 Expr *SimpleRefExpr = RefExpr;
11657 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000011658 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011659 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011660 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011661 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011662 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011663 ValueDecl *D = Res.first;
11664 if (!D)
11665 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011666
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011667 QualType Type = D->getType();
11668 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011669
11670 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11671 // A variable that appears in a private clause must not have an incomplete
11672 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011673 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011674 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011675 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011676
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011677 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11678 // A variable that is privatized must not have a const-qualified type
11679 // unless it is of class type with a mutable member. This restriction does
11680 // not apply to the firstprivate clause.
11681 //
11682 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
11683 // A variable that appears in a private clause must not have a
11684 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011685 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011686 continue;
11687
Alexey Bataev758e55e2013-09-06 18:03:48 +000011688 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11689 // in a Construct]
11690 // Variables with the predetermined data-sharing attributes may not be
11691 // listed in data-sharing attributes clauses, except for the cases
11692 // listed below. For these exceptions only, listing a predetermined
11693 // variable in a data-sharing attribute clause is allowed and overrides
11694 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011695 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011696 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011697 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11698 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000011699 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011700 continue;
11701 }
11702
Alexey Bataeve3727102018-04-18 15:57:46 +000011703 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011704 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011705 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000011706 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011707 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11708 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000011709 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011710 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011711 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011712 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011713 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011714 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011715 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011716 continue;
11717 }
11718
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011719 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11720 // A list item cannot appear in both a map clause and a data-sharing
11721 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000011722 //
11723 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
11724 // A list item cannot appear in both a map clause and a data-sharing
11725 // attribute clause on the same construct unless the construct is a
11726 // combined construct.
11727 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
11728 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000011729 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011730 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011731 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000011732 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
11733 OpenMPClauseKind WhereFoundClauseKind) -> bool {
11734 ConflictKind = WhereFoundClauseKind;
11735 return true;
11736 })) {
11737 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011738 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000011739 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000011740 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000011741 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011742 continue;
11743 }
11744 }
11745
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011746 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
11747 // A variable of class type (or array thereof) that appears in a private
11748 // clause requires an accessible, unambiguous default constructor for the
11749 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000011750 // Generate helper private variable and initialize it with the default
11751 // value. The address of the original variable is replaced by the address of
11752 // the new private variable in CodeGen. This new variable is not added to
11753 // IdResolver, so the code in the OpenMP region uses original variable for
11754 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011755 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011756 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011757 buildVarDecl(*this, ELoc, Type, D->getName(),
11758 D->hasAttrs() ? &D->getAttrs() : nullptr,
11759 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000011760 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011761 if (VDPrivate->isInvalidDecl())
11762 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000011763 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011764 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011765
Alexey Bataev90c228f2016-02-08 09:29:13 +000011766 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011767 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000011768 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000011769 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011770 Vars.push_back((VD || CurContext->isDependentContext())
11771 ? RefExpr->IgnoreParens()
11772 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000011773 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011774 }
11775
Alexey Bataeved09d242014-05-28 05:53:51 +000011776 if (Vars.empty())
11777 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011778
Alexey Bataev03b340a2014-10-21 03:16:40 +000011779 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11780 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011781}
11782
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011783namespace {
11784class DiagsUninitializedSeveretyRAII {
11785private:
11786 DiagnosticsEngine &Diags;
11787 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000011788 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011789
11790public:
11791 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
11792 bool IsIgnored)
11793 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
11794 if (!IsIgnored) {
11795 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
11796 /*Map*/ diag::Severity::Ignored, Loc);
11797 }
11798 }
11799 ~DiagsUninitializedSeveretyRAII() {
11800 if (!IsIgnored)
11801 Diags.popMappings(SavedLoc);
11802 }
11803};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000011804}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011805
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011806OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11807 SourceLocation StartLoc,
11808 SourceLocation LParenLoc,
11809 SourceLocation EndLoc) {
11810 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011811 SmallVector<Expr *, 8> PrivateCopies;
11812 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000011813 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011814 bool IsImplicitClause =
11815 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000011816 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011817
Alexey Bataeve3727102018-04-18 15:57:46 +000011818 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011819 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011820 SourceLocation ELoc;
11821 SourceRange ERange;
11822 Expr *SimpleRefExpr = RefExpr;
11823 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000011824 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011825 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011826 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000011827 PrivateCopies.push_back(nullptr);
11828 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011829 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000011830 ValueDecl *D = Res.first;
11831 if (!D)
11832 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011833
Alexey Bataev60da77e2016-02-29 05:54:20 +000011834 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011835 QualType Type = D->getType();
11836 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011837
11838 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11839 // A variable that appears in a private clause must not have an incomplete
11840 // type or a reference type.
11841 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000011842 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011843 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011844 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011845
11846 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
11847 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000011848 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011849 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011850 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011851
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011852 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000011853 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011854 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011855 DSAStackTy::DSAVarData DVar =
11856 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000011857 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011858 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011859 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011860 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
11861 // A list item that specifies a given variable may not appear in more
11862 // than one clause on the same directive, except that a variable may be
11863 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011864 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11865 // A list item may appear in a firstprivate or lastprivate clause but not
11866 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011867 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011868 (isOpenMPDistributeDirective(CurrDir) ||
11869 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011870 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011871 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011872 << getOpenMPClauseName(DVar.CKind)
11873 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011874 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011875 continue;
11876 }
11877
11878 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11879 // in a Construct]
11880 // Variables with the predetermined data-sharing attributes may not be
11881 // listed in data-sharing attributes clauses, except for the cases
11882 // listed below. For these exceptions only, listing a predetermined
11883 // variable in a data-sharing attribute clause is allowed and overrides
11884 // the variable's predetermined data-sharing attributes.
11885 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11886 // in a Construct, C/C++, p.2]
11887 // Variables with const-qualified type having no mutable member may be
11888 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000011889 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011890 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
11891 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000011892 << getOpenMPClauseName(DVar.CKind)
11893 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011894 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011895 continue;
11896 }
11897
11898 // OpenMP [2.9.3.4, Restrictions, p.2]
11899 // A list item that is private within a parallel region must not appear
11900 // in a firstprivate clause on a worksharing construct if any of the
11901 // worksharing regions arising from the worksharing construct ever bind
11902 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011903 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11904 // A list item that is private within a teams region must not appear in a
11905 // firstprivate clause on a distribute construct if any of the distribute
11906 // regions arising from the distribute construct ever bind to any of the
11907 // teams regions arising from the teams construct.
11908 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
11909 // A list item that appears in a reduction clause of a teams construct
11910 // must not appear in a firstprivate clause on a distribute construct if
11911 // any of the distribute regions arising from the distribute construct
11912 // ever bind to any of the teams regions arising from the teams construct.
11913 if ((isOpenMPWorksharingDirective(CurrDir) ||
11914 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011915 !isOpenMPParallelDirective(CurrDir) &&
11916 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000011917 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011918 if (DVar.CKind != OMPC_shared &&
11919 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011920 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011921 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000011922 Diag(ELoc, diag::err_omp_required_access)
11923 << getOpenMPClauseName(OMPC_firstprivate)
11924 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011925 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011926 continue;
11927 }
11928 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011929 // OpenMP [2.9.3.4, Restrictions, p.3]
11930 // A list item that appears in a reduction clause of a parallel construct
11931 // must not appear in a firstprivate clause on a worksharing or task
11932 // construct if any of the worksharing or task regions arising from the
11933 // worksharing or task construct ever bind to any of the parallel regions
11934 // arising from the parallel construct.
11935 // OpenMP [2.9.3.4, Restrictions, p.4]
11936 // A list item that appears in a reduction clause in worksharing
11937 // construct must not appear in a firstprivate clause in a task construct
11938 // encountered during execution of any of the worksharing regions arising
11939 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000011940 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011941 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011942 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
11943 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011944 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011945 isOpenMPWorksharingDirective(K) ||
11946 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011947 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011948 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011949 if (DVar.CKind == OMPC_reduction &&
11950 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011951 isOpenMPWorksharingDirective(DVar.DKind) ||
11952 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011953 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
11954 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000011955 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000011956 continue;
11957 }
11958 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000011959
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011960 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
11961 // A list item cannot appear in both a map clause and a data-sharing
11962 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000011963 //
11964 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
11965 // A list item cannot appear in both a map clause and a data-sharing
11966 // attribute clause on the same construct unless the construct is a
11967 // combined construct.
11968 if ((LangOpts.OpenMP <= 45 &&
11969 isOpenMPTargetExecutionDirective(CurrDir)) ||
11970 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000011971 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000011972 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000011973 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000011974 [&ConflictKind](
11975 OMPClauseMappableExprCommon::MappableExprComponentListRef,
11976 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000011977 ConflictKind = WhereFoundClauseKind;
11978 return true;
11979 })) {
11980 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011981 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000011982 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011983 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000011984 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000011985 continue;
11986 }
11987 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011988 }
11989
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011990 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011991 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000011992 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011993 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
11994 << getOpenMPClauseName(OMPC_firstprivate) << Type
11995 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
11996 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000011997 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011998 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000011999 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012000 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000012001 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012002 continue;
12003 }
12004
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012005 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012006 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012007 buildVarDecl(*this, ELoc, Type, D->getName(),
12008 D->hasAttrs() ? &D->getAttrs() : nullptr,
12009 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012010 // Generate helper private variable and initialize it with the value of the
12011 // original variable. The address of the original variable is replaced by
12012 // the address of the new private variable in the CodeGen. This new variable
12013 // is not added to IdResolver, so the code in the OpenMP region uses
12014 // original variable for proper diagnostics and variable capturing.
12015 Expr *VDInitRefExpr = nullptr;
12016 // For arrays generate initializer for single element and replace it by the
12017 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012018 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012019 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000012020 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012021 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012022 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012023 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012024 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
12025 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000012026 InitializedEntity Entity =
12027 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012028 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
12029
12030 InitializationSequence InitSeq(*this, Entity, Kind, Init);
12031 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
12032 if (Result.isInvalid())
12033 VDPrivate->setInvalidDecl();
12034 else
12035 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012036 // Remove temp variable declaration.
12037 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012038 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000012039 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
12040 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000012041 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
12042 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000012043 AddInitializerToDecl(VDPrivate,
12044 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012045 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012046 }
12047 if (VDPrivate->isInvalidDecl()) {
12048 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012049 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012050 diag::note_omp_task_predetermined_firstprivate_here);
12051 }
12052 continue;
12053 }
12054 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012055 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000012056 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
12057 RefExpr->getExprLoc());
12058 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012059 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012060 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012061 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012062 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012063 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012064 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012065 ExprCaptures.push_back(Ref->getDecl());
12066 }
Alexey Bataev417089f2016-02-17 13:19:37 +000012067 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012068 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012069 Vars.push_back((VD || CurContext->isDependentContext())
12070 ? RefExpr->IgnoreParens()
12071 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012072 PrivateCopies.push_back(VDPrivateRefExpr);
12073 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012074 }
12075
Alexey Bataeved09d242014-05-28 05:53:51 +000012076 if (Vars.empty())
12077 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012078
12079 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012080 Vars, PrivateCopies, Inits,
12081 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012082}
12083
Alexander Musman1bb328c2014-06-04 13:06:39 +000012084OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
12085 SourceLocation StartLoc,
12086 SourceLocation LParenLoc,
12087 SourceLocation EndLoc) {
12088 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000012089 SmallVector<Expr *, 8> SrcExprs;
12090 SmallVector<Expr *, 8> DstExprs;
12091 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000012092 SmallVector<Decl *, 4> ExprCaptures;
12093 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000012094 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012095 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012096 SourceLocation ELoc;
12097 SourceRange ERange;
12098 Expr *SimpleRefExpr = RefExpr;
12099 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000012100 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000012101 // It will be analyzed later.
12102 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012103 SrcExprs.push_back(nullptr);
12104 DstExprs.push_back(nullptr);
12105 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012106 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012107 ValueDecl *D = Res.first;
12108 if (!D)
12109 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012110
Alexey Bataev74caaf22016-02-20 04:09:36 +000012111 QualType Type = D->getType();
12112 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012113
12114 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
12115 // A variable that appears in a lastprivate clause must not have an
12116 // incomplete type or a reference type.
12117 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000012118 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000012119 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012120 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012121
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012122 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12123 // A variable that is privatized must not have a const-qualified type
12124 // unless it is of class type with a mutable member. This restriction does
12125 // not apply to the firstprivate clause.
12126 //
12127 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
12128 // A variable that appears in a lastprivate clause must not have a
12129 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012130 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012131 continue;
12132
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012133 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000012134 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12135 // in a Construct]
12136 // Variables with the predetermined data-sharing attributes may not be
12137 // listed in data-sharing attributes clauses, except for the cases
12138 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012139 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12140 // A list item may appear in a firstprivate or lastprivate clause but not
12141 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000012142 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012143 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012144 (isOpenMPDistributeDirective(CurrDir) ||
12145 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000012146 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
12147 Diag(ELoc, diag::err_omp_wrong_dsa)
12148 << getOpenMPClauseName(DVar.CKind)
12149 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012150 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012151 continue;
12152 }
12153
Alexey Bataevf29276e2014-06-18 04:14:57 +000012154 // OpenMP [2.14.3.5, Restrictions, p.2]
12155 // A list item that is private within a parallel region, or that appears in
12156 // the reduction clause of a parallel construct, must not appear in a
12157 // lastprivate clause on a worksharing construct if any of the corresponding
12158 // worksharing regions ever binds to any of the corresponding parallel
12159 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000012160 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000012161 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012162 !isOpenMPParallelDirective(CurrDir) &&
12163 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000012164 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012165 if (DVar.CKind != OMPC_shared) {
12166 Diag(ELoc, diag::err_omp_required_access)
12167 << getOpenMPClauseName(OMPC_lastprivate)
12168 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012169 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012170 continue;
12171 }
12172 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000012173
Alexander Musman1bb328c2014-06-04 13:06:39 +000012174 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000012175 // A variable of class type (or array thereof) that appears in a
12176 // lastprivate clause requires an accessible, unambiguous default
12177 // constructor for the class type, unless the list item is also specified
12178 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000012179 // A variable of class type (or array thereof) that appears in a
12180 // lastprivate clause requires an accessible, unambiguous copy assignment
12181 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000012182 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012183 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
12184 Type.getUnqualifiedType(), ".lastprivate.src",
12185 D->hasAttrs() ? &D->getAttrs() : nullptr);
12186 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000012187 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000012188 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012189 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000012190 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012191 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000012192 // For arrays generate assignment operation for single element and replace
12193 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012194 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
12195 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000012196 if (AssignmentOp.isInvalid())
12197 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012198 AssignmentOp =
12199 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000012200 if (AssignmentOp.isInvalid())
12201 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012202
Alexey Bataev74caaf22016-02-20 04:09:36 +000012203 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012204 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012205 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012206 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000012207 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000012208 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012209 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000012210 ExprCaptures.push_back(Ref->getDecl());
12211 }
12212 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012213 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012214 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000012215 ExprResult RefRes = DefaultLvalueConversion(Ref);
12216 if (!RefRes.isUsable())
12217 continue;
12218 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000012219 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12220 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012221 if (!PostUpdateRes.isUsable())
12222 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012223 ExprPostUpdates.push_back(
12224 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000012225 }
12226 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012227 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012228 Vars.push_back((VD || CurContext->isDependentContext())
12229 ? RefExpr->IgnoreParens()
12230 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000012231 SrcExprs.push_back(PseudoSrcExpr);
12232 DstExprs.push_back(PseudoDstExpr);
12233 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000012234 }
12235
12236 if (Vars.empty())
12237 return nullptr;
12238
12239 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000012240 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012241 buildPreInits(Context, ExprCaptures),
12242 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000012243}
12244
Alexey Bataev758e55e2013-09-06 18:03:48 +000012245OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
12246 SourceLocation StartLoc,
12247 SourceLocation LParenLoc,
12248 SourceLocation EndLoc) {
12249 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012250 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012251 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012252 SourceLocation ELoc;
12253 SourceRange ERange;
12254 Expr *SimpleRefExpr = RefExpr;
12255 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012256 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000012257 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012258 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012259 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012260 ValueDecl *D = Res.first;
12261 if (!D)
12262 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012263
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012264 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012265 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12266 // in a Construct]
12267 // Variables with the predetermined data-sharing attributes may not be
12268 // listed in data-sharing attributes clauses, except for the cases
12269 // listed below. For these exceptions only, listing a predetermined
12270 // variable in a data-sharing attribute clause is allowed and overrides
12271 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012272 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000012273 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
12274 DVar.RefExpr) {
12275 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12276 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012277 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012278 continue;
12279 }
12280
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012281 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012282 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012283 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000012284 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012285 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
12286 ? RefExpr->IgnoreParens()
12287 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012288 }
12289
Alexey Bataeved09d242014-05-28 05:53:51 +000012290 if (Vars.empty())
12291 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012292
12293 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
12294}
12295
Alexey Bataevc5e02582014-06-16 07:08:35 +000012296namespace {
12297class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
12298 DSAStackTy *Stack;
12299
12300public:
12301 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012302 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
12303 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012304 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
12305 return false;
12306 if (DVar.CKind != OMPC_unknown)
12307 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012308 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012309 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012310 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000012311 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012312 }
12313 return false;
12314 }
12315 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012316 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012317 if (Child && Visit(Child))
12318 return true;
12319 }
12320 return false;
12321 }
Alexey Bataev23b69422014-06-18 07:08:49 +000012322 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012323};
Alexey Bataev23b69422014-06-18 07:08:49 +000012324} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000012325
Alexey Bataev60da77e2016-02-29 05:54:20 +000012326namespace {
12327// Transform MemberExpression for specified FieldDecl of current class to
12328// DeclRefExpr to specified OMPCapturedExprDecl.
12329class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
12330 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000012331 ValueDecl *Field = nullptr;
12332 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012333
12334public:
12335 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
12336 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
12337
12338 ExprResult TransformMemberExpr(MemberExpr *E) {
12339 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
12340 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000012341 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012342 return CapturedExpr;
12343 }
12344 return BaseTransform::TransformMemberExpr(E);
12345 }
12346 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
12347};
12348} // namespace
12349
Alexey Bataev97d18bf2018-04-11 19:21:00 +000012350template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000012351static T filterLookupForUDReductionAndMapper(
12352 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012353 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012354 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012355 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012356 return Res;
12357 }
12358 }
12359 return T();
12360}
12361
Alexey Bataev43b90b72018-09-12 16:31:59 +000012362static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
12363 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
12364
12365 for (auto RD : D->redecls()) {
12366 // Don't bother with extra checks if we already know this one isn't visible.
12367 if (RD == D)
12368 continue;
12369
12370 auto ND = cast<NamedDecl>(RD);
12371 if (LookupResult::isVisible(SemaRef, ND))
12372 return ND;
12373 }
12374
12375 return nullptr;
12376}
12377
12378static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000012379argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000012380 SourceLocation Loc, QualType Ty,
12381 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
12382 // Find all of the associated namespaces and classes based on the
12383 // arguments we have.
12384 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12385 Sema::AssociatedClassSet AssociatedClasses;
12386 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
12387 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
12388 AssociatedClasses);
12389
12390 // C++ [basic.lookup.argdep]p3:
12391 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12392 // and let Y be the lookup set produced by argument dependent
12393 // lookup (defined as follows). If X contains [...] then Y is
12394 // empty. Otherwise Y is the set of declarations found in the
12395 // namespaces associated with the argument types as described
12396 // below. The set of declarations found by the lookup of the name
12397 // is the union of X and Y.
12398 //
12399 // Here, we compute Y and add its members to the overloaded
12400 // candidate set.
12401 for (auto *NS : AssociatedNamespaces) {
12402 // When considering an associated namespace, the lookup is the
12403 // same as the lookup performed when the associated namespace is
12404 // used as a qualifier (3.4.3.2) except that:
12405 //
12406 // -- Any using-directives in the associated namespace are
12407 // ignored.
12408 //
12409 // -- Any namespace-scope friend functions declared in
12410 // associated classes are visible within their respective
12411 // namespaces even if they are not visible during an ordinary
12412 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000012413 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000012414 for (auto *D : R) {
12415 auto *Underlying = D;
12416 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12417 Underlying = USD->getTargetDecl();
12418
Michael Kruse4304e9d2019-02-19 16:38:20 +000012419 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
12420 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000012421 continue;
12422
12423 if (!SemaRef.isVisible(D)) {
12424 D = findAcceptableDecl(SemaRef, D);
12425 if (!D)
12426 continue;
12427 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
12428 Underlying = USD->getTargetDecl();
12429 }
12430 Lookups.emplace_back();
12431 Lookups.back().addDecl(Underlying);
12432 }
12433 }
12434}
12435
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012436static ExprResult
12437buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
12438 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
12439 const DeclarationNameInfo &ReductionId, QualType Ty,
12440 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
12441 if (ReductionIdScopeSpec.isInvalid())
12442 return ExprError();
12443 SmallVector<UnresolvedSet<8>, 4> Lookups;
12444 if (S) {
12445 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12446 Lookup.suppressDiagnostics();
12447 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012448 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012449 do {
12450 S = S->getParent();
12451 } while (S && !S->isDeclScope(D));
12452 if (S)
12453 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000012454 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012455 Lookups.back().append(Lookup.begin(), Lookup.end());
12456 Lookup.clear();
12457 }
12458 } else if (auto *ULE =
12459 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
12460 Lookups.push_back(UnresolvedSet<8>());
12461 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012462 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012463 if (D == PrevD)
12464 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000012465 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012466 Lookups.back().addDecl(DRD);
12467 PrevD = D;
12468 }
12469 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000012470 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
12471 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012472 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000012473 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012474 return !D->isInvalidDecl() &&
12475 (D->getType()->isDependentType() ||
12476 D->getType()->isInstantiationDependentType() ||
12477 D->getType()->containsUnexpandedParameterPack());
12478 })) {
12479 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000012480 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000012481 if (Set.empty())
12482 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012483 ResSet.append(Set.begin(), Set.end());
12484 // The last item marks the end of all declarations at the specified scope.
12485 ResSet.addDecl(Set[Set.size() - 1]);
12486 }
12487 return UnresolvedLookupExpr::Create(
12488 SemaRef.Context, /*NamingClass=*/nullptr,
12489 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
12490 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
12491 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000012492 // Lookup inside the classes.
12493 // C++ [over.match.oper]p3:
12494 // For a unary operator @ with an operand of a type whose
12495 // cv-unqualified version is T1, and for a binary operator @ with
12496 // a left operand of a type whose cv-unqualified version is T1 and
12497 // a right operand of a type whose cv-unqualified version is T2,
12498 // three sets of candidate functions, designated member
12499 // candidates, non-member candidates and built-in candidates, are
12500 // constructed as follows:
12501 // -- If T1 is a complete class type or a class currently being
12502 // defined, the set of member candidates is the result of the
12503 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
12504 // the set of member candidates is empty.
12505 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
12506 Lookup.suppressDiagnostics();
12507 if (const auto *TyRec = Ty->getAs<RecordType>()) {
12508 // Complete the type if it can be completed.
12509 // If the type is neither complete nor being defined, bail out now.
12510 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
12511 TyRec->getDecl()->getDefinition()) {
12512 Lookup.clear();
12513 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
12514 if (Lookup.empty()) {
12515 Lookups.emplace_back();
12516 Lookups.back().append(Lookup.begin(), Lookup.end());
12517 }
12518 }
12519 }
12520 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000012521 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000012522 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000012523 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12524 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
12525 if (!D->isInvalidDecl() &&
12526 SemaRef.Context.hasSameType(D->getType(), Ty))
12527 return D;
12528 return nullptr;
12529 }))
12530 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
12531 VK_LValue, Loc);
12532 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000012533 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
12534 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
12535 if (!D->isInvalidDecl() &&
12536 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
12537 !Ty.isMoreQualifiedThan(D->getType()))
12538 return D;
12539 return nullptr;
12540 })) {
12541 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
12542 /*DetectVirtual=*/false);
12543 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
12544 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
12545 VD->getType().getUnqualifiedType()))) {
12546 if (SemaRef.CheckBaseClassAccess(
12547 Loc, VD->getType(), Ty, Paths.front(),
12548 /*DiagID=*/0) != Sema::AR_inaccessible) {
12549 SemaRef.BuildBasePathArray(Paths, BasePath);
12550 return SemaRef.BuildDeclRefExpr(
12551 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
12552 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012553 }
12554 }
12555 }
12556 }
12557 if (ReductionIdScopeSpec.isSet()) {
12558 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
12559 return ExprError();
12560 }
12561 return ExprEmpty();
12562}
12563
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012564namespace {
12565/// Data for the reduction-based clauses.
12566struct ReductionData {
12567 /// List of original reduction items.
12568 SmallVector<Expr *, 8> Vars;
12569 /// List of private copies of the reduction items.
12570 SmallVector<Expr *, 8> Privates;
12571 /// LHS expressions for the reduction_op expressions.
12572 SmallVector<Expr *, 8> LHSs;
12573 /// RHS expressions for the reduction_op expressions.
12574 SmallVector<Expr *, 8> RHSs;
12575 /// Reduction operation expression.
12576 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000012577 /// Taskgroup descriptors for the corresponding reduction items in
12578 /// in_reduction clauses.
12579 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012580 /// List of captures for clause.
12581 SmallVector<Decl *, 4> ExprCaptures;
12582 /// List of postupdate expressions.
12583 SmallVector<Expr *, 4> ExprPostUpdates;
12584 ReductionData() = delete;
12585 /// Reserves required memory for the reduction data.
12586 ReductionData(unsigned Size) {
12587 Vars.reserve(Size);
12588 Privates.reserve(Size);
12589 LHSs.reserve(Size);
12590 RHSs.reserve(Size);
12591 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000012592 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012593 ExprCaptures.reserve(Size);
12594 ExprPostUpdates.reserve(Size);
12595 }
12596 /// Stores reduction item and reduction operation only (required for dependent
12597 /// reduction item).
12598 void push(Expr *Item, Expr *ReductionOp) {
12599 Vars.emplace_back(Item);
12600 Privates.emplace_back(nullptr);
12601 LHSs.emplace_back(nullptr);
12602 RHSs.emplace_back(nullptr);
12603 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012604 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012605 }
12606 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000012607 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
12608 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012609 Vars.emplace_back(Item);
12610 Privates.emplace_back(Private);
12611 LHSs.emplace_back(LHS);
12612 RHSs.emplace_back(RHS);
12613 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000012614 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012615 }
12616};
12617} // namespace
12618
Alexey Bataeve3727102018-04-18 15:57:46 +000012619static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012620 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
12621 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
12622 const Expr *Length = OASE->getLength();
12623 if (Length == nullptr) {
12624 // For array sections of the form [1:] or [:], we would need to analyze
12625 // the lower bound...
12626 if (OASE->getColonLoc().isValid())
12627 return false;
12628
12629 // This is an array subscript which has implicit length 1!
12630 SingleElement = true;
12631 ArraySizes.push_back(llvm::APSInt::get(1));
12632 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012633 Expr::EvalResult Result;
12634 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012635 return false;
12636
Fangrui Song407659a2018-11-30 23:41:18 +000012637 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012638 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
12639 ArraySizes.push_back(ConstantLengthValue);
12640 }
12641
12642 // Get the base of this array section and walk up from there.
12643 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
12644
12645 // We require length = 1 for all array sections except the right-most to
12646 // guarantee that the memory region is contiguous and has no holes in it.
12647 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
12648 Length = TempOASE->getLength();
12649 if (Length == nullptr) {
12650 // For array sections of the form [1:] or [:], we would need to analyze
12651 // the lower bound...
12652 if (OASE->getColonLoc().isValid())
12653 return false;
12654
12655 // This is an array subscript which has implicit length 1!
12656 ArraySizes.push_back(llvm::APSInt::get(1));
12657 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000012658 Expr::EvalResult Result;
12659 if (!Length->EvaluateAsInt(Result, Context))
12660 return false;
12661
12662 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
12663 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012664 return false;
12665
12666 ArraySizes.push_back(ConstantLengthValue);
12667 }
12668 Base = TempOASE->getBase()->IgnoreParenImpCasts();
12669 }
12670
12671 // If we have a single element, we don't need to add the implicit lengths.
12672 if (!SingleElement) {
12673 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
12674 // Has implicit length 1!
12675 ArraySizes.push_back(llvm::APSInt::get(1));
12676 Base = TempASE->getBase()->IgnoreParenImpCasts();
12677 }
12678 }
12679
12680 // This array section can be privatized as a single value or as a constant
12681 // sized array.
12682 return true;
12683}
12684
Alexey Bataeve3727102018-04-18 15:57:46 +000012685static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000012686 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
12687 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12688 SourceLocation ColonLoc, SourceLocation EndLoc,
12689 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012690 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012691 DeclarationName DN = ReductionId.getName();
12692 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012693 BinaryOperatorKind BOK = BO_Comma;
12694
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012695 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012696 // OpenMP [2.14.3.6, reduction clause]
12697 // C
12698 // reduction-identifier is either an identifier or one of the following
12699 // operators: +, -, *, &, |, ^, && and ||
12700 // C++
12701 // reduction-identifier is either an id-expression or one of the following
12702 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000012703 switch (OOK) {
12704 case OO_Plus:
12705 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012706 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012707 break;
12708 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012709 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012710 break;
12711 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012712 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012713 break;
12714 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012715 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012716 break;
12717 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012718 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012719 break;
12720 case OO_AmpAmp:
12721 BOK = BO_LAnd;
12722 break;
12723 case OO_PipePipe:
12724 BOK = BO_LOr;
12725 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012726 case OO_New:
12727 case OO_Delete:
12728 case OO_Array_New:
12729 case OO_Array_Delete:
12730 case OO_Slash:
12731 case OO_Percent:
12732 case OO_Tilde:
12733 case OO_Exclaim:
12734 case OO_Equal:
12735 case OO_Less:
12736 case OO_Greater:
12737 case OO_LessEqual:
12738 case OO_GreaterEqual:
12739 case OO_PlusEqual:
12740 case OO_MinusEqual:
12741 case OO_StarEqual:
12742 case OO_SlashEqual:
12743 case OO_PercentEqual:
12744 case OO_CaretEqual:
12745 case OO_AmpEqual:
12746 case OO_PipeEqual:
12747 case OO_LessLess:
12748 case OO_GreaterGreater:
12749 case OO_LessLessEqual:
12750 case OO_GreaterGreaterEqual:
12751 case OO_EqualEqual:
12752 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000012753 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012754 case OO_PlusPlus:
12755 case OO_MinusMinus:
12756 case OO_Comma:
12757 case OO_ArrowStar:
12758 case OO_Arrow:
12759 case OO_Call:
12760 case OO_Subscript:
12761 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000012762 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012763 case NUM_OVERLOADED_OPERATORS:
12764 llvm_unreachable("Unexpected reduction identifier");
12765 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000012766 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012767 if (II->isStr("max"))
12768 BOK = BO_GT;
12769 else if (II->isStr("min"))
12770 BOK = BO_LT;
12771 }
12772 break;
12773 }
12774 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012775 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000012776 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012777 else
12778 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000012779 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000012780
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012781 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
12782 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012783 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000012784 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000012785 // OpenMP [2.1, C/C++]
12786 // A list item is a variable or array section, subject to the restrictions
12787 // specified in Section 2.4 on page 42 and in each of the sections
12788 // describing clauses and directives for which a list appears.
12789 // OpenMP [2.14.3.3, Restrictions, p.1]
12790 // A variable that is part of another variable (as an array or
12791 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012792 if (!FirstIter && IR != ER)
12793 ++IR;
12794 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012795 SourceLocation ELoc;
12796 SourceRange ERange;
12797 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012798 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000012799 /*AllowArraySection=*/true);
12800 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012801 // Try to find 'declare reduction' corresponding construct before using
12802 // builtin/overloaded operators.
12803 QualType Type = Context.DependentTy;
12804 CXXCastPath BasePath;
12805 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012806 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012807 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012808 Expr *ReductionOp = nullptr;
12809 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012810 (DeclareReductionRef.isUnset() ||
12811 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012812 ReductionOp = DeclareReductionRef.get();
12813 // It will be analyzed later.
12814 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012815 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012816 ValueDecl *D = Res.first;
12817 if (!D)
12818 continue;
12819
Alexey Bataev88202be2017-07-27 13:20:36 +000012820 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000012821 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000012822 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
12823 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000012824 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000012825 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012826 } else if (OASE) {
12827 QualType BaseType =
12828 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
12829 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000012830 Type = ATy->getElementType();
12831 else
12832 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000012833 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012834 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012835 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000012836 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012837 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000012838
Alexey Bataevc5e02582014-06-16 07:08:35 +000012839 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12840 // A variable that appears in a private clause must not have an incomplete
12841 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000012842 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012843 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012844 continue;
12845 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000012846 // A list item that appears in a reduction clause must not be
12847 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012848 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
12849 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012850 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000012851
12852 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000012853 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
12854 // If a list-item is a reference type then it must bind to the same object
12855 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000012856 if (!ASE && !OASE) {
12857 if (VD) {
12858 VarDecl *VDDef = VD->getDefinition();
12859 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
12860 DSARefChecker Check(Stack);
12861 if (Check.Visit(VDDef->getInit())) {
12862 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
12863 << getOpenMPClauseName(ClauseKind) << ERange;
12864 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
12865 continue;
12866 }
Alexey Bataeva1764212015-09-30 09:22:36 +000012867 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000012868 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012869
Alexey Bataevbc529672018-09-28 19:33:14 +000012870 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
12871 // in a Construct]
12872 // Variables with the predetermined data-sharing attributes may not be
12873 // listed in data-sharing attributes clauses, except for the cases
12874 // listed below. For these exceptions only, listing a predetermined
12875 // variable in a data-sharing attribute clause is allowed and overrides
12876 // the variable's predetermined data-sharing attributes.
12877 // OpenMP [2.14.3.6, Restrictions, p.3]
12878 // Any number of reduction clauses can be specified on the directive,
12879 // but a list item can appear only once in the reduction clauses for that
12880 // directive.
12881 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
12882 if (DVar.CKind == OMPC_reduction) {
12883 S.Diag(ELoc, diag::err_omp_once_referenced)
12884 << getOpenMPClauseName(ClauseKind);
12885 if (DVar.RefExpr)
12886 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
12887 continue;
12888 }
12889 if (DVar.CKind != OMPC_unknown) {
12890 S.Diag(ELoc, diag::err_omp_wrong_dsa)
12891 << getOpenMPClauseName(DVar.CKind)
12892 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000012893 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012894 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000012895 }
Alexey Bataevbc529672018-09-28 19:33:14 +000012896
12897 // OpenMP [2.14.3.6, Restrictions, p.1]
12898 // A list item that appears in a reduction clause of a worksharing
12899 // construct must be shared in the parallel regions to which any of the
12900 // worksharing regions arising from the worksharing construct bind.
12901 if (isOpenMPWorksharingDirective(CurrDir) &&
12902 !isOpenMPParallelDirective(CurrDir) &&
12903 !isOpenMPTeamsDirective(CurrDir)) {
12904 DVar = Stack->getImplicitDSA(D, true);
12905 if (DVar.CKind != OMPC_shared) {
12906 S.Diag(ELoc, diag::err_omp_required_access)
12907 << getOpenMPClauseName(OMPC_reduction)
12908 << getOpenMPClauseName(OMPC_shared);
12909 reportOriginalDsa(S, Stack, D, DVar);
12910 continue;
12911 }
12912 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000012913 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012914
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012915 // Try to find 'declare reduction' corresponding construct before using
12916 // builtin/overloaded operators.
12917 CXXCastPath BasePath;
12918 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012919 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012920 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
12921 if (DeclareReductionRef.isInvalid())
12922 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012923 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012924 (DeclareReductionRef.isUnset() ||
12925 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012926 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012927 continue;
12928 }
12929 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
12930 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012931 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012932 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012933 << Type << ReductionIdRange;
12934 continue;
12935 }
12936
12937 // OpenMP [2.14.3.6, reduction clause, Restrictions]
12938 // The type of a list item that appears in a reduction clause must be valid
12939 // for the reduction-identifier. For a max or min reduction in C, the type
12940 // of the list item must be an allowed arithmetic data type: char, int,
12941 // float, double, or _Bool, possibly modified with long, short, signed, or
12942 // unsigned. For a max or min reduction in C++, the type of the list item
12943 // must be an allowed arithmetic data type: char, wchar_t, int, float,
12944 // double, or bool, possibly modified with long, short, signed, or unsigned.
12945 if (DeclareReductionRef.isUnset()) {
12946 if ((BOK == BO_GT || BOK == BO_LT) &&
12947 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012948 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
12949 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000012950 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012951 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012952 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12953 VarDecl::DeclarationOnly;
12954 S.Diag(D->getLocation(),
12955 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012956 << D;
12957 }
12958 continue;
12959 }
12960 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012961 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000012962 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
12963 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012964 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012965 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12966 VarDecl::DeclarationOnly;
12967 S.Diag(D->getLocation(),
12968 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012969 << D;
12970 }
12971 continue;
12972 }
12973 }
12974
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012975 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012976 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
12977 D->hasAttrs() ? &D->getAttrs() : nullptr);
12978 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
12979 D->hasAttrs() ? &D->getAttrs() : nullptr);
12980 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012981
12982 // Try if we can determine constant lengths for all array sections and avoid
12983 // the VLA.
12984 bool ConstantLengthOASE = false;
12985 if (OASE) {
12986 bool SingleElement;
12987 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000012988 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012989 Context, OASE, SingleElement, ArraySizes);
12990
12991 // If we don't have a single element, we must emit a constant array type.
12992 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012993 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012994 PrivateTy = Context.getConstantArrayType(
12995 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000012996 }
12997 }
12998
12999 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000013000 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000013001 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000013002 if (!Context.getTargetInfo().isVLASupported()) {
13003 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
13004 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13005 S.Diag(ELoc, diag::note_vla_unsupported);
13006 } else {
13007 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
13008 S.targetDiag(ELoc, diag::note_vla_unsupported);
13009 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000013010 continue;
13011 }
David Majnemer9d168222016-08-05 17:44:54 +000013012 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013013 // Create pseudo array type for private copy. The size for this array will
13014 // be generated during codegen.
13015 // For array subscripts or single variables Private Ty is the same as Type
13016 // (type of the variable or single array element).
13017 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013018 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000013019 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013020 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000013021 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013022 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013023 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013024 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013025 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013026 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013027 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
13028 D->hasAttrs() ? &D->getAttrs() : nullptr,
13029 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013030 // Add initializer for private variable.
13031 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013032 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
13033 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013034 if (DeclareReductionRef.isUsable()) {
13035 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
13036 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
13037 if (DRD->getInitializer()) {
13038 Init = DRDRef;
13039 RHSVD->setInit(DRDRef);
13040 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013041 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013042 } else {
13043 switch (BOK) {
13044 case BO_Add:
13045 case BO_Xor:
13046 case BO_Or:
13047 case BO_LOr:
13048 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
13049 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013050 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013051 break;
13052 case BO_Mul:
13053 case BO_LAnd:
13054 if (Type->isScalarType() || Type->isAnyComplexType()) {
13055 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013056 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013057 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013058 break;
13059 case BO_And: {
13060 // '&' reduction op - initializer is '~0'.
13061 QualType OrigType = Type;
13062 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
13063 Type = ComplexTy->getElementType();
13064 if (Type->isRealFloatingType()) {
13065 llvm::APFloat InitValue =
13066 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
13067 /*isIEEE=*/true);
13068 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13069 Type, ELoc);
13070 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013071 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013072 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
13073 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
13074 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13075 }
13076 if (Init && OrigType->isAnyComplexType()) {
13077 // Init = 0xFFFF + 0xFFFFi;
13078 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013079 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013080 }
13081 Type = OrigType;
13082 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013083 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013084 case BO_LT:
13085 case BO_GT: {
13086 // 'min' reduction op - initializer is 'Largest representable number in
13087 // the reduction list item type'.
13088 // 'max' reduction op - initializer is 'Least representable number in
13089 // the reduction list item type'.
13090 if (Type->isIntegerType() || Type->isPointerType()) {
13091 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013092 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013093 QualType IntTy =
13094 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
13095 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013096 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
13097 : llvm::APInt::getMinValue(Size)
13098 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
13099 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013100 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
13101 if (Type->isPointerType()) {
13102 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013103 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000013104 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013105 if (CastExpr.isInvalid())
13106 continue;
13107 Init = CastExpr.get();
13108 }
13109 } else if (Type->isRealFloatingType()) {
13110 llvm::APFloat InitValue = llvm::APFloat::getLargest(
13111 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
13112 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
13113 Type, ELoc);
13114 }
13115 break;
13116 }
13117 case BO_PtrMemD:
13118 case BO_PtrMemI:
13119 case BO_MulAssign:
13120 case BO_Div:
13121 case BO_Rem:
13122 case BO_Sub:
13123 case BO_Shl:
13124 case BO_Shr:
13125 case BO_LE:
13126 case BO_GE:
13127 case BO_EQ:
13128 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000013129 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013130 case BO_AndAssign:
13131 case BO_XorAssign:
13132 case BO_OrAssign:
13133 case BO_Assign:
13134 case BO_AddAssign:
13135 case BO_SubAssign:
13136 case BO_DivAssign:
13137 case BO_RemAssign:
13138 case BO_ShlAssign:
13139 case BO_ShrAssign:
13140 case BO_Comma:
13141 llvm_unreachable("Unexpected reduction operation");
13142 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013143 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013144 if (Init && DeclareReductionRef.isUnset())
13145 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
13146 else if (!Init)
13147 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013148 if (RHSVD->isInvalidDecl())
13149 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000013150 if (!RHSVD->hasInit() &&
13151 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013152 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
13153 << Type << ReductionIdRange;
13154 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13155 VarDecl::DeclarationOnly;
13156 S.Diag(D->getLocation(),
13157 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000013158 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013159 continue;
13160 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013161 // Store initializer for single element in private copy. Will be used during
13162 // codegen.
13163 PrivateVD->setInit(RHSVD->getInit());
13164 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000013165 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013166 ExprResult ReductionOp;
13167 if (DeclareReductionRef.isUsable()) {
13168 QualType RedTy = DeclareReductionRef.get()->getType();
13169 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013170 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
13171 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013172 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013173 LHS = S.DefaultLvalueConversion(LHS.get());
13174 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013175 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13176 CK_UncheckedDerivedToBase, LHS.get(),
13177 &BasePath, LHS.get()->getValueKind());
13178 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
13179 CK_UncheckedDerivedToBase, RHS.get(),
13180 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013181 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013182 FunctionProtoType::ExtProtoInfo EPI;
13183 QualType Params[] = {PtrRedTy, PtrRedTy};
13184 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
13185 auto *OVE = new (Context) OpaqueValueExpr(
13186 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013187 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013188 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000013189 ReductionOp =
13190 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013191 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013192 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013193 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013194 if (ReductionOp.isUsable()) {
13195 if (BOK != BO_LT && BOK != BO_GT) {
13196 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013197 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013198 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013199 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000013200 auto *ConditionalOp = new (Context)
13201 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
13202 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013203 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013204 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013205 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013206 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013207 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013208 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
13209 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013210 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013211 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013212 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013213 }
13214
Alexey Bataevfa312f32017-07-21 18:48:21 +000013215 // OpenMP [2.15.4.6, Restrictions, p.2]
13216 // A list item that appears in an in_reduction clause of a task construct
13217 // must appear in a task_reduction clause of a construct associated with a
13218 // taskgroup region that includes the participating task in its taskgroup
13219 // set. The construct associated with the innermost region that meets this
13220 // condition must specify the same reduction-identifier as the in_reduction
13221 // clause.
13222 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000013223 SourceRange ParentSR;
13224 BinaryOperatorKind ParentBOK;
13225 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000013226 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000013227 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013228 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
13229 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013230 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000013231 Stack->getTopMostTaskgroupReductionData(
13232 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013233 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
13234 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
13235 if (!IsParentBOK && !IsParentReductionOp) {
13236 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
13237 continue;
13238 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000013239 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
13240 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
13241 IsParentReductionOp) {
13242 bool EmitError = true;
13243 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
13244 llvm::FoldingSetNodeID RedId, ParentRedId;
13245 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
13246 DeclareReductionRef.get()->Profile(RedId, Context,
13247 /*Canonical=*/true);
13248 EmitError = RedId != ParentRedId;
13249 }
13250 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013251 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000013252 diag::err_omp_reduction_identifier_mismatch)
13253 << ReductionIdRange << RefExpr->getSourceRange();
13254 S.Diag(ParentSR.getBegin(),
13255 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000013256 << ParentSR
13257 << (IsParentBOK ? ParentBOKDSA.RefExpr
13258 : ParentReductionOpDSA.RefExpr)
13259 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000013260 continue;
13261 }
13262 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013263 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
13264 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000013265 }
13266
Alexey Bataev60da77e2016-02-29 05:54:20 +000013267 DeclRefExpr *Ref = nullptr;
13268 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013269 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013270 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013271 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013272 VarsExpr =
13273 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
13274 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000013275 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013276 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013277 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013278 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013279 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013280 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013281 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000013282 if (!RefRes.isUsable())
13283 continue;
13284 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013285 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13286 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000013287 if (!PostUpdateRes.isUsable())
13288 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013289 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
13290 Stack->getCurrentDirective() == OMPD_taskgroup) {
13291 S.Diag(RefExpr->getExprLoc(),
13292 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000013293 << RefExpr->getSourceRange();
13294 continue;
13295 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013296 RD.ExprPostUpdates.emplace_back(
13297 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000013298 }
13299 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013300 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000013301 // All reduction items are still marked as reduction (to do not increase
13302 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013303 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013304 if (CurrDir == OMPD_taskgroup) {
13305 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013306 Stack->addTaskgroupReductionData(D, ReductionIdRange,
13307 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000013308 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000013309 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000013310 }
Alexey Bataev88202be2017-07-27 13:20:36 +000013311 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
13312 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013313 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013314 return RD.Vars.empty();
13315}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013316
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013317OMPClause *Sema::ActOnOpenMPReductionClause(
13318 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13319 SourceLocation ColonLoc, SourceLocation EndLoc,
13320 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13321 ArrayRef<Expr *> UnresolvedReductions) {
13322 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013323 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013324 StartLoc, LParenLoc, ColonLoc, EndLoc,
13325 ReductionIdScopeSpec, ReductionId,
13326 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013327 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000013328
Alexey Bataevc5e02582014-06-16 07:08:35 +000013329 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013330 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13331 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13332 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13333 buildPreInits(Context, RD.ExprCaptures),
13334 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000013335}
13336
Alexey Bataev169d96a2017-07-18 20:17:46 +000013337OMPClause *Sema::ActOnOpenMPTaskReductionClause(
13338 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13339 SourceLocation ColonLoc, SourceLocation EndLoc,
13340 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13341 ArrayRef<Expr *> UnresolvedReductions) {
13342 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013343 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
13344 StartLoc, LParenLoc, ColonLoc, EndLoc,
13345 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000013346 UnresolvedReductions, RD))
13347 return nullptr;
13348
13349 return OMPTaskReductionClause::Create(
13350 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13351 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
13352 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
13353 buildPreInits(Context, RD.ExprCaptures),
13354 buildPostUpdate(*this, RD.ExprPostUpdates));
13355}
13356
Alexey Bataevfa312f32017-07-21 18:48:21 +000013357OMPClause *Sema::ActOnOpenMPInReductionClause(
13358 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13359 SourceLocation ColonLoc, SourceLocation EndLoc,
13360 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
13361 ArrayRef<Expr *> UnresolvedReductions) {
13362 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000013363 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013364 StartLoc, LParenLoc, ColonLoc, EndLoc,
13365 ReductionIdScopeSpec, ReductionId,
13366 UnresolvedReductions, RD))
13367 return nullptr;
13368
13369 return OMPInReductionClause::Create(
13370 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
13371 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000013372 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000013373 buildPreInits(Context, RD.ExprCaptures),
13374 buildPostUpdate(*this, RD.ExprPostUpdates));
13375}
13376
Alexey Bataevecba70f2016-04-12 11:02:11 +000013377bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
13378 SourceLocation LinLoc) {
13379 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
13380 LinKind == OMPC_LINEAR_unknown) {
13381 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
13382 return true;
13383 }
13384 return false;
13385}
13386
Alexey Bataeve3727102018-04-18 15:57:46 +000013387bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000013388 OpenMPLinearClauseKind LinKind,
13389 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013390 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000013391 // A variable must not have an incomplete type or a reference type.
13392 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
13393 return true;
13394 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
13395 !Type->isReferenceType()) {
13396 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
13397 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
13398 return true;
13399 }
13400 Type = Type.getNonReferenceType();
13401
Joel E. Dennybae586f2019-01-04 22:12:13 +000013402 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13403 // A variable that is privatized must not have a const-qualified type
13404 // unless it is of class type with a mutable member. This restriction does
13405 // not apply to the firstprivate clause.
13406 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000013407 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013408
13409 // A list item must be of integral or pointer type.
13410 Type = Type.getUnqualifiedType().getCanonicalType();
13411 const auto *Ty = Type.getTypePtrOrNull();
13412 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
13413 !Ty->isPointerType())) {
13414 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
13415 if (D) {
13416 bool IsDecl =
13417 !VD ||
13418 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
13419 Diag(D->getLocation(),
13420 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13421 << D;
13422 }
13423 return true;
13424 }
13425 return false;
13426}
13427
Alexey Bataev182227b2015-08-20 10:54:39 +000013428OMPClause *Sema::ActOnOpenMPLinearClause(
13429 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
13430 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
13431 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013432 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013433 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000013434 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013435 SmallVector<Decl *, 4> ExprCaptures;
13436 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013437 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000013438 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000013439 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013440 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013441 SourceLocation ELoc;
13442 SourceRange ERange;
13443 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013444 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013445 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000013446 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013447 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013448 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013449 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000013450 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013451 ValueDecl *D = Res.first;
13452 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000013453 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000013454
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013455 QualType Type = D->getType();
13456 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000013457
13458 // OpenMP [2.14.3.7, linear clause]
13459 // A list-item cannot appear in more than one linear clause.
13460 // A list-item that appears in a linear clause cannot appear in any
13461 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013462 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000013463 if (DVar.RefExpr) {
13464 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13465 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000013466 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000013467 continue;
13468 }
13469
Alexey Bataevecba70f2016-04-12 11:02:11 +000013470 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000013471 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000013472 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000013473
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013474 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000013475 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013476 buildVarDecl(*this, ELoc, Type, D->getName(),
13477 D->hasAttrs() ? &D->getAttrs() : nullptr,
13478 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013479 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013480 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013481 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013482 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013483 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013484 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013485 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013486 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000013487 ExprCaptures.push_back(Ref->getDecl());
13488 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
13489 ExprResult RefRes = DefaultLvalueConversion(Ref);
13490 if (!RefRes.isUsable())
13491 continue;
13492 ExprResult PostUpdateRes =
13493 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
13494 SimpleRefExpr, RefRes.get());
13495 if (!PostUpdateRes.isUsable())
13496 continue;
13497 ExprPostUpdates.push_back(
13498 IgnoredValueConversions(PostUpdateRes.get()).get());
13499 }
13500 }
13501 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013502 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013503 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013504 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013505 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013506 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013507 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013508 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013509
13510 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013511 Vars.push_back((VD || CurContext->isDependentContext())
13512 ? RefExpr->IgnoreParens()
13513 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013514 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000013515 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000013516 }
13517
13518 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013519 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013520
13521 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000013522 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000013523 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
13524 !Step->isInstantiationDependent() &&
13525 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013526 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000013527 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000013528 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000013529 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000013530 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000013531
Alexander Musman3276a272015-03-21 10:12:56 +000013532 // Build var to save the step value.
13533 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013534 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000013535 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000013536 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000013537 ExprResult CalcStep =
13538 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013539 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013540
Alexander Musman8dba6642014-04-22 13:09:42 +000013541 // Warn about zero linear step (it would be probably better specified as
13542 // making corresponding variables 'const').
13543 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000013544 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
13545 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000013546 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
13547 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000013548 if (!IsConstant && CalcStep.isUsable()) {
13549 // Calculate the step beforehand instead of doing this on each iteration.
13550 // (This is not used if the number of iterations may be kfold-ed).
13551 CalcStepExpr = CalcStep.get();
13552 }
Alexander Musman8dba6642014-04-22 13:09:42 +000013553 }
13554
Alexey Bataev182227b2015-08-20 10:54:39 +000013555 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
13556 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013557 StepExpr, CalcStepExpr,
13558 buildPreInits(Context, ExprCaptures),
13559 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000013560}
13561
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013562static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
13563 Expr *NumIterations, Sema &SemaRef,
13564 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000013565 // Walk the vars and build update/final expressions for the CodeGen.
13566 SmallVector<Expr *, 8> Updates;
13567 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000013568 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000013569 Expr *Step = Clause.getStep();
13570 Expr *CalcStep = Clause.getCalcStep();
13571 // OpenMP [2.14.3.7, linear clause]
13572 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000013573 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000013574 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013575 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000013576 Step = cast<BinaryOperator>(CalcStep)->getLHS();
13577 bool HasErrors = false;
13578 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013579 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000013580 OpenMPLinearClauseKind LinKind = Clause.getModifier();
13581 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013582 SourceLocation ELoc;
13583 SourceRange ERange;
13584 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013585 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013586 ValueDecl *D = Res.first;
13587 if (Res.second || !D) {
13588 Updates.push_back(nullptr);
13589 Finals.push_back(nullptr);
13590 HasErrors = true;
13591 continue;
13592 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013593 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000013594 // OpenMP [2.15.11, distribute simd Construct]
13595 // A list item may not appear in a linear clause, unless it is the loop
13596 // iteration variable.
13597 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
13598 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
13599 SemaRef.Diag(ELoc,
13600 diag::err_omp_linear_distribute_var_non_loop_iteration);
13601 Updates.push_back(nullptr);
13602 Finals.push_back(nullptr);
13603 HasErrors = true;
13604 continue;
13605 }
Alexander Musman3276a272015-03-21 10:12:56 +000013606 Expr *InitExpr = *CurInit;
13607
13608 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000013609 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000013610 Expr *CapturedRef;
13611 if (LinKind == OMPC_LINEAR_uval)
13612 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
13613 else
13614 CapturedRef =
13615 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
13616 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
13617 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000013618
13619 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013620 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000013621 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000013622 Update = buildCounterUpdate(
13623 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
13624 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013625 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013626 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013627 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013628 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000013629
13630 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013631 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000013632 if (!Info.first)
13633 Final =
13634 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000013635 InitExpr, NumIterations, Step, /*Subtract=*/false,
13636 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013637 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013638 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013639 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013640 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000013641
Alexander Musman3276a272015-03-21 10:12:56 +000013642 if (!Update.isUsable() || !Final.isUsable()) {
13643 Updates.push_back(nullptr);
13644 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000013645 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013646 HasErrors = true;
13647 } else {
13648 Updates.push_back(Update.get());
13649 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000013650 if (!Info.first)
13651 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000013652 }
Richard Trieucc3949d2016-02-18 22:34:54 +000013653 ++CurInit;
13654 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000013655 }
Alexey Bataev195ae902019-08-08 13:42:45 +000013656 if (Expr *S = Clause.getStep())
13657 UsedExprs.push_back(S);
13658 // Fill the remaining part with the nullptr.
13659 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000013660 Clause.setUpdates(Updates);
13661 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000013662 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000013663 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000013664}
13665
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013666OMPClause *Sema::ActOnOpenMPAlignedClause(
13667 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
13668 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013669 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013670 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000013671 assert(RefExpr && "NULL expr in OpenMP linear clause.");
13672 SourceLocation ELoc;
13673 SourceRange ERange;
13674 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013675 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000013676 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013677 // It will be analyzed later.
13678 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013679 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000013680 ValueDecl *D = Res.first;
13681 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013682 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013683
Alexey Bataev1efd1662016-03-29 10:59:56 +000013684 QualType QType = D->getType();
13685 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013686
13687 // OpenMP [2.8.1, simd construct, Restrictions]
13688 // The type of list items appearing in the aligned clause must be
13689 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013690 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013691 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000013692 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013693 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000013694 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013695 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000013696 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013697 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000013698 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013699 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000013700 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013701 continue;
13702 }
13703
13704 // OpenMP [2.8.1, simd construct, Restrictions]
13705 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000013706 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000013707 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013708 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
13709 << getOpenMPClauseName(OMPC_aligned);
13710 continue;
13711 }
13712
Alexey Bataev1efd1662016-03-29 10:59:56 +000013713 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013714 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000013715 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13716 Vars.push_back(DefaultFunctionArrayConversion(
13717 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
13718 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000013719 }
13720
13721 // OpenMP [2.8.1, simd construct, Description]
13722 // The parameter of the aligned clause, alignment, must be a constant
13723 // positive integer expression.
13724 // If no optional parameter is specified, implementation-defined default
13725 // alignments for SIMD instructions on the target platforms are assumed.
13726 if (Alignment != nullptr) {
13727 ExprResult AlignResult =
13728 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
13729 if (AlignResult.isInvalid())
13730 return nullptr;
13731 Alignment = AlignResult.get();
13732 }
13733 if (Vars.empty())
13734 return nullptr;
13735
13736 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
13737 EndLoc, Vars, Alignment);
13738}
13739
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013740OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
13741 SourceLocation StartLoc,
13742 SourceLocation LParenLoc,
13743 SourceLocation EndLoc) {
13744 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013745 SmallVector<Expr *, 8> SrcExprs;
13746 SmallVector<Expr *, 8> DstExprs;
13747 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000013748 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000013749 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
13750 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013751 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013752 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013753 SrcExprs.push_back(nullptr);
13754 DstExprs.push_back(nullptr);
13755 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013756 continue;
13757 }
13758
Alexey Bataeved09d242014-05-28 05:53:51 +000013759 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013760 // OpenMP [2.1, C/C++]
13761 // A list item is a variable name.
13762 // OpenMP [2.14.4.1, Restrictions, p.1]
13763 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000013764 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013765 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000013766 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
13767 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013768 continue;
13769 }
13770
13771 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013772 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013773
13774 QualType Type = VD->getType();
13775 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
13776 // It will be analyzed later.
13777 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013778 SrcExprs.push_back(nullptr);
13779 DstExprs.push_back(nullptr);
13780 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013781 continue;
13782 }
13783
13784 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
13785 // A list item that appears in a copyin clause must be threadprivate.
13786 if (!DSAStack->isThreadPrivate(VD)) {
13787 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000013788 << getOpenMPClauseName(OMPC_copyin)
13789 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013790 continue;
13791 }
13792
13793 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13794 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000013795 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013796 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013797 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
13798 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013799 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000013800 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013801 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013802 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000013803 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013804 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000013805 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013806 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013807 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013808 // For arrays generate assignment operation for single element and replace
13809 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013810 ExprResult AssignmentOp =
13811 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
13812 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013813 if (AssignmentOp.isInvalid())
13814 continue;
13815 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013816 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013817 if (AssignmentOp.isInvalid())
13818 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013819
13820 DSAStack->addDSA(VD, DE, OMPC_copyin);
13821 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013822 SrcExprs.push_back(PseudoSrcExpr);
13823 DstExprs.push_back(PseudoDstExpr);
13824 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013825 }
13826
Alexey Bataeved09d242014-05-28 05:53:51 +000013827 if (Vars.empty())
13828 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013829
Alexey Bataevf56f98c2015-04-16 05:39:01 +000013830 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
13831 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000013832}
13833
Alexey Bataevbae9a792014-06-27 10:37:06 +000013834OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
13835 SourceLocation StartLoc,
13836 SourceLocation LParenLoc,
13837 SourceLocation EndLoc) {
13838 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000013839 SmallVector<Expr *, 8> SrcExprs;
13840 SmallVector<Expr *, 8> DstExprs;
13841 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000013842 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000013843 assert(RefExpr && "NULL expr in OpenMP linear clause.");
13844 SourceLocation ELoc;
13845 SourceRange ERange;
13846 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000013847 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000013848 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000013849 // It will be analyzed later.
13850 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013851 SrcExprs.push_back(nullptr);
13852 DstExprs.push_back(nullptr);
13853 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013854 }
Alexey Bataeve122da12016-03-17 10:50:17 +000013855 ValueDecl *D = Res.first;
13856 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000013857 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013858
Alexey Bataeve122da12016-03-17 10:50:17 +000013859 QualType Type = D->getType();
13860 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013861
13862 // OpenMP [2.14.4.2, Restrictions, p.2]
13863 // A list item that appears in a copyprivate clause may not appear in a
13864 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000013865 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013866 DSAStackTy::DSAVarData DVar =
13867 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013868 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
13869 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000013870 Diag(ELoc, diag::err_omp_wrong_dsa)
13871 << getOpenMPClauseName(DVar.CKind)
13872 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013873 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013874 continue;
13875 }
13876
13877 // OpenMP [2.11.4.2, Restrictions, p.1]
13878 // All list items that appear in a copyprivate clause must be either
13879 // threadprivate or private in the enclosing context.
13880 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000013881 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013882 if (DVar.CKind == OMPC_shared) {
13883 Diag(ELoc, diag::err_omp_required_access)
13884 << getOpenMPClauseName(OMPC_copyprivate)
13885 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000013886 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013887 continue;
13888 }
13889 }
13890 }
13891
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013892 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000013893 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013894 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013895 << getOpenMPClauseName(OMPC_copyprivate) << Type
13896 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013897 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000013898 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013899 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000013900 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013901 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000013902 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000013903 continue;
13904 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013905
Alexey Bataevbae9a792014-06-27 10:37:06 +000013906 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
13907 // A variable of class type (or array thereof) that appears in a
13908 // copyin clause requires an accessible, unambiguous copy assignment
13909 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013910 Type = Context.getBaseElementType(Type.getNonReferenceType())
13911 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013912 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013913 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000013914 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013915 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
13916 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013917 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000013918 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013919 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
13920 ExprResult AssignmentOp = BuildBinOp(
13921 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013922 if (AssignmentOp.isInvalid())
13923 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013924 AssignmentOp =
13925 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000013926 if (AssignmentOp.isInvalid())
13927 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000013928
13929 // No need to mark vars as copyprivate, they are already threadprivate or
13930 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000013931 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000013932 Vars.push_back(
13933 VD ? RefExpr->IgnoreParens()
13934 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000013935 SrcExprs.push_back(PseudoSrcExpr);
13936 DstExprs.push_back(PseudoDstExpr);
13937 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000013938 }
13939
13940 if (Vars.empty())
13941 return nullptr;
13942
Alexey Bataeva63048e2015-03-23 06:18:07 +000013943 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13944 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000013945}
13946
Alexey Bataev6125da92014-07-21 11:26:11 +000013947OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
13948 SourceLocation StartLoc,
13949 SourceLocation LParenLoc,
13950 SourceLocation EndLoc) {
13951 if (VarList.empty())
13952 return nullptr;
13953
13954 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
13955}
Alexey Bataevdea47612014-07-23 07:46:59 +000013956
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013957OMPClause *
13958Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
13959 SourceLocation DepLoc, SourceLocation ColonLoc,
13960 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13961 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013962 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013963 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000013964 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013965 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000013966 return nullptr;
13967 }
13968 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013969 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
13970 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000013971 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013972 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000013973 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
13974 /*Last=*/OMPC_DEPEND_unknown, Except)
13975 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013976 return nullptr;
13977 }
13978 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000013979 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013980 llvm::APSInt DepCounter(/*BitWidth=*/32);
13981 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000013982 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
13983 if (const Expr *OrderedCountExpr =
13984 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013985 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
13986 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013987 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013988 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013989 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000013990 assert(RefExpr && "NULL expr in OpenMP shared clause.");
13991 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
13992 // It will be analyzed later.
13993 Vars.push_back(RefExpr);
13994 continue;
13995 }
13996
13997 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000013998 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000013999 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000014000 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014001 DepCounter >= TotalDepCount) {
14002 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
14003 continue;
14004 }
14005 ++DepCounter;
14006 // OpenMP [2.13.9, Summary]
14007 // depend(dependence-type : vec), where dependence-type is:
14008 // 'sink' and where vec is the iteration vector, which has the form:
14009 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
14010 // where n is the value specified by the ordered clause in the loop
14011 // directive, xi denotes the loop iteration variable of the i-th nested
14012 // loop associated with the loop directive, and di is a constant
14013 // non-negative integer.
14014 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014015 // It will be analyzed later.
14016 Vars.push_back(RefExpr);
14017 continue;
14018 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014019 SimpleExpr = SimpleExpr->IgnoreImplicit();
14020 OverloadedOperatorKind OOK = OO_None;
14021 SourceLocation OOLoc;
14022 Expr *LHS = SimpleExpr;
14023 Expr *RHS = nullptr;
14024 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
14025 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
14026 OOLoc = BO->getOperatorLoc();
14027 LHS = BO->getLHS()->IgnoreParenImpCasts();
14028 RHS = BO->getRHS()->IgnoreParenImpCasts();
14029 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
14030 OOK = OCE->getOperator();
14031 OOLoc = OCE->getOperatorLoc();
14032 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
14033 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
14034 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
14035 OOK = MCE->getMethodDecl()
14036 ->getNameInfo()
14037 .getName()
14038 .getCXXOverloadedOperator();
14039 OOLoc = MCE->getCallee()->getExprLoc();
14040 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
14041 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014042 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014043 SourceLocation ELoc;
14044 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000014045 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014046 if (Res.second) {
14047 // It will be analyzed later.
14048 Vars.push_back(RefExpr);
14049 }
14050 ValueDecl *D = Res.first;
14051 if (!D)
14052 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014053
Alexey Bataev17daedf2018-02-15 22:42:57 +000014054 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
14055 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
14056 continue;
14057 }
14058 if (RHS) {
14059 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
14060 RHS, OMPC_depend, /*StrictlyPositive=*/false);
14061 if (RHSRes.isInvalid())
14062 continue;
14063 }
14064 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014065 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014066 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014067 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000014068 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000014069 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000014070 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
14071 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000014072 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000014073 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000014074 continue;
14075 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014076 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000014077 } else {
14078 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
14079 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
14080 (ASE &&
14081 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
14082 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
14083 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14084 << RefExpr->getSourceRange();
14085 continue;
14086 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000014087
14088 ExprResult Res;
14089 {
14090 Sema::TentativeAnalysisScope Trap(*this);
14091 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
14092 RefExpr->IgnoreParenImpCasts());
14093 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014094 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
14095 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
14096 << RefExpr->getSourceRange();
14097 continue;
14098 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014099 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014100 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000014101 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000014102
14103 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
14104 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000014105 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000014106 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
14107 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
14108 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
14109 }
14110 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
14111 Vars.empty())
14112 return nullptr;
14113
Alexey Bataev8b427062016-05-25 12:36:08 +000014114 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000014115 DepKind, DepLoc, ColonLoc, Vars,
14116 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000014117 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
14118 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000014119 DSAStack->addDoacrossDependClause(C, OpsOffs);
14120 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000014121}
Michael Wonge710d542015-08-07 16:16:36 +000014122
14123OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
14124 SourceLocation LParenLoc,
14125 SourceLocation EndLoc) {
14126 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014127 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000014128
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014129 // OpenMP [2.9.1, Restrictions]
14130 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014131 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000014132 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014133 return nullptr;
14134
Alexey Bataev931e19b2017-10-02 16:32:39 +000014135 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014136 OpenMPDirectiveKind CaptureRegion =
14137 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
14138 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014139 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014140 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000014141 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14142 HelperValStmt = buildPreInits(Context, Captures);
14143 }
14144
Alexey Bataev8451efa2018-01-15 19:06:12 +000014145 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
14146 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000014147}
Kelvin Li0bff7af2015-11-23 05:32:03 +000014148
Alexey Bataeve3727102018-04-18 15:57:46 +000014149static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000014150 DSAStackTy *Stack, QualType QTy,
14151 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000014152 NamedDecl *ND;
14153 if (QTy->isIncompleteType(&ND)) {
14154 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
14155 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014156 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000014157 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
14158 !QTy.isTrivialType(SemaRef.Context))
14159 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014160 return true;
14161}
14162
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000014163/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014164/// (array section or array subscript) does NOT specify the whole size of the
14165/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014166static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014167 const Expr *E,
14168 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014169 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014170
14171 // If this is an array subscript, it refers to the whole size if the size of
14172 // the dimension is constant and equals 1. Also, an array section assumes the
14173 // format of an array subscript if no colon is used.
14174 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014175 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014176 return ATy->getSize().getSExtValue() != 1;
14177 // Size can't be evaluated statically.
14178 return false;
14179 }
14180
14181 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014182 const Expr *LowerBound = OASE->getLowerBound();
14183 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014184
14185 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000014186 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014187 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000014188 Expr::EvalResult Result;
14189 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014190 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000014191
14192 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014193 if (ConstLowerBound.getSExtValue())
14194 return true;
14195 }
14196
14197 // If we don't have a length we covering the whole dimension.
14198 if (!Length)
14199 return false;
14200
14201 // If the base is a pointer, we don't have a way to get the size of the
14202 // pointee.
14203 if (BaseQTy->isPointerType())
14204 return false;
14205
14206 // We can only check if the length is the same as the size of the dimension
14207 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000014208 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014209 if (!CATy)
14210 return false;
14211
Fangrui Song407659a2018-11-30 23:41:18 +000014212 Expr::EvalResult Result;
14213 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014214 return false; // Can't get the integer value as a constant.
14215
Fangrui Song407659a2018-11-30 23:41:18 +000014216 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014217 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
14218}
14219
14220// Return true if it can be proven that the provided array expression (array
14221// section or array subscript) does NOT specify a single element of the array
14222// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014223static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000014224 const Expr *E,
14225 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014226 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014227
14228 // An array subscript always refer to a single element. Also, an array section
14229 // assumes the format of an array subscript if no colon is used.
14230 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
14231 return false;
14232
14233 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000014234 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014235
14236 // If we don't have a length we have to check if the array has unitary size
14237 // for this dimension. Also, we should always expect a length if the base type
14238 // is pointer.
14239 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014240 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014241 return ATy->getSize().getSExtValue() != 1;
14242 // We cannot assume anything.
14243 return false;
14244 }
14245
14246 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000014247 Expr::EvalResult Result;
14248 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014249 return false; // Can't get the integer value as a constant.
14250
Fangrui Song407659a2018-11-30 23:41:18 +000014251 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014252 return ConstLength.getSExtValue() != 1;
14253}
14254
Samuel Antao661c0902016-05-26 17:39:58 +000014255// Return the expression of the base of the mappable expression or null if it
14256// cannot be determined and do all the necessary checks to see if the expression
14257// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000014258// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014259static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000014260 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000014261 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014262 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014263 SourceLocation ELoc = E->getExprLoc();
14264 SourceRange ERange = E->getSourceRange();
14265
14266 // The base of elements of list in a map clause have to be either:
14267 // - a reference to variable or field.
14268 // - a member expression.
14269 // - an array expression.
14270 //
14271 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
14272 // reference to 'r'.
14273 //
14274 // If we have:
14275 //
14276 // struct SS {
14277 // Bla S;
14278 // foo() {
14279 // #pragma omp target map (S.Arr[:12]);
14280 // }
14281 // }
14282 //
14283 // We want to retrieve the member expression 'this->S';
14284
Alexey Bataeve3727102018-04-18 15:57:46 +000014285 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014286
Samuel Antao5de996e2016-01-22 20:21:36 +000014287 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
14288 // If a list item is an array section, it must specify contiguous storage.
14289 //
14290 // For this restriction it is sufficient that we make sure only references
14291 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014292 // exist except in the rightmost expression (unless they cover the whole
14293 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000014294 //
14295 // r.ArrS[3:5].Arr[6:7]
14296 //
14297 // r.ArrS[3:5].x
14298 //
14299 // but these would be valid:
14300 // r.ArrS[3].Arr[6:7]
14301 //
14302 // r.ArrS[3].x
14303
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014304 bool AllowUnitySizeArraySection = true;
14305 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014306
Dmitry Polukhin644a9252016-03-11 07:58:34 +000014307 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014308 E = E->IgnoreParenImpCasts();
14309
14310 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
14311 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000014312 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014313
14314 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014315
14316 // If we got a reference to a declaration, we should not expect any array
14317 // section before that.
14318 AllowUnitySizeArraySection = false;
14319 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014320
14321 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014322 CurComponents.emplace_back(CurE, CurE->getDecl());
14323 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014324 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000014325
14326 if (isa<CXXThisExpr>(BaseE))
14327 // We found a base expression: this->Val.
14328 RelevantExpr = CurE;
14329 else
14330 E = BaseE;
14331
14332 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014333 if (!NoDiagnose) {
14334 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
14335 << CurE->getSourceRange();
14336 return nullptr;
14337 }
14338 if (RelevantExpr)
14339 return nullptr;
14340 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014341 }
14342
14343 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
14344
14345 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
14346 // A bit-field cannot appear in a map clause.
14347 //
14348 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014349 if (!NoDiagnose) {
14350 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
14351 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
14352 return nullptr;
14353 }
14354 if (RelevantExpr)
14355 return nullptr;
14356 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014357 }
14358
14359 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14360 // If the type of a list item is a reference to a type T then the type
14361 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014362 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014363
14364 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
14365 // A list item cannot be a variable that is a member of a structure with
14366 // a union type.
14367 //
Alexey Bataeve3727102018-04-18 15:57:46 +000014368 if (CurType->isUnionType()) {
14369 if (!NoDiagnose) {
14370 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
14371 << CurE->getSourceRange();
14372 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014373 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014374 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014375 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014376
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014377 // If we got a member expression, we should not expect any array section
14378 // before that:
14379 //
14380 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
14381 // If a list item is an element of a structure, only the rightmost symbol
14382 // of the variable reference can be an array section.
14383 //
14384 AllowUnitySizeArraySection = false;
14385 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014386
14387 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014388 CurComponents.emplace_back(CurE, FD);
14389 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014390 E = CurE->getBase()->IgnoreParenImpCasts();
14391
14392 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014393 if (!NoDiagnose) {
14394 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14395 << 0 << CurE->getSourceRange();
14396 return nullptr;
14397 }
14398 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000014399 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014400
14401 // If we got an array subscript that express the whole dimension we
14402 // can have any array expressions before. If it only expressing part of
14403 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000014404 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014405 E->getType()))
14406 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000014407
Patrick Lystere13b1e32019-01-02 19:28:48 +000014408 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14409 Expr::EvalResult Result;
14410 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
14411 if (!Result.Val.getInt().isNullValue()) {
14412 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14413 diag::err_omp_invalid_map_this_expr);
14414 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
14415 diag::note_omp_invalid_subscript_on_this_ptr_map);
14416 }
14417 }
14418 RelevantExpr = TE;
14419 }
14420
Samuel Antao90927002016-04-26 14:54:23 +000014421 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014422 CurComponents.emplace_back(CurE, nullptr);
14423 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014424 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000014425 E = CurE->getBase()->IgnoreParenImpCasts();
14426
Alexey Bataev27041fa2017-12-05 15:22:49 +000014427 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014428 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14429
Samuel Antao5de996e2016-01-22 20:21:36 +000014430 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14431 // If the type of a list item is a reference to a type T then the type
14432 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000014433 if (CurType->isReferenceType())
14434 CurType = CurType->getPointeeType();
14435
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014436 bool IsPointer = CurType->isAnyPointerType();
14437
14438 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014439 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
14440 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014441 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014442 }
14443
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014444 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000014445 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014446 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000014447 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014448
Samuel Antaodab51bb2016-07-18 23:22:11 +000014449 if (AllowWholeSizeArraySection) {
14450 // Any array section is currently allowed. Allowing a whole size array
14451 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014452 //
14453 // If this array section refers to the whole dimension we can still
14454 // accept other array sections before this one, except if the base is a
14455 // pointer. Otherwise, only unitary sections are accepted.
14456 if (NotWhole || IsPointer)
14457 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000014458 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014459 // A unity or whole array section is not allowed and that is not
14460 // compatible with the properties of the current array section.
14461 SemaRef.Diag(
14462 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
14463 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000014464 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000014465 }
Samuel Antao90927002016-04-26 14:54:23 +000014466
Patrick Lystere13b1e32019-01-02 19:28:48 +000014467 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
14468 Expr::EvalResult ResultR;
14469 Expr::EvalResult ResultL;
14470 if (CurE->getLength()->EvaluateAsInt(ResultR,
14471 SemaRef.getASTContext())) {
14472 if (!ResultR.Val.getInt().isOneValue()) {
14473 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14474 diag::err_omp_invalid_map_this_expr);
14475 SemaRef.Diag(CurE->getLength()->getExprLoc(),
14476 diag::note_omp_invalid_length_on_this_ptr_mapping);
14477 }
14478 }
14479 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
14480 ResultL, SemaRef.getASTContext())) {
14481 if (!ResultL.Val.getInt().isNullValue()) {
14482 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14483 diag::err_omp_invalid_map_this_expr);
14484 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
14485 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
14486 }
14487 }
14488 RelevantExpr = TE;
14489 }
14490
Samuel Antao90927002016-04-26 14:54:23 +000014491 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000014492 CurComponents.emplace_back(CurE, nullptr);
14493 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000014494 if (!NoDiagnose) {
14495 // If nothing else worked, this is not a valid map clause expression.
14496 SemaRef.Diag(
14497 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
14498 << ERange;
14499 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000014500 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014501 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014502 }
14503
14504 return RelevantExpr;
14505}
14506
14507// Return true if expression E associated with value VD has conflicts with other
14508// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000014509static bool checkMapConflicts(
14510 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000014511 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000014512 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
14513 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014514 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000014515 SourceLocation ELoc = E->getExprLoc();
14516 SourceRange ERange = E->getSourceRange();
14517
14518 // In order to easily check the conflicts we need to match each component of
14519 // the expression under test with the components of the expressions that are
14520 // already in the stack.
14521
Samuel Antao5de996e2016-01-22 20:21:36 +000014522 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014523 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014524 "Map clause expression with unexpected base!");
14525
14526 // Variables to help detecting enclosing problems in data environment nests.
14527 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000014528 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000014529
Samuel Antao90927002016-04-26 14:54:23 +000014530 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
14531 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000014532 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
14533 ERange, CKind, &EnclosingExpr,
14534 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
14535 StackComponents,
14536 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014537 assert(!StackComponents.empty() &&
14538 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000014539 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000014540 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000014541 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000014542
Samuel Antao90927002016-04-26 14:54:23 +000014543 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000014544 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000014545
Samuel Antao5de996e2016-01-22 20:21:36 +000014546 // Expressions must start from the same base. Here we detect at which
14547 // point both expressions diverge from each other and see if we can
14548 // detect if the memory referred to both expressions is contiguous and
14549 // do not overlap.
14550 auto CI = CurComponents.rbegin();
14551 auto CE = CurComponents.rend();
14552 auto SI = StackComponents.rbegin();
14553 auto SE = StackComponents.rend();
14554 for (; CI != CE && SI != SE; ++CI, ++SI) {
14555
14556 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
14557 // At most one list item can be an array item derived from a given
14558 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000014559 if (CurrentRegionOnly &&
14560 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
14561 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
14562 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
14563 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
14564 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000014565 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000014566 << CI->getAssociatedExpression()->getSourceRange();
14567 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
14568 diag::note_used_here)
14569 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000014570 return true;
14571 }
14572
14573 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000014574 if (CI->getAssociatedExpression()->getStmtClass() !=
14575 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000014576 break;
14577
14578 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000014579 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000014580 break;
14581 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000014582 // Check if the extra components of the expressions in the enclosing
14583 // data environment are redundant for the current base declaration.
14584 // If they are, the maps completely overlap, which is legal.
14585 for (; SI != SE; ++SI) {
14586 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000014587 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000014588 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000014589 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014590 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000014591 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014592 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000014593 Type =
14594 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
14595 }
14596 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000014597 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000014598 SemaRef, SI->getAssociatedExpression(), Type))
14599 break;
14600 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014601
14602 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14603 // List items of map clauses in the same construct must not share
14604 // original storage.
14605 //
14606 // If the expressions are exactly the same or one is a subset of the
14607 // other, it means they are sharing storage.
14608 if (CI == CE && SI == SE) {
14609 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014610 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000014611 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014612 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014613 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014614 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14615 << ERange;
14616 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014617 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14618 << RE->getSourceRange();
14619 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014620 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014621 // If we find the same expression in the enclosing data environment,
14622 // that is legal.
14623 IsEnclosedByDataEnvironmentExpr = true;
14624 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000014625 }
14626
Samuel Antao90927002016-04-26 14:54:23 +000014627 QualType DerivedType =
14628 std::prev(CI)->getAssociatedDeclaration()->getType();
14629 SourceLocation DerivedLoc =
14630 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000014631
14632 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
14633 // If the type of a list item is a reference to a type T then the type
14634 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000014635 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000014636
14637 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
14638 // A variable for which the type is pointer and an array section
14639 // derived from that variable must not appear as list items of map
14640 // clauses of the same construct.
14641 //
14642 // Also, cover one of the cases in:
14643 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
14644 // If any part of the original storage of a list item has corresponding
14645 // storage in the device data environment, all of the original storage
14646 // must have corresponding storage in the device data environment.
14647 //
14648 if (DerivedType->isAnyPointerType()) {
14649 if (CI == CE || SI == SE) {
14650 SemaRef.Diag(
14651 DerivedLoc,
14652 diag::err_omp_pointer_mapped_along_with_derived_section)
14653 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000014654 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14655 << RE->getSourceRange();
14656 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000014657 }
14658 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000014659 SI->getAssociatedExpression()->getStmtClass() ||
14660 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
14661 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000014662 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000014663 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000014664 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000014665 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14666 << RE->getSourceRange();
14667 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000014668 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014669 }
14670
14671 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
14672 // List items of map clauses in the same construct must not share
14673 // original storage.
14674 //
14675 // An expression is a subset of the other.
14676 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014677 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000014678 if (CI != CE || SI != SE) {
14679 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
14680 // a pointer.
14681 auto Begin =
14682 CI != CE ? CurComponents.begin() : StackComponents.begin();
14683 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
14684 auto It = Begin;
14685 while (It != End && !It->getAssociatedDeclaration())
14686 std::advance(It, 1);
14687 assert(It != End &&
14688 "Expected at least one component with the declaration.");
14689 if (It != Begin && It->getAssociatedDeclaration()
14690 ->getType()
14691 .getCanonicalType()
14692 ->isAnyPointerType()) {
14693 IsEnclosedByDataEnvironmentExpr = false;
14694 EnclosingExpr = nullptr;
14695 return false;
14696 }
14697 }
Samuel Antao661c0902016-05-26 17:39:58 +000014698 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000014699 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000014700 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000014701 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
14702 << ERange;
14703 }
Samuel Antao5de996e2016-01-22 20:21:36 +000014704 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
14705 << RE->getSourceRange();
14706 return true;
14707 }
14708
14709 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000014710 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000014711 if (!CurrentRegionOnly && SI != SE)
14712 EnclosingExpr = RE;
14713
14714 // The current expression is a subset of the expression in the data
14715 // environment.
14716 IsEnclosedByDataEnvironmentExpr |=
14717 (!CurrentRegionOnly && CI != CE && SI == SE);
14718
14719 return false;
14720 });
14721
14722 if (CurrentRegionOnly)
14723 return FoundError;
14724
14725 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
14726 // If any part of the original storage of a list item has corresponding
14727 // storage in the device data environment, all of the original storage must
14728 // have corresponding storage in the device data environment.
14729 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
14730 // If a list item is an element of a structure, and a different element of
14731 // the structure has a corresponding list item in the device data environment
14732 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000014733 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000014734 // data environment prior to the task encountering the construct.
14735 //
14736 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
14737 SemaRef.Diag(ELoc,
14738 diag::err_omp_original_storage_is_shared_and_does_not_contain)
14739 << ERange;
14740 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
14741 << EnclosingExpr->getSourceRange();
14742 return true;
14743 }
14744
14745 return FoundError;
14746}
14747
Michael Kruse4304e9d2019-02-19 16:38:20 +000014748// Look up the user-defined mapper given the mapper name and mapped type, and
14749// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000014750static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
14751 CXXScopeSpec &MapperIdScopeSpec,
14752 const DeclarationNameInfo &MapperId,
14753 QualType Type,
14754 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000014755 if (MapperIdScopeSpec.isInvalid())
14756 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000014757 // Get the actual type for the array type.
14758 if (Type->isArrayType()) {
14759 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
14760 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
14761 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014762 // Find all user-defined mappers with the given MapperId.
14763 SmallVector<UnresolvedSet<8>, 4> Lookups;
14764 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
14765 Lookup.suppressDiagnostics();
14766 if (S) {
14767 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
14768 NamedDecl *D = Lookup.getRepresentativeDecl();
14769 while (S && !S->isDeclScope(D))
14770 S = S->getParent();
14771 if (S)
14772 S = S->getParent();
14773 Lookups.emplace_back();
14774 Lookups.back().append(Lookup.begin(), Lookup.end());
14775 Lookup.clear();
14776 }
14777 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
14778 // Extract the user-defined mappers with the given MapperId.
14779 Lookups.push_back(UnresolvedSet<8>());
14780 for (NamedDecl *D : ULE->decls()) {
14781 auto *DMD = cast<OMPDeclareMapperDecl>(D);
14782 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
14783 Lookups.back().addDecl(DMD);
14784 }
14785 }
14786 // Defer the lookup for dependent types. The results will be passed through
14787 // UnresolvedMapper on instantiation.
14788 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
14789 Type->isInstantiationDependentType() ||
14790 Type->containsUnexpandedParameterPack() ||
14791 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
14792 return !D->isInvalidDecl() &&
14793 (D->getType()->isDependentType() ||
14794 D->getType()->isInstantiationDependentType() ||
14795 D->getType()->containsUnexpandedParameterPack());
14796 })) {
14797 UnresolvedSet<8> URS;
14798 for (const UnresolvedSet<8> &Set : Lookups) {
14799 if (Set.empty())
14800 continue;
14801 URS.append(Set.begin(), Set.end());
14802 }
14803 return UnresolvedLookupExpr::Create(
14804 SemaRef.Context, /*NamingClass=*/nullptr,
14805 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
14806 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
14807 }
Michael Kruse945249b2019-09-26 22:53:01 +000014808 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000014809 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14810 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000014811 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
14812 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
14813 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
14814 return ExprError();
14815 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014816 // Perform argument dependent lookup.
14817 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
14818 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
14819 // Return the first user-defined mapper with the desired type.
14820 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14821 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
14822 if (!D->isInvalidDecl() &&
14823 SemaRef.Context.hasSameType(D->getType(), Type))
14824 return D;
14825 return nullptr;
14826 }))
14827 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
14828 // Find the first user-defined mapper with a type derived from the desired
14829 // type.
14830 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
14831 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
14832 if (!D->isInvalidDecl() &&
14833 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
14834 !Type.isMoreQualifiedThan(D->getType()))
14835 return D;
14836 return nullptr;
14837 })) {
14838 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
14839 /*DetectVirtual=*/false);
14840 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
14841 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
14842 VD->getType().getUnqualifiedType()))) {
14843 if (SemaRef.CheckBaseClassAccess(
14844 Loc, VD->getType(), Type, Paths.front(),
14845 /*DiagID=*/0) != Sema::AR_inaccessible) {
14846 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
14847 }
14848 }
14849 }
14850 }
14851 // Report error if a mapper is specified, but cannot be found.
14852 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
14853 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
14854 << Type << MapperId.getName();
14855 return ExprError();
14856 }
14857 return ExprEmpty();
14858}
14859
Samuel Antao661c0902016-05-26 17:39:58 +000014860namespace {
14861// Utility struct that gathers all the related lists associated with a mappable
14862// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014863struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000014864 // The list of expressions.
14865 ArrayRef<Expr *> VarList;
14866 // The list of processed expressions.
14867 SmallVector<Expr *, 16> ProcessedVarList;
14868 // The mappble components for each expression.
14869 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
14870 // The base declaration of the variable.
14871 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000014872 // The reference to the user-defined mapper associated with every expression.
14873 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000014874
14875 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
14876 // We have a list of components and base declarations for each entry in the
14877 // variable list.
14878 VarComponents.reserve(VarList.size());
14879 VarBaseDeclarations.reserve(VarList.size());
14880 }
14881};
14882}
14883
14884// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000014885// \a CKind. In the check process the valid expressions, mappable expression
14886// components, variables, and user-defined mappers are extracted and used to
14887// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
14888// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
14889// and \a MapperId are expected to be valid if the clause kind is 'map'.
14890static void checkMappableExpressionList(
14891 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
14892 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014893 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
14894 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014895 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000014896 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014897 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
14898 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000014899 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000014900
14901 // If the identifier of user-defined mapper is not specified, it is "default".
14902 // We do not change the actual name in this clause to distinguish whether a
14903 // mapper is specified explicitly, i.e., it is not explicitly specified when
14904 // MapperId.getName() is empty.
14905 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
14906 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
14907 MapperId.setName(DeclNames.getIdentifier(
14908 &SemaRef.getASTContext().Idents.get("default")));
14909 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000014910
14911 // Iterators to find the current unresolved mapper expression.
14912 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
14913 bool UpdateUMIt = false;
14914 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000014915
Samuel Antao90927002016-04-26 14:54:23 +000014916 // Keep track of the mappable components and base declarations in this clause.
14917 // Each entry in the list is going to have a list of components associated. We
14918 // record each set of the components so that we can build the clause later on.
14919 // In the end we should have the same amount of declarations and component
14920 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000014921
Alexey Bataeve3727102018-04-18 15:57:46 +000014922 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014923 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014924 SourceLocation ELoc = RE->getExprLoc();
14925
Michael Kruse4304e9d2019-02-19 16:38:20 +000014926 // Find the current unresolved mapper expression.
14927 if (UpdateUMIt && UMIt != UMEnd) {
14928 UMIt++;
14929 assert(
14930 UMIt != UMEnd &&
14931 "Expect the size of UnresolvedMappers to match with that of VarList");
14932 }
14933 UpdateUMIt = true;
14934 if (UMIt != UMEnd)
14935 UnresolvedMapper = *UMIt;
14936
Alexey Bataeve3727102018-04-18 15:57:46 +000014937 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014938
14939 if (VE->isValueDependent() || VE->isTypeDependent() ||
14940 VE->isInstantiationDependent() ||
14941 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000014942 // Try to find the associated user-defined mapper.
14943 ExprResult ER = buildUserDefinedMapperRef(
14944 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14945 VE->getType().getCanonicalType(), UnresolvedMapper);
14946 if (ER.isInvalid())
14947 continue;
14948 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000014949 // We can only analyze this information once the missing information is
14950 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000014951 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014952 continue;
14953 }
14954
Alexey Bataeve3727102018-04-18 15:57:46 +000014955 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014956
Samuel Antao5de996e2016-01-22 20:21:36 +000014957 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000014958 SemaRef.Diag(ELoc,
14959 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000014960 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000014961 continue;
14962 }
14963
Samuel Antao90927002016-04-26 14:54:23 +000014964 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
14965 ValueDecl *CurDeclaration = nullptr;
14966
14967 // Obtain the array or member expression bases if required. Also, fill the
14968 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000014969 const Expr *BE = checkMapClauseExpressionBase(
14970 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000014971 if (!BE)
14972 continue;
14973
Samuel Antao90927002016-04-26 14:54:23 +000014974 assert(!CurComponents.empty() &&
14975 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000014976
Patrick Lystere13b1e32019-01-02 19:28:48 +000014977 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
14978 // Add store "this" pointer to class in DSAStackTy for future checking
14979 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000014980 // Try to find the associated user-defined mapper.
14981 ExprResult ER = buildUserDefinedMapperRef(
14982 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14983 VE->getType().getCanonicalType(), UnresolvedMapper);
14984 if (ER.isInvalid())
14985 continue;
14986 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000014987 // Skip restriction checking for variable or field declarations
14988 MVLI.ProcessedVarList.push_back(RE);
14989 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14990 MVLI.VarComponents.back().append(CurComponents.begin(),
14991 CurComponents.end());
14992 MVLI.VarBaseDeclarations.push_back(nullptr);
14993 continue;
14994 }
14995
Samuel Antao90927002016-04-26 14:54:23 +000014996 // For the following checks, we rely on the base declaration which is
14997 // expected to be associated with the last component. The declaration is
14998 // expected to be a variable or a field (if 'this' is being mapped).
14999 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
15000 assert(CurDeclaration && "Null decl on map clause.");
15001 assert(
15002 CurDeclaration->isCanonicalDecl() &&
15003 "Expecting components to have associated only canonical declarations.");
15004
15005 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000015006 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000015007
15008 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000015009 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015010
15011 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000015012 // threadprivate variables cannot appear in a map clause.
15013 // OpenMP 4.5 [2.10.5, target update Construct]
15014 // threadprivate variables cannot appear in a from clause.
15015 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015016 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015017 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
15018 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000015019 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015020 continue;
15021 }
15022
Samuel Antao5de996e2016-01-22 20:21:36 +000015023 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
15024 // A list item cannot appear in both a map clause and a data-sharing
15025 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000015026
Samuel Antao5de996e2016-01-22 20:21:36 +000015027 // Check conflicts with other map clause expressions. We check the conflicts
15028 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000015029 // environment, because the restrictions are different. We only have to
15030 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000015031 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015032 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015033 break;
Samuel Antao661c0902016-05-26 17:39:58 +000015034 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000015035 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000015036 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000015037 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015038
Samuel Antao661c0902016-05-26 17:39:58 +000015039 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000015040 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15041 // If the type of a list item is a reference to a type T then the type will
15042 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000015043 auto I = llvm::find_if(
15044 CurComponents,
15045 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
15046 return MC.getAssociatedDeclaration();
15047 });
15048 assert(I != CurComponents.end() && "Null decl on map clause.");
15049 QualType Type =
15050 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015051
Samuel Antao661c0902016-05-26 17:39:58 +000015052 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
15053 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000015054 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000015055 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000015056 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000015057 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000015058 continue;
15059
Samuel Antao661c0902016-05-26 17:39:58 +000015060 if (CKind == OMPC_map) {
15061 // target enter data
15062 // OpenMP [2.10.2, Restrictions, p. 99]
15063 // A map-type must be specified in all map clauses and must be either
15064 // to or alloc.
15065 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
15066 if (DKind == OMPD_target_enter_data &&
15067 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
15068 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15069 << (IsMapTypeImplicit ? 1 : 0)
15070 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15071 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015072 continue;
15073 }
Samuel Antao661c0902016-05-26 17:39:58 +000015074
15075 // target exit_data
15076 // OpenMP [2.10.3, Restrictions, p. 102]
15077 // A map-type must be specified in all map clauses and must be either
15078 // from, release, or delete.
15079 if (DKind == OMPD_target_exit_data &&
15080 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
15081 MapType == OMPC_MAP_delete)) {
15082 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
15083 << (IsMapTypeImplicit ? 1 : 0)
15084 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
15085 << getOpenMPDirectiveName(DKind);
15086 continue;
15087 }
15088
15089 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
15090 // A list item cannot appear in both a map clause and a data-sharing
15091 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000015092 //
15093 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
15094 // A list item cannot appear in both a map clause and a data-sharing
15095 // attribute clause on the same construct unless the construct is a
15096 // combined construct.
15097 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
15098 isOpenMPTargetExecutionDirective(DKind)) ||
15099 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015100 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000015101 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000015102 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000015103 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000015104 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000015105 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000015106 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000015107 continue;
15108 }
15109 }
Michael Kruse01f670d2019-02-22 22:29:42 +000015110 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015111
Michael Kruse01f670d2019-02-22 22:29:42 +000015112 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000015113 ExprResult ER = buildUserDefinedMapperRef(
15114 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
15115 Type.getCanonicalType(), UnresolvedMapper);
15116 if (ER.isInvalid())
15117 continue;
15118 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000015119
Samuel Antao90927002016-04-26 14:54:23 +000015120 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000015121 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000015122
15123 // Store the components in the stack so that they can be used to check
15124 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000015125 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
15126 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000015127
15128 // Save the components and declaration to create the clause. For purposes of
15129 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000015130 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000015131 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
15132 MVLI.VarComponents.back().append(CurComponents.begin(),
15133 CurComponents.end());
15134 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
15135 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015136 }
Samuel Antao661c0902016-05-26 17:39:58 +000015137}
15138
Michael Kruse4304e9d2019-02-19 16:38:20 +000015139OMPClause *Sema::ActOnOpenMPMapClause(
15140 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
15141 ArrayRef<SourceLocation> MapTypeModifiersLoc,
15142 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
15143 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
15144 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
15145 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
15146 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
15147 OMPC_MAP_MODIFIER_unknown,
15148 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000015149 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
15150
15151 // Process map-type-modifiers, flag errors for duplicate modifiers.
15152 unsigned Count = 0;
15153 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
15154 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
15155 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
15156 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
15157 continue;
15158 }
15159 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000015160 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000015161 Modifiers[Count] = MapTypeModifiers[I];
15162 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
15163 ++Count;
15164 }
15165
Michael Kruse4304e9d2019-02-19 16:38:20 +000015166 MappableVarListInfo MVLI(VarList);
15167 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015168 MapperIdScopeSpec, MapperId, UnresolvedMappers,
15169 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000015170
Samuel Antao5de996e2016-01-22 20:21:36 +000015171 // We need to produce a map clause even if we don't have variables so that
15172 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000015173 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
15174 MVLI.VarBaseDeclarations, MVLI.VarComponents,
15175 MVLI.UDMapperList, Modifiers, ModifiersLoc,
15176 MapperIdScopeSpec.getWithLocInContext(Context),
15177 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000015178}
Kelvin Li099bb8c2015-11-24 20:50:12 +000015179
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015180QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
15181 TypeResult ParsedType) {
15182 assert(ParsedType.isUsable());
15183
15184 QualType ReductionType = GetTypeFromParser(ParsedType.get());
15185 if (ReductionType.isNull())
15186 return QualType();
15187
15188 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
15189 // A type name in a declare reduction directive cannot be a function type, an
15190 // array type, a reference type, or a type qualified with const, volatile or
15191 // restrict.
15192 if (ReductionType.hasQualifiers()) {
15193 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
15194 return QualType();
15195 }
15196
15197 if (ReductionType->isFunctionType()) {
15198 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
15199 return QualType();
15200 }
15201 if (ReductionType->isReferenceType()) {
15202 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
15203 return QualType();
15204 }
15205 if (ReductionType->isArrayType()) {
15206 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
15207 return QualType();
15208 }
15209 return ReductionType;
15210}
15211
15212Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
15213 Scope *S, DeclContext *DC, DeclarationName Name,
15214 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
15215 AccessSpecifier AS, Decl *PrevDeclInScope) {
15216 SmallVector<Decl *, 8> Decls;
15217 Decls.reserve(ReductionTypes.size());
15218
15219 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000015220 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015221 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
15222 // A reduction-identifier may not be re-declared in the current scope for the
15223 // same type or for a type that is compatible according to the base language
15224 // rules.
15225 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15226 OMPDeclareReductionDecl *PrevDRD = nullptr;
15227 bool InCompoundScope = true;
15228 if (S != nullptr) {
15229 // Find previous declaration with the same name not referenced in other
15230 // declarations.
15231 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15232 InCompoundScope =
15233 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15234 LookupName(Lookup, S);
15235 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15236 /*AllowInlineNamespace=*/false);
15237 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000015238 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015239 while (Filter.hasNext()) {
15240 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
15241 if (InCompoundScope) {
15242 auto I = UsedAsPrevious.find(PrevDecl);
15243 if (I == UsedAsPrevious.end())
15244 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000015245 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015246 UsedAsPrevious[D] = true;
15247 }
15248 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15249 PrevDecl->getLocation();
15250 }
15251 Filter.done();
15252 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015253 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015254 if (!PrevData.second) {
15255 PrevDRD = PrevData.first;
15256 break;
15257 }
15258 }
15259 }
15260 } else if (PrevDeclInScope != nullptr) {
15261 auto *PrevDRDInScope = PrevDRD =
15262 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
15263 do {
15264 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
15265 PrevDRDInScope->getLocation();
15266 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
15267 } while (PrevDRDInScope != nullptr);
15268 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015269 for (const auto &TyData : ReductionTypes) {
15270 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015271 bool Invalid = false;
15272 if (I != PreviousRedeclTypes.end()) {
15273 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
15274 << TyData.first;
15275 Diag(I->second, diag::note_previous_definition);
15276 Invalid = true;
15277 }
15278 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
15279 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
15280 Name, TyData.first, PrevDRD);
15281 DC->addDecl(DRD);
15282 DRD->setAccess(AS);
15283 Decls.push_back(DRD);
15284 if (Invalid)
15285 DRD->setInvalidDecl();
15286 else
15287 PrevDRD = DRD;
15288 }
15289
15290 return DeclGroupPtrTy::make(
15291 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
15292}
15293
15294void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
15295 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15296
15297 // Enter new function scope.
15298 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015299 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015300 getCurFunction()->setHasOMPDeclareReductionCombiner();
15301
15302 if (S != nullptr)
15303 PushDeclContext(S, DRD);
15304 else
15305 CurContext = DRD;
15306
Faisal Valid143a0c2017-04-01 21:30:49 +000015307 PushExpressionEvaluationContext(
15308 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015309
15310 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015311 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
15312 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
15313 // uses semantics of argument handles by value, but it should be passed by
15314 // reference. C lang does not support references, so pass all parameters as
15315 // pointers.
15316 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015317 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015318 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015319 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
15320 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
15321 // uses semantics of argument handles by value, but it should be passed by
15322 // reference. C lang does not support references, so pass all parameters as
15323 // pointers.
15324 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015325 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015326 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
15327 if (S != nullptr) {
15328 PushOnScopeChains(OmpInParm, S);
15329 PushOnScopeChains(OmpOutParm, S);
15330 } else {
15331 DRD->addDecl(OmpInParm);
15332 DRD->addDecl(OmpOutParm);
15333 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015334 Expr *InE =
15335 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
15336 Expr *OutE =
15337 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
15338 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015339}
15340
15341void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
15342 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15343 DiscardCleanupsInEvaluationContext();
15344 PopExpressionEvaluationContext();
15345
15346 PopDeclContext();
15347 PopFunctionScopeInfo();
15348
15349 if (Combiner != nullptr)
15350 DRD->setCombiner(Combiner);
15351 else
15352 DRD->setInvalidDecl();
15353}
15354
Alexey Bataev070f43a2017-09-06 14:49:58 +000015355VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015356 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15357
15358 // Enter new function scope.
15359 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000015360 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015361
15362 if (S != nullptr)
15363 PushDeclContext(S, DRD);
15364 else
15365 CurContext = DRD;
15366
Faisal Valid143a0c2017-04-01 21:30:49 +000015367 PushExpressionEvaluationContext(
15368 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015369
15370 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015371 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
15372 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
15373 // uses semantics of argument handles by value, but it should be passed by
15374 // reference. C lang does not support references, so pass all parameters as
15375 // pointers.
15376 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015377 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015378 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015379 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
15380 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
15381 // uses semantics of argument handles by value, but it should be passed by
15382 // reference. C lang does not support references, so pass all parameters as
15383 // pointers.
15384 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000015385 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000015386 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015387 if (S != nullptr) {
15388 PushOnScopeChains(OmpPrivParm, S);
15389 PushOnScopeChains(OmpOrigParm, S);
15390 } else {
15391 DRD->addDecl(OmpPrivParm);
15392 DRD->addDecl(OmpOrigParm);
15393 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000015394 Expr *OrigE =
15395 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
15396 Expr *PrivE =
15397 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
15398 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000015399 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015400}
15401
Alexey Bataev070f43a2017-09-06 14:49:58 +000015402void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
15403 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015404 auto *DRD = cast<OMPDeclareReductionDecl>(D);
15405 DiscardCleanupsInEvaluationContext();
15406 PopExpressionEvaluationContext();
15407
15408 PopDeclContext();
15409 PopFunctionScopeInfo();
15410
Alexey Bataev070f43a2017-09-06 14:49:58 +000015411 if (Initializer != nullptr) {
15412 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
15413 } else if (OmpPrivParm->hasInit()) {
15414 DRD->setInitializer(OmpPrivParm->getInit(),
15415 OmpPrivParm->isDirectInit()
15416 ? OMPDeclareReductionDecl::DirectInit
15417 : OMPDeclareReductionDecl::CopyInit);
15418 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015419 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000015420 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015421}
15422
15423Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
15424 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015425 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015426 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015427 if (S)
15428 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
15429 /*AddToContext=*/false);
15430 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015431 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000015432 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000015433 }
15434 return DeclReductions;
15435}
15436
Michael Kruse251e1482019-02-01 20:25:04 +000015437TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
15438 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15439 QualType T = TInfo->getType();
15440 if (D.isInvalidType())
15441 return true;
15442
15443 if (getLangOpts().CPlusPlus) {
15444 // Check that there are no default arguments (C++ only).
15445 CheckExtraCXXDefaultArguments(D);
15446 }
15447
15448 return CreateParsedType(T, TInfo);
15449}
15450
15451QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
15452 TypeResult ParsedType) {
15453 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
15454
15455 QualType MapperType = GetTypeFromParser(ParsedType.get());
15456 assert(!MapperType.isNull() && "Expect valid mapper type");
15457
15458 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15459 // The type must be of struct, union or class type in C and C++
15460 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
15461 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
15462 return QualType();
15463 }
15464 return MapperType;
15465}
15466
15467OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
15468 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
15469 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
15470 Decl *PrevDeclInScope) {
15471 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
15472 forRedeclarationInCurContext());
15473 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15474 // A mapper-identifier may not be redeclared in the current scope for the
15475 // same type or for a type that is compatible according to the base language
15476 // rules.
15477 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
15478 OMPDeclareMapperDecl *PrevDMD = nullptr;
15479 bool InCompoundScope = true;
15480 if (S != nullptr) {
15481 // Find previous declaration with the same name not referenced in other
15482 // declarations.
15483 FunctionScopeInfo *ParentFn = getEnclosingFunction();
15484 InCompoundScope =
15485 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
15486 LookupName(Lookup, S);
15487 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
15488 /*AllowInlineNamespace=*/false);
15489 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
15490 LookupResult::Filter Filter = Lookup.makeFilter();
15491 while (Filter.hasNext()) {
15492 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
15493 if (InCompoundScope) {
15494 auto I = UsedAsPrevious.find(PrevDecl);
15495 if (I == UsedAsPrevious.end())
15496 UsedAsPrevious[PrevDecl] = false;
15497 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
15498 UsedAsPrevious[D] = true;
15499 }
15500 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
15501 PrevDecl->getLocation();
15502 }
15503 Filter.done();
15504 if (InCompoundScope) {
15505 for (const auto &PrevData : UsedAsPrevious) {
15506 if (!PrevData.second) {
15507 PrevDMD = PrevData.first;
15508 break;
15509 }
15510 }
15511 }
15512 } else if (PrevDeclInScope) {
15513 auto *PrevDMDInScope = PrevDMD =
15514 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
15515 do {
15516 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
15517 PrevDMDInScope->getLocation();
15518 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
15519 } while (PrevDMDInScope != nullptr);
15520 }
15521 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
15522 bool Invalid = false;
15523 if (I != PreviousRedeclTypes.end()) {
15524 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
15525 << MapperType << Name;
15526 Diag(I->second, diag::note_previous_definition);
15527 Invalid = true;
15528 }
15529 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
15530 MapperType, VN, PrevDMD);
15531 DC->addDecl(DMD);
15532 DMD->setAccess(AS);
15533 if (Invalid)
15534 DMD->setInvalidDecl();
15535
15536 // Enter new function scope.
15537 PushFunctionScope();
15538 setFunctionHasBranchProtectedScope();
15539
15540 CurContext = DMD;
15541
15542 return DMD;
15543}
15544
15545void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
15546 Scope *S,
15547 QualType MapperType,
15548 SourceLocation StartLoc,
15549 DeclarationName VN) {
15550 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
15551 if (S)
15552 PushOnScopeChains(VD, S);
15553 else
15554 DMD->addDecl(VD);
15555 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
15556 DMD->setMapperVarRef(MapperVarRefExpr);
15557}
15558
15559Sema::DeclGroupPtrTy
15560Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
15561 ArrayRef<OMPClause *> ClauseList) {
15562 PopDeclContext();
15563 PopFunctionScopeInfo();
15564
15565 if (D) {
15566 if (S)
15567 PushOnScopeChains(D, S, /*AddToContext=*/false);
15568 D->CreateClauses(Context, ClauseList);
15569 }
15570
15571 return DeclGroupPtrTy::make(DeclGroupRef(D));
15572}
15573
David Majnemer9d168222016-08-05 17:44:54 +000015574OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000015575 SourceLocation StartLoc,
15576 SourceLocation LParenLoc,
15577 SourceLocation EndLoc) {
15578 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015579 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015580
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015581 // OpenMP [teams Constrcut, Restrictions]
15582 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015583 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000015584 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015585 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000015586
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015587 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015588 OpenMPDirectiveKind CaptureRegion =
15589 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
15590 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015591 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015592 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000015593 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15594 HelperValStmt = buildPreInits(Context, Captures);
15595 }
15596
15597 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
15598 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000015599}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015600
15601OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
15602 SourceLocation StartLoc,
15603 SourceLocation LParenLoc,
15604 SourceLocation EndLoc) {
15605 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015606 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015607
15608 // OpenMP [teams Constrcut, Restrictions]
15609 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015610 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000015611 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015612 return nullptr;
15613
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015614 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015615 OpenMPDirectiveKind CaptureRegion =
15616 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
15617 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015618 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015619 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000015620 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15621 HelperValStmt = buildPreInits(Context, Captures);
15622 }
15623
15624 return new (Context) OMPThreadLimitClause(
15625 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015626}
Alexey Bataeva0569352015-12-01 10:17:31 +000015627
15628OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
15629 SourceLocation StartLoc,
15630 SourceLocation LParenLoc,
15631 SourceLocation EndLoc) {
15632 Expr *ValExpr = Priority;
15633
15634 // OpenMP [2.9.1, task Constrcut]
15635 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015636 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000015637 /*StrictlyPositive=*/false))
15638 return nullptr;
15639
15640 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15641}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015642
15643OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
15644 SourceLocation StartLoc,
15645 SourceLocation LParenLoc,
15646 SourceLocation EndLoc) {
15647 Expr *ValExpr = Grainsize;
15648
15649 // OpenMP [2.9.2, taskloop Constrcut]
15650 // The parameter of the grainsize clause must be a positive integer
15651 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015652 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000015653 /*StrictlyPositive=*/true))
15654 return nullptr;
15655
15656 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15657}
Alexey Bataev382967a2015-12-08 12:06:20 +000015658
15659OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
15660 SourceLocation StartLoc,
15661 SourceLocation LParenLoc,
15662 SourceLocation EndLoc) {
15663 Expr *ValExpr = NumTasks;
15664
15665 // OpenMP [2.9.2, taskloop Constrcut]
15666 // The parameter of the num_tasks clause must be a positive integer
15667 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015668 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000015669 /*StrictlyPositive=*/true))
15670 return nullptr;
15671
15672 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
15673}
15674
Alexey Bataev28c75412015-12-15 08:19:24 +000015675OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
15676 SourceLocation LParenLoc,
15677 SourceLocation EndLoc) {
15678 // OpenMP [2.13.2, critical construct, Description]
15679 // ... where hint-expression is an integer constant expression that evaluates
15680 // to a valid lock hint.
15681 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
15682 if (HintExpr.isInvalid())
15683 return nullptr;
15684 return new (Context)
15685 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
15686}
15687
Carlo Bertollib4adf552016-01-15 18:50:31 +000015688OMPClause *Sema::ActOnOpenMPDistScheduleClause(
15689 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
15690 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
15691 SourceLocation EndLoc) {
15692 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
15693 std::string Values;
15694 Values += "'";
15695 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
15696 Values += "'";
15697 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
15698 << Values << getOpenMPClauseName(OMPC_dist_schedule);
15699 return nullptr;
15700 }
15701 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000015702 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000015703 if (ChunkSize) {
15704 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
15705 !ChunkSize->isInstantiationDependent() &&
15706 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015707 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000015708 ExprResult Val =
15709 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
15710 if (Val.isInvalid())
15711 return nullptr;
15712
15713 ValExpr = Val.get();
15714
15715 // OpenMP [2.7.1, Restrictions]
15716 // chunk_size must be a loop invariant integer expression with a positive
15717 // value.
15718 llvm::APSInt Result;
15719 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
15720 if (Result.isSigned() && !Result.isStrictlyPositive()) {
15721 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
15722 << "dist_schedule" << ChunkSize->getSourceRange();
15723 return nullptr;
15724 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000015725 } else if (getOpenMPCaptureRegionForClause(
15726 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
15727 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000015728 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015729 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015730 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000015731 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15732 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000015733 }
15734 }
15735 }
15736
15737 return new (Context)
15738 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000015739 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000015740}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015741
15742OMPClause *Sema::ActOnOpenMPDefaultmapClause(
15743 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
15744 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
15745 SourceLocation KindLoc, SourceLocation EndLoc) {
15746 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000015747 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015748 std::string Value;
15749 SourceLocation Loc;
15750 Value += "'";
15751 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
15752 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000015753 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015754 Loc = MLoc;
15755 } else {
15756 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000015757 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015758 Loc = KindLoc;
15759 }
15760 Value += "'";
15761 Diag(Loc, diag::err_omp_unexpected_clause_value)
15762 << Value << getOpenMPClauseName(OMPC_defaultmap);
15763 return nullptr;
15764 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000015765 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000015766
15767 return new (Context)
15768 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
15769}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015770
15771bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
15772 DeclContext *CurLexicalContext = getCurLexicalContext();
15773 if (!CurLexicalContext->isFileContext() &&
15774 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000015775 !CurLexicalContext->isExternCXXContext() &&
15776 !isa<CXXRecordDecl>(CurLexicalContext) &&
15777 !isa<ClassTemplateDecl>(CurLexicalContext) &&
15778 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
15779 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015780 Diag(Loc, diag::err_omp_region_not_file_context);
15781 return false;
15782 }
Kelvin Libc38e632018-09-10 02:07:09 +000015783 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015784 return true;
15785}
15786
15787void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000015788 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015789 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000015790 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015791}
15792
Alexey Bataev729e2422019-08-23 16:11:14 +000015793NamedDecl *
15794Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
15795 const DeclarationNameInfo &Id,
15796 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015797 LookupResult Lookup(*this, Id, LookupOrdinaryName);
15798 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
15799
15800 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000015801 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015802 Lookup.suppressDiagnostics();
15803
15804 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000015805 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015806 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000015807 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015808 CTK_ErrorRecovery)) {
15809 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
15810 << Id.getName());
15811 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000015812 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015813 }
15814
15815 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000015816 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015817 }
15818
15819 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000015820 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
15821 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015822 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000015823 return nullptr;
15824 }
15825 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
15826 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
15827 return ND;
15828}
15829
15830void Sema::ActOnOpenMPDeclareTargetName(
15831 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
15832 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
15833 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
15834 isa<FunctionTemplateDecl>(ND)) &&
15835 "Expected variable, function or function template.");
15836
15837 // Diagnose marking after use as it may lead to incorrect diagnosis and
15838 // codegen.
15839 if (LangOpts.OpenMP >= 50 &&
15840 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
15841 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
15842
15843 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
15844 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
15845 if (DevTy.hasValue() && *DevTy != DT) {
15846 Diag(Loc, diag::err_omp_device_type_mismatch)
15847 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
15848 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
15849 return;
15850 }
15851 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
15852 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
15853 if (!Res) {
15854 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
15855 SourceRange(Loc, Loc));
15856 ND->addAttr(A);
15857 if (ASTMutationListener *ML = Context.getASTMutationListener())
15858 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
15859 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
15860 } else if (*Res != MT) {
15861 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000015862 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000015863}
15864
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015865static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
15866 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000015867 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015868 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000015869 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000015870 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
15871 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
15872 if (SemaRef.LangOpts.OpenMP >= 50 &&
15873 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
15874 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
15875 VD->hasGlobalStorage()) {
15876 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
15877 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
15878 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
15879 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
15880 // If a lambda declaration and definition appears between a
15881 // declare target directive and the matching end declare target
15882 // directive, all variables that are captured by the lambda
15883 // expression must also appear in a to clause.
15884 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000015885 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000015886 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
15887 << VD << 0 << SR;
15888 return;
15889 }
15890 }
15891 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000015892 return;
15893 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
15894 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015895}
15896
15897static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
15898 Sema &SemaRef, DSAStackTy *Stack,
15899 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000015900 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015901 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
15902 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015903}
15904
Kelvin Li1ce87c72017-12-12 20:08:12 +000015905void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
15906 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015907 if (!D || D->isInvalidDecl())
15908 return;
15909 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000015910 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000015911 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000015912 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000015913 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
15914 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000015915 return;
15916 // 2.10.6: threadprivate variable cannot appear in a declare target
15917 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015918 if (DSAStack->isThreadPrivate(VD)) {
15919 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000015920 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015921 return;
15922 }
15923 }
Alexey Bataev97b72212018-08-14 18:31:20 +000015924 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
15925 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015926 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000015927 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
15928 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015929 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000015930 Diag(IdLoc, diag::err_omp_function_in_link_clause);
15931 Diag(FD->getLocation(), diag::note_defined_here) << FD;
15932 return;
15933 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015934 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000015935 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
15936 OMPDeclareTargetDeclAttr::getDeviceType(FD);
15937 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
15938 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000015939 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000015940 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
15941 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
15942 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000015943 }
Alexey Bataev30a78212018-09-11 13:59:10 +000015944 if (auto *VD = dyn_cast<ValueDecl>(D)) {
15945 // Problem if any with var declared with incomplete type will be reported
15946 // as normal, so no need to check it here.
15947 if ((E || !VD->getType()->isIncompleteType()) &&
15948 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
15949 return;
15950 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
15951 // Checking declaration inside declare target region.
15952 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
15953 isa<FunctionTemplateDecl>(D)) {
15954 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000015955 Context, OMPDeclareTargetDeclAttr::MT_To,
15956 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000015957 D->addAttr(A);
15958 if (ASTMutationListener *ML = Context.getASTMutationListener())
15959 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
15960 }
15961 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015962 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015963 }
Alexey Bataev30a78212018-09-11 13:59:10 +000015964 if (!E)
15965 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000015966 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
15967}
Samuel Antao661c0902016-05-26 17:39:58 +000015968
15969OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000015970 CXXScopeSpec &MapperIdScopeSpec,
15971 DeclarationNameInfo &MapperId,
15972 const OMPVarListLocTy &Locs,
15973 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000015974 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015975 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
15976 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000015977 if (MVLI.ProcessedVarList.empty())
15978 return nullptr;
15979
Michael Kruse01f670d2019-02-22 22:29:42 +000015980 return OMPToClause::Create(
15981 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15982 MVLI.VarComponents, MVLI.UDMapperList,
15983 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000015984}
Samuel Antaoec172c62016-05-26 17:49:04 +000015985
15986OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000015987 CXXScopeSpec &MapperIdScopeSpec,
15988 DeclarationNameInfo &MapperId,
15989 const OMPVarListLocTy &Locs,
15990 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015991 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000015992 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
15993 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000015994 if (MVLI.ProcessedVarList.empty())
15995 return nullptr;
15996
Michael Kruse0336c752019-02-25 20:34:15 +000015997 return OMPFromClause::Create(
15998 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
15999 MVLI.VarComponents, MVLI.UDMapperList,
16000 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000016001}
Carlo Bertolli2404b172016-07-13 15:37:16 +000016002
16003OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016004 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000016005 MappableVarListInfo MVLI(VarList);
16006 SmallVector<Expr *, 8> PrivateCopies;
16007 SmallVector<Expr *, 8> Inits;
16008
Alexey Bataeve3727102018-04-18 15:57:46 +000016009 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016010 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
16011 SourceLocation ELoc;
16012 SourceRange ERange;
16013 Expr *SimpleRefExpr = RefExpr;
16014 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16015 if (Res.second) {
16016 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000016017 MVLI.ProcessedVarList.push_back(RefExpr);
16018 PrivateCopies.push_back(nullptr);
16019 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016020 }
16021 ValueDecl *D = Res.first;
16022 if (!D)
16023 continue;
16024
16025 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000016026 Type = Type.getNonReferenceType().getUnqualifiedType();
16027
16028 auto *VD = dyn_cast<VarDecl>(D);
16029
16030 // Item should be a pointer or reference to pointer.
16031 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000016032 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
16033 << 0 << RefExpr->getSourceRange();
16034 continue;
16035 }
Samuel Antaocc10b852016-07-28 14:23:26 +000016036
16037 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000016038 auto VDPrivate =
16039 buildVarDecl(*this, ELoc, Type, D->getName(),
16040 D->hasAttrs() ? &D->getAttrs() : nullptr,
16041 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000016042 if (VDPrivate->isInvalidDecl())
16043 continue;
16044
16045 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000016046 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000016047 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
16048
16049 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000016050 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000016051 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000016052 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
16053 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000016054 AddInitializerToDecl(VDPrivate,
16055 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000016056 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000016057
16058 // If required, build a capture to implement the privatization initialized
16059 // with the current list item value.
16060 DeclRefExpr *Ref = nullptr;
16061 if (!VD)
16062 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
16063 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
16064 PrivateCopies.push_back(VDPrivateRefExpr);
16065 Inits.push_back(VDInitRefExpr);
16066
16067 // We need to add a data sharing attribute for this variable to make sure it
16068 // is correctly captured. A variable that shows up in a use_device_ptr has
16069 // similar properties of a first private variable.
16070 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
16071
16072 // Create a mappable component for the list item. List items in this clause
16073 // only need a component.
16074 MVLI.VarBaseDeclarations.push_back(D);
16075 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16076 MVLI.VarComponents.back().push_back(
16077 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000016078 }
16079
Samuel Antaocc10b852016-07-28 14:23:26 +000016080 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000016081 return nullptr;
16082
Samuel Antaocc10b852016-07-28 14:23:26 +000016083 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000016084 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
16085 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000016086}
Carlo Bertolli70594e92016-07-13 17:16:49 +000016087
16088OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000016089 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000016090 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000016091 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000016092 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000016093 SourceLocation ELoc;
16094 SourceRange ERange;
16095 Expr *SimpleRefExpr = RefExpr;
16096 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16097 if (Res.second) {
16098 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000016099 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016100 }
16101 ValueDecl *D = Res.first;
16102 if (!D)
16103 continue;
16104
16105 QualType Type = D->getType();
16106 // item should be a pointer or array or reference to pointer or array
16107 if (!Type.getNonReferenceType()->isPointerType() &&
16108 !Type.getNonReferenceType()->isArrayType()) {
16109 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
16110 << 0 << RefExpr->getSourceRange();
16111 continue;
16112 }
Samuel Antao6890b092016-07-28 14:25:09 +000016113
16114 // Check if the declaration in the clause does not show up in any data
16115 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000016116 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000016117 if (isOpenMPPrivate(DVar.CKind)) {
16118 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
16119 << getOpenMPClauseName(DVar.CKind)
16120 << getOpenMPClauseName(OMPC_is_device_ptr)
16121 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016122 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000016123 continue;
16124 }
16125
Alexey Bataeve3727102018-04-18 15:57:46 +000016126 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000016127 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000016128 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000016129 [&ConflictExpr](
16130 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
16131 OpenMPClauseKind) -> bool {
16132 ConflictExpr = R.front().getAssociatedExpression();
16133 return true;
16134 })) {
16135 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
16136 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
16137 << ConflictExpr->getSourceRange();
16138 continue;
16139 }
16140
16141 // Store the components in the stack so that they can be used to check
16142 // against other clauses later on.
16143 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
16144 DSAStack->addMappableExpressionComponents(
16145 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
16146
16147 // Record the expression we've just processed.
16148 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
16149
16150 // Create a mappable component for the list item. List items in this clause
16151 // only need a component. We use a null declaration to signal fields in
16152 // 'this'.
16153 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
16154 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
16155 "Unexpected device pointer expression!");
16156 MVLI.VarBaseDeclarations.push_back(
16157 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
16158 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16159 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016160 }
16161
Samuel Antao6890b092016-07-28 14:25:09 +000016162 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000016163 return nullptr;
16164
Michael Kruse4304e9d2019-02-19 16:38:20 +000016165 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
16166 MVLI.VarBaseDeclarations,
16167 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000016168}
Alexey Bataeve04483e2019-03-27 14:14:31 +000016169
16170OMPClause *Sema::ActOnOpenMPAllocateClause(
16171 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
16172 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
16173 if (Allocator) {
16174 // OpenMP [2.11.4 allocate Clause, Description]
16175 // allocator is an expression of omp_allocator_handle_t type.
16176 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
16177 return nullptr;
16178
16179 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
16180 if (AllocatorRes.isInvalid())
16181 return nullptr;
16182 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
16183 DSAStack->getOMPAllocatorHandleT(),
16184 Sema::AA_Initializing,
16185 /*AllowExplicit=*/true);
16186 if (AllocatorRes.isInvalid())
16187 return nullptr;
16188 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000016189 } else {
16190 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
16191 // allocate clauses that appear on a target construct or on constructs in a
16192 // target region must specify an allocator expression unless a requires
16193 // directive with the dynamic_allocators clause is present in the same
16194 // compilation unit.
16195 if (LangOpts.OpenMPIsDevice &&
16196 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
16197 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000016198 }
16199 // Analyze and build list of variables.
16200 SmallVector<Expr *, 8> Vars;
16201 for (Expr *RefExpr : VarList) {
16202 assert(RefExpr && "NULL expr in OpenMP private clause.");
16203 SourceLocation ELoc;
16204 SourceRange ERange;
16205 Expr *SimpleRefExpr = RefExpr;
16206 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
16207 if (Res.second) {
16208 // It will be analyzed later.
16209 Vars.push_back(RefExpr);
16210 }
16211 ValueDecl *D = Res.first;
16212 if (!D)
16213 continue;
16214
16215 auto *VD = dyn_cast<VarDecl>(D);
16216 DeclRefExpr *Ref = nullptr;
16217 if (!VD && !CurContext->isDependentContext())
16218 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
16219 Vars.push_back((VD || CurContext->isDependentContext())
16220 ? RefExpr->IgnoreParens()
16221 : Ref);
16222 }
16223
16224 if (Vars.empty())
16225 return nullptr;
16226
16227 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
16228 ColonLoc, EndLoc, Vars);
16229}